BfExprEvaluator.cpp 753 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170
  1. #pragma warning(push)
  2. #pragma warning(disable:4800)
  3. #pragma warning(disable:4244)
  4. #pragma warning(disable:4141)
  5. #pragma warning(disable:4624)
  6. #pragma warning(disable:4146)
  7. #pragma warning(disable:4267)
  8. #pragma warning(disable:4291)
  9. #include "BfExprEvaluator.h"
  10. #include "BfConstResolver.h"
  11. #include "BfAutoComplete.h"
  12. #include "BeefySysLib/util/PerfTimer.h"
  13. #include "BeefySysLib/util/BeefPerf.h"
  14. #include "BfParser.h"
  15. #include "BfMangler.h"
  16. #include "BfResolvePass.h"
  17. #include "BfUtil.h"
  18. #include "BfDeferEvalChecker.h"
  19. #include "BfVarDeclChecker.h"
  20. #include "BfFixits.h"
  21. #include "CeMachine.h"
  22. #pragma warning(pop)
  23. #pragma warning(disable:4996)
  24. #include "BeefySysLib/util/AllocDebug.h"
  25. USING_NS_BF;
  26. using namespace llvm;
  27. //////////////////////////////////////////////////////////////////////////
  28. DeferredTupleAssignData::~DeferredTupleAssignData()
  29. {
  30. for (auto entry : mChildren)
  31. {
  32. delete entry.mExprEvaluator;
  33. delete entry.mInnerTuple;
  34. }
  35. }
  36. //////////////////////////////////////////////////////////////////////////
  37. BfBaseClassWalker::BfBaseClassWalker(BfType* typeA, BfType* typeB, BfModule* module)
  38. {
  39. mMayBeFromInterface = false;
  40. if (typeB == typeA)
  41. typeB = NULL;
  42. if ((typeA != NULL) && (!typeA->IsInterface()))
  43. mTypes[0] = typeA->ToTypeInstance();
  44. else
  45. mTypes[0] = NULL;
  46. if ((typeB != NULL) && (!typeB->IsInterface()))
  47. mTypes[1] = typeB->ToTypeInstance();
  48. else
  49. mTypes[1] = NULL;
  50. if ((typeA != NULL) && (typeA->IsGenericParam()))
  51. {
  52. mMayBeFromInterface = true;
  53. AddConstraints(typeA, module->GetGenericParamInstance((BfGenericParamType*)typeA));
  54. }
  55. if ((typeB != NULL) && (typeB->IsGenericParam()))
  56. {
  57. mMayBeFromInterface = true;
  58. AddConstraints(typeB, module->GetGenericParamInstance((BfGenericParamType*)typeB));
  59. }
  60. }
  61. /*BfBaseClassWalker::BfBaseClassWalker(BfTypeInstance* typeA, BfTypeInstance* typeB)
  62. {
  63. mTypes[0] = typeA;
  64. mTypes[1] = typeB;
  65. }*/
  66. BfBaseClassWalker::BfBaseClassWalker()
  67. {
  68. mMayBeFromInterface = false;
  69. mTypes[0] = NULL;
  70. mTypes[1] = NULL;
  71. }
  72. void BfBaseClassWalker::AddConstraints(BfType* srcType, BfGenericParamInstance* genericParam)
  73. {
  74. if (genericParam->mTypeConstraint != NULL)
  75. {
  76. auto typeInst = genericParam->mTypeConstraint->ToTypeInstance();
  77. {
  78. Entry entry(srcType, typeInst);
  79. if ((typeInst != NULL) && (!mManualList.Contains(entry)))
  80. mManualList.Add(entry);
  81. }
  82. }
  83. for (auto typeInst : genericParam->mInterfaceConstraints)
  84. {
  85. Entry entry(srcType, typeInst);
  86. if ((typeInst != NULL) && (!mManualList.Contains(entry)))
  87. mManualList.Add(entry);
  88. }
  89. }
  90. BfBaseClassWalker::Entry BfBaseClassWalker::Next()
  91. {
  92. if (!mManualList.IsEmpty())
  93. {
  94. auto entry = mManualList.back();
  95. mManualList.pop_back();
  96. return entry;
  97. }
  98. // Check the most specific type instance first (highest inheritance level)
  99. auto checkInstance = mTypes[0];
  100. if (mTypes[0] == NULL)
  101. checkInstance = mTypes[1];
  102. else if ((mTypes[1] != NULL) && (mTypes[1]->mInheritDepth > mTypes[0]->mInheritDepth))
  103. checkInstance = mTypes[1];
  104. if (checkInstance == NULL)
  105. return Entry();
  106. // Do it this was so if we reach the same base class for both types that we only handle each base type once
  107. if (checkInstance == mTypes[0])
  108. mTypes[0] = checkInstance->mBaseType;
  109. if (checkInstance == mTypes[1])
  110. mTypes[1] = checkInstance->mBaseType;
  111. Entry entry;
  112. entry.mSrcType = checkInstance;
  113. entry.mTypeInstance = checkInstance;
  114. return entry;
  115. }
  116. //////////////////////////////////////////////////////////////////////////
  117. BfMethodMatcher::BfMethodMatcher(BfAstNode* targetSrc, BfModule* module, const StringImpl& methodName, SizedArrayImpl<BfResolvedArg>& arguments, BfSizedArray<ASTREF(BfTypeReference*)>* methodGenericArguments) :
  118. mArguments(arguments)
  119. {
  120. mTargetSrc = targetSrc;
  121. mModule = module;
  122. mMethodName = methodName;
  123. Init(/*arguments, */methodGenericArguments);
  124. }
  125. BfMethodMatcher::BfMethodMatcher(BfAstNode* targetSrc, BfModule* module, BfMethodInstance* interfaceMethodInstance, SizedArrayImpl<BfResolvedArg>& arguments, BfSizedArray<ASTREF(BfTypeReference*)>* methodGenericArguments) :
  126. mArguments(arguments)
  127. {
  128. mTargetSrc = targetSrc;
  129. mModule = module;
  130. Init(/*arguments, */methodGenericArguments);
  131. mInterfaceMethodInstance = interfaceMethodInstance;
  132. mMethodName = mInterfaceMethodInstance->mMethodDef->mName;
  133. }
  134. void BfMethodMatcher::Init(/*SizedArrayImpl<BfResolvedArg>& arguments, */BfSizedArray<ASTREF(BfTypeReference*)>* methodGenericArguments)
  135. {
  136. //mArguments = arguments;
  137. mActiveTypeDef = NULL;
  138. mBestMethodDef = NULL;
  139. mBackupMethodDef = NULL;
  140. mBackupMatchKind = BackupMatchKind_None;
  141. mBestRawMethodInstance = NULL;
  142. mBestMethodTypeInstance = NULL;
  143. mExplicitInterfaceCheck = NULL;
  144. mSelfType = NULL;
  145. mMethodType = BfMethodType_Normal;
  146. mHadExplicitGenericArguments = false;
  147. mHasVarArguments = false;
  148. mInterfaceMethodInstance = NULL;
  149. mFakeConcreteTarget = false;
  150. mBypassVirtual = false;
  151. mAllowStatic = true;
  152. mAllowNonStatic = true;
  153. mSkipImplicitParams = false;
  154. mAllowImplicitThis = false;
  155. mAllowImplicitRef = false;
  156. mHadVarConflictingReturnType = false;
  157. mAutoFlushAmbiguityErrors = true;
  158. mMethodCheckCount = 0;
  159. mCheckedKind = BfCheckedKind_NotSet;
  160. mMatchFailKind = MatchFailKind_None;
  161. mBfEvalExprFlags = BfEvalExprFlags_None;
  162. for (auto& arg : mArguments)
  163. {
  164. auto bfType = arg.mTypedValue.mType;
  165. if (bfType != NULL)
  166. {
  167. mHasVarArguments |= bfType->IsVar();
  168. if (bfType->IsGenericParam())
  169. {
  170. auto genericParamInstance = mModule->GetGenericParamInstance((BfGenericParamType*)bfType);
  171. if ((genericParamInstance->mGenericParamFlags & BfGenericParamFlag_Var) != 0)
  172. mHasVarArguments = true;
  173. }
  174. }
  175. }
  176. if (methodGenericArguments != NULL)
  177. {
  178. for (BfTypeReference* genericArg : *methodGenericArguments)
  179. {
  180. auto genericArgType = mModule->ResolveTypeRef(genericArg);
  181. if ((genericArgType != NULL) && (genericArgType->IsGenericParam()))
  182. {
  183. auto genericParamInstance = mModule->GetGenericParamInstance((BfGenericParamType*)genericArgType);
  184. if ((genericParamInstance->mGenericParamFlags & BfGenericParamFlag_Var) != 0)
  185. mHasVarArguments = true;
  186. }
  187. mExplicitMethodGenericArguments.push_back(genericArgType);
  188. }
  189. mHadExplicitGenericArguments = true;
  190. }
  191. }
  192. bool BfMethodMatcher::IsMemberAccessible(BfTypeInstance* typeInst, BfTypeDef* declaringType)
  193. {
  194. if (!declaringType->mIsPartial)
  195. return true;
  196. if (mActiveTypeDef == NULL)
  197. mActiveTypeDef = mModule->GetActiveTypeDef();
  198. // Note that mActiveTypeDef does not pose a constraint here
  199. if (!typeInst->IsTypeMemberIncluded(declaringType, mActiveTypeDef, mModule))
  200. return false;
  201. auto visibleProjectSet = mModule->GetVisibleProjectSet();
  202. if ((visibleProjectSet != NULL) && (!typeInst->IsTypeMemberAccessible(declaringType, visibleProjectSet)))
  203. {
  204. return false;
  205. }
  206. return true;
  207. }
  208. bool BfGenericInferContext::InferGenericArgument(BfMethodInstance* methodInstance, BfType* argType, BfType* wantType, BfIRValue argValue)
  209. {
  210. if (argType == NULL)
  211. return false;
  212. if (!wantType->IsUnspecializedType())
  213. return true;
  214. bool alreadyChecked = false;
  215. auto _AddToCheckedSet = [](BfType* type, HashSet<BfType*>& checkedTypeSet, bool& alreadyChecked)
  216. {
  217. if (alreadyChecked)
  218. return true;
  219. alreadyChecked = true;
  220. return checkedTypeSet.Add(type);
  221. };
  222. if (wantType->IsGenericParam())
  223. {
  224. auto wantGenericParam = (BfGenericParamType*)wantType;
  225. BfType* methodGenericTypeConstraint = NULL;
  226. auto _SetGeneric = [&]()
  227. {
  228. if (argType != NULL)
  229. {
  230. // Disallow illegal types
  231. if (argType->IsRef())
  232. return;
  233. if (argType->IsNull())
  234. return;
  235. }
  236. if ((*mCheckMethodGenericArguments)[wantGenericParam->mGenericParamIdx] != argType)
  237. {
  238. if (methodGenericTypeConstraint != NULL)
  239. {
  240. if (methodGenericTypeConstraint->IsGenericTypeInstance())
  241. {
  242. auto wantGenericType = (BfTypeInstance*)methodGenericTypeConstraint;
  243. auto checkArgType = argType;
  244. while (checkArgType != NULL)
  245. {
  246. if (checkArgType->IsGenericTypeInstance())
  247. {
  248. auto argGenericType = (BfTypeInstance*)checkArgType;
  249. if (argGenericType->mTypeDef == wantGenericType->mTypeDef)
  250. {
  251. for (int genericArgIdx = 0; genericArgIdx < (int)argGenericType->mGenericTypeInfo->mTypeGenericArguments.size(); genericArgIdx++)
  252. InferGenericArgument(methodInstance, argGenericType->mGenericTypeInfo->mTypeGenericArguments[genericArgIdx], wantGenericType->mGenericTypeInfo->mTypeGenericArguments[genericArgIdx], BfIRValue());
  253. }
  254. }
  255. else if (checkArgType->IsSizedArray())
  256. {
  257. auto sizedArrayType = (BfSizedArrayType*)checkArgType;
  258. if (wantGenericType->mTypeDef == mModule->mCompiler->mSizedArrayTypeDef)
  259. {
  260. InferGenericArgument(methodInstance, sizedArrayType->mElementType, wantGenericType->mGenericTypeInfo->mTypeGenericArguments[0], BfIRValue());
  261. auto intType = mModule->GetPrimitiveType(BfTypeCode_IntPtr);
  262. BfTypedValue arraySize = BfTypedValue(mModule->mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, (uint64)sizedArrayType->mElementCount), intType);
  263. InferGenericArgument(methodInstance, mModule->CreateConstExprValueType(arraySize), wantGenericType->mGenericTypeInfo->mTypeGenericArguments[1], BfIRValue());
  264. }
  265. }
  266. else if (checkArgType->IsPointer())
  267. {
  268. auto pointerType = (BfPointerType*)checkArgType;
  269. if (wantGenericType->mTypeDef == mModule->mCompiler->mPointerTTypeDef)
  270. {
  271. InferGenericArgument(methodInstance, pointerType->mElementType, wantGenericType->mGenericTypeInfo->mTypeGenericArguments[0], BfIRValue());
  272. }
  273. }
  274. auto checkTypeInst = checkArgType->ToTypeInstance();
  275. if ((checkTypeInst == NULL) || (!checkTypeInst->mHasParameterizedBase))
  276. break;
  277. checkArgType = checkTypeInst->mBaseType;
  278. }
  279. }
  280. }
  281. }
  282. if ((*mCheckMethodGenericArguments)[wantGenericParam->mGenericParamIdx] == NULL)
  283. mInferredCount++;
  284. (*mCheckMethodGenericArguments)[wantGenericParam->mGenericParamIdx] = argType;
  285. if (!mPrevArgValues.IsEmpty())
  286. mPrevArgValues[wantGenericParam->mGenericParamIdx] = argValue;
  287. };
  288. if (argType->IsVar())
  289. {
  290. _SetGeneric();
  291. return true;
  292. }
  293. if (wantGenericParam->mGenericParamKind == BfGenericParamKind_Method)
  294. {
  295. auto genericParamInst = methodInstance->mMethodInfoEx->mGenericParams[wantGenericParam->mGenericParamIdx];
  296. methodGenericTypeConstraint = genericParamInst->mTypeConstraint;
  297. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_Const) != 0)
  298. {
  299. if (argValue.IsConst())
  300. {
  301. argType = mModule->CreateConstExprValueType(BfTypedValue(argValue, argType));
  302. }
  303. else if (!argType->IsConstExprValue())
  304. {
  305. return false;
  306. }
  307. }
  308. if (argType == mModule->mContext->mBfObjectType)
  309. {
  310. if ((genericParamInst->mTypeConstraint != NULL) && (genericParamInst->mTypeConstraint->IsDelegate()))
  311. {
  312. argType = mModule->ResolveGenericType(genericParamInst->mTypeConstraint, NULL, mCheckMethodGenericArguments);
  313. if (argType == NULL)
  314. return true;
  315. }
  316. }
  317. if (mPrevArgValues.IsEmpty())
  318. {
  319. _SetGeneric();
  320. return true;
  321. }
  322. auto prevGenericMethodArg = (*mCheckMethodGenericArguments)[wantGenericParam->mGenericParamIdx];
  323. auto prevArgValue = mPrevArgValues[wantGenericParam->mGenericParamIdx];
  324. if (prevGenericMethodArg == NULL)
  325. {
  326. _SetGeneric();
  327. return true;
  328. }
  329. if ((prevGenericMethodArg->IsIntUnknown()) && (!argType->IsIntUnknown()))
  330. {
  331. // Old int fits into new argType, that's good
  332. if (mModule->CanCast(BfTypedValue(prevArgValue, prevGenericMethodArg), argType))
  333. {
  334. _SetGeneric();
  335. return true;
  336. }
  337. // Doesn't fit, upgrade type to 'int'
  338. argType = mModule->GetPrimitiveType(BfTypeCode_IntPtr);
  339. if (mModule->CanCast(BfTypedValue(prevArgValue, prevGenericMethodArg), argType))
  340. {
  341. _SetGeneric();
  342. return true;
  343. }
  344. }
  345. if (argType->IsIntUnknown())
  346. {
  347. // New int fits into previous arg type, that's good
  348. if (mModule->CanCast(BfTypedValue(argValue, argType), prevGenericMethodArg))
  349. return true;
  350. // Doesn't fit, upgrade type to 'int'
  351. argType = mModule->GetPrimitiveType(BfTypeCode_IntPtr);
  352. }
  353. else
  354. {
  355. // Prev is already best
  356. if (mModule->CanCast(mModule->GetFakeTypedValue(argType), prevGenericMethodArg))
  357. return true;
  358. }
  359. // New best?
  360. if (mModule->CanCast(mModule->GetFakeTypedValue(prevGenericMethodArg), argType))
  361. {
  362. _SetGeneric();
  363. return true;
  364. }
  365. // No implicit conversion, FAIL!
  366. (*mCheckMethodGenericArguments)[wantGenericParam->mGenericParamIdx] = NULL;
  367. return false;
  368. }
  369. return true;
  370. }
  371. if (wantType->IsTuple())
  372. {
  373. if (argType->IsTuple())
  374. {
  375. auto wantTupleType = (BfTupleType*)wantType;
  376. auto argTupleType = (BfTupleType*)argType;
  377. if (wantTupleType->mFieldInstances.size() == argTupleType->mFieldInstances.size())
  378. {
  379. for (int fieldIdx = 0; fieldIdx < (int)wantTupleType->mFieldInstances.size(); fieldIdx++)
  380. {
  381. InferGenericArgument(methodInstance, argTupleType->mFieldInstances[fieldIdx].mResolvedType,
  382. wantTupleType->mFieldInstances[fieldIdx].mResolvedType, BfIRValue());
  383. }
  384. }
  385. }
  386. }
  387. if ((wantType->IsGenericTypeInstance()) && (wantType->IsUnspecializedTypeVariation()))
  388. {
  389. auto wantGenericType = (BfTypeInstance*)wantType;
  390. if (argType->IsGenericParam())
  391. {
  392. auto genericParam = mModule->GetGenericParamInstance((BfGenericParamType*)argType);
  393. if ((genericParam->mGenericParamFlags & BfGenericParamFlag_Var) != 0)
  394. {
  395. InferGenericArgument(methodInstance, mModule->GetPrimitiveType(BfTypeCode_Var), wantType, BfIRValue());
  396. return true;
  397. }
  398. if ((genericParam->mTypeConstraint != NULL) && (genericParam->mTypeConstraint->IsGenericTypeInstance()))
  399. InferGenericArgument(methodInstance, genericParam->mTypeConstraint, wantType, BfIRValue());
  400. }
  401. if (argType->IsVar())
  402. {
  403. for (int genericArgIdx = 0; genericArgIdx < (int)wantGenericType->mGenericTypeInfo->mTypeGenericArguments.size(); genericArgIdx++)
  404. {
  405. BfType* wantGenericArgument = wantGenericType->mGenericTypeInfo->mTypeGenericArguments[genericArgIdx];
  406. if (!wantGenericArgument->IsUnspecializedType())
  407. continue;
  408. InferGenericArgument(methodInstance, mModule->GetPrimitiveType(BfTypeCode_Var), wantGenericArgument, BfIRValue());
  409. }
  410. return true;
  411. }
  412. auto typeInstance = argType->ToTypeInstance();
  413. if (typeInstance == NULL)
  414. return true;
  415. if (wantGenericType->IsInterface())
  416. {
  417. for (auto& ifaceEntry : typeInstance->mInterfaces)
  418. InferGenericArgument(methodInstance, ifaceEntry.mInterfaceType, wantType, BfIRValue());
  419. }
  420. else if (typeInstance->mBaseType != NULL)
  421. InferGenericArgument(methodInstance, typeInstance->mBaseType, wantType, BfIRValue());
  422. if (!argType->IsGenericTypeInstance())
  423. return true;
  424. auto argGenericType = (BfTypeInstance*)argType;
  425. if (argGenericType->mTypeDef != wantGenericType->mTypeDef)
  426. return true;
  427. for (int genericArgIdx = 0; genericArgIdx < (int)argGenericType->mGenericTypeInfo->mTypeGenericArguments.size(); genericArgIdx++)
  428. {
  429. BfType* wantGenericArgument = wantGenericType->mGenericTypeInfo->mTypeGenericArguments[genericArgIdx];
  430. if (!wantGenericArgument->IsUnspecializedType())
  431. continue;
  432. if (!_AddToCheckedSet(argType, mCheckedTypeSet, alreadyChecked))
  433. return true;
  434. InferGenericArgument(methodInstance, argGenericType->mGenericTypeInfo->mTypeGenericArguments[genericArgIdx], wantGenericArgument, BfIRValue());
  435. }
  436. return true;
  437. }
  438. if (wantType->IsRef())
  439. {
  440. auto wantRefType = (BfRefType*)wantType;
  441. if (!argType->IsRef())
  442. {
  443. // Match to non-ref
  444. InferGenericArgument(methodInstance, argType, wantRefType->mElementType, BfIRValue());
  445. return true;
  446. }
  447. auto argRefType = (BfRefType*)argType;
  448. //TODO: We removed this check so we still infer even if we have the wrong ref kind
  449. //if (wantRefType->mRefKind != argRefType->mRefKind)
  450. //return true;
  451. return InferGenericArgument(methodInstance, argRefType->mElementType, wantRefType->mElementType, BfIRValue());
  452. }
  453. if (wantType->IsPointer())
  454. {
  455. if (!argType->IsPointer())
  456. return true;
  457. auto wantPointerType = (BfPointerType*) wantType;
  458. auto argPointerType = (BfPointerType*) argType;
  459. return InferGenericArgument(methodInstance, argPointerType->mElementType, wantPointerType->mElementType, BfIRValue());
  460. }
  461. if (wantType->IsUnknownSizedArrayType())
  462. {
  463. auto wantArrayType = (BfUnknownSizedArrayType*)wantType;
  464. if (argType->IsUnknownSizedArrayType())
  465. {
  466. auto argArrayType = (BfUnknownSizedArrayType*)argType;
  467. InferGenericArgument(methodInstance, argArrayType->mElementCountSource, wantArrayType->mElementCountSource, BfIRValue());
  468. }
  469. else if (argType->IsSizedArray())
  470. {
  471. auto argArrayType = (BfSizedArrayType*)argType;
  472. BfTypedValue sizeValue(mModule->GetConstValue(argArrayType->mElementCount), mModule->GetPrimitiveType(BfTypeCode_IntPtr));
  473. auto sizedType = mModule->CreateConstExprValueType(sizeValue);
  474. InferGenericArgument(methodInstance, sizedType, wantArrayType->mElementCountSource, BfIRValue());
  475. }
  476. }
  477. if (wantType->IsSizedArray())
  478. {
  479. if (argType->IsSizedArray())
  480. {
  481. auto wantArrayType = (BfSizedArrayType*)wantType;
  482. auto argArrayType = (BfSizedArrayType*)argType;
  483. InferGenericArgument(methodInstance, argArrayType->mElementType, wantArrayType->mElementType, BfIRValue());
  484. }
  485. }
  486. if ((wantType->IsDelegate()) || (wantType->IsFunction()))
  487. {
  488. if (((argType->IsDelegate()) || (argType->IsFunction())) &&
  489. (wantType->IsDelegate() == argType->IsDelegate()))
  490. {
  491. if (!_AddToCheckedSet(argType, mCheckedTypeSet, alreadyChecked))
  492. return true;
  493. auto argInvokeMethod = mModule->GetRawMethodByName(argType->ToTypeInstance(), "Invoke");
  494. auto wantInvokeMethod = mModule->GetRawMethodByName(wantType->ToTypeInstance(), "Invoke");
  495. if ((argInvokeMethod != NULL) && (wantInvokeMethod != NULL) && (argInvokeMethod->GetParamCount() == wantInvokeMethod->GetParamCount()))
  496. {
  497. InferGenericArgument(methodInstance, argInvokeMethod->mReturnType, wantInvokeMethod->mReturnType, BfIRValue());
  498. for (int argIdx = 0; argIdx < (int)argInvokeMethod->GetParamCount(); argIdx++)
  499. InferGenericArgument(methodInstance, argInvokeMethod->GetParamType(argIdx), wantInvokeMethod->GetParamType(argIdx), BfIRValue());
  500. }
  501. }
  502. else if (argType->IsMethodRef())
  503. {
  504. auto methodTypeRef = (BfMethodRefType*)argType;
  505. if (!_AddToCheckedSet(argType, mCheckedTypeSet, alreadyChecked))
  506. return true;
  507. auto argInvokeMethod = methodTypeRef->mMethodRef;
  508. auto delegateInfo = wantType->GetDelegateInfo();
  509. auto wantInvokeMethod = mModule->GetRawMethodByName(wantType->ToTypeInstance(), "Invoke");
  510. if ((delegateInfo->mHasExplicitThis) && (argInvokeMethod->HasThis()))
  511. InferGenericArgument(methodInstance, argInvokeMethod->GetParamType(-1), delegateInfo->mParams[0], BfIRValue());
  512. int wantInvokeOffset = delegateInfo->mHasExplicitThis ? 1 : 0;
  513. if ((argInvokeMethod != NULL) && (wantInvokeMethod != NULL) && (argInvokeMethod->GetParamCount() == wantInvokeMethod->GetParamCount() - wantInvokeOffset))
  514. {
  515. InferGenericArgument(methodInstance, argInvokeMethod->mReturnType, wantInvokeMethod->mReturnType, BfIRValue());
  516. for (int argIdx = 0; argIdx < (int)argInvokeMethod->GetParamCount(); argIdx++)
  517. InferGenericArgument(methodInstance, argInvokeMethod->GetParamType(argIdx), wantInvokeMethod->GetParamType(argIdx + wantInvokeOffset), BfIRValue());
  518. }
  519. }
  520. }
  521. return true;
  522. }
  523. bool BfGenericInferContext::InferGenericArguments(BfMethodInstance* methodInstance, int srcGenericIdx)
  524. {
  525. auto& srcGenericArg = (*mCheckMethodGenericArguments)[srcGenericIdx];
  526. if (srcGenericArg == NULL)
  527. return false;
  528. int startInferCount = mInferredCount;
  529. auto srcGenericParam = methodInstance->mMethodInfoEx->mGenericParams[srcGenericIdx];
  530. for (auto ifaceConstraint : srcGenericParam->mInterfaceConstraints)
  531. {
  532. if ((ifaceConstraint->IsUnspecializedTypeVariation()) && (ifaceConstraint->IsGenericTypeInstance()))
  533. {
  534. InferGenericArgument(methodInstance, srcGenericArg, ifaceConstraint, BfIRValue());
  535. auto typeInstance = srcGenericArg->ToTypeInstance();
  536. if ((typeInstance == NULL) && (srcGenericArg->IsWrappableType()))
  537. typeInstance = mModule->GetWrappedStructType(srcGenericArg);
  538. if (typeInstance != NULL)
  539. {
  540. for (auto ifaceEntry : typeInstance->mInterfaces)
  541. InferGenericArgument(methodInstance, ifaceEntry.mInterfaceType, ifaceConstraint, BfIRValue());
  542. }
  543. if (srcGenericArg->IsGenericParam())
  544. {
  545. auto genericParamType = (BfGenericParamType*)srcGenericArg;
  546. BfGenericParamInstance* genericParam = NULL;
  547. if (genericParamType->mGenericParamKind == BfGenericParamKind_Method)
  548. genericParam = methodInstance->mMethodInfoEx->mGenericParams[genericParamType->mGenericParamIdx];
  549. else
  550. genericParam = mModule->GetGenericParamInstance(genericParamType);
  551. if (genericParam->mTypeConstraint != NULL)
  552. InferGenericArgument(methodInstance, genericParam->mTypeConstraint, ifaceConstraint, BfIRValue());
  553. for (auto argIfaceConstraint : genericParam->mInterfaceConstraints)
  554. InferGenericArgument(methodInstance, argIfaceConstraint, ifaceConstraint, BfIRValue());
  555. }
  556. }
  557. }
  558. return mInferredCount != startInferCount;
  559. }
  560. void BfGenericInferContext::InferGenericArguments(BfMethodInstance* methodInstance)
  561. {
  562. // Attempt to infer from other generic args
  563. for (int srcGenericIdx = 0; srcGenericIdx < (int)mCheckMethodGenericArguments->size(); srcGenericIdx++)
  564. {
  565. InferGenericArguments(methodInstance, srcGenericIdx);
  566. }
  567. }
  568. int BfMethodMatcher::GetMostSpecificType(BfType* lhs, BfType* rhs)
  569. {
  570. if ((lhs->IsRef()) && (rhs->IsRef()))
  571. return GetMostSpecificType(lhs->GetUnderlyingType(), rhs->GetUnderlyingType());
  572. if ((lhs->IsPointer()) && (rhs->IsPointer()))
  573. return GetMostSpecificType(lhs->GetUnderlyingType(), rhs->GetUnderlyingType());
  574. if ((lhs->IsSizedArray()) && (rhs->IsSizedArray()))
  575. return GetMostSpecificType(lhs->GetUnderlyingType(), rhs->GetUnderlyingType());
  576. if (lhs->IsGenericParam())
  577. return rhs->IsGenericParam() ? -1 : 1;
  578. if (rhs->IsGenericParam())
  579. return 0;
  580. if ((lhs->IsUnspecializedType()) && (lhs->IsGenericTypeInstance()))
  581. {
  582. if ((!rhs->IsUnspecializedType()) || (!rhs->IsGenericTypeInstance()))
  583. return 1;
  584. auto lhsTypeInst = lhs->ToTypeInstance();
  585. auto rhsTypeInst = rhs->ToTypeInstance();
  586. if ((rhsTypeInst == NULL) || (lhsTypeInst == NULL) || (lhsTypeInst->mTypeDef != rhsTypeInst->mTypeDef))
  587. return -1;
  588. bool hadLHSMoreSpecific = false;
  589. bool hadRHSMoreSpecific = false;
  590. for (int generigArgIdx = 0; generigArgIdx < (int)lhsTypeInst->mGenericTypeInfo->mTypeGenericArguments.size(); generigArgIdx++)
  591. {
  592. int argMoreSpecific = GetMostSpecificType(lhsTypeInst->mGenericTypeInfo->mTypeGenericArguments[generigArgIdx],
  593. rhsTypeInst->mGenericTypeInfo->mTypeGenericArguments[generigArgIdx]);
  594. if (argMoreSpecific == 0)
  595. hadLHSMoreSpecific = true;
  596. else if (argMoreSpecific == 1)
  597. hadRHSMoreSpecific = true;
  598. }
  599. if ((hadLHSMoreSpecific) && (!hadRHSMoreSpecific))
  600. return 0;
  601. if ((hadRHSMoreSpecific) && (!hadLHSMoreSpecific))
  602. return 1;
  603. return -1;
  604. }
  605. if (rhs->IsUnspecializedType())
  606. return 0;
  607. return -1;
  608. }
  609. void BfMethodMatcher::CompareMethods(BfMethodInstance* prevMethodInstance, BfTypeVector* prevGenericArgumentsSubstitute,
  610. BfMethodInstance* newMethodInstance, BfTypeVector* genericArgumentsSubstitute,
  611. bool* outNewIsBetter, bool* outNewIsWorse, bool allowSpecializeFail)
  612. {
  613. if (prevMethodInstance == newMethodInstance)
  614. {
  615. *outNewIsBetter = false;
  616. *outNewIsWorse = true;
  617. return;
  618. }
  619. #define SET_BETTER_OR_WORSE(lhs, rhs) \
  620. if ((!isBetter) && (lhs) && !(rhs)) isBetter = true; \
  621. if ((!isWorse) && !(lhs) && (rhs)) isWorse = true;
  622. #define RETURN_BETTER_OR_WORSE(lhs, rhs) \
  623. if ((!isBetter) && (lhs) && !(rhs)) { *outNewIsBetter = true; *outNewIsWorse = false; return; } \
  624. if ((!isWorse) && !(lhs) && (rhs)) { *outNewIsBetter = false; *outNewIsWorse = true; return; };
  625. #define RETURN_RESULTS \
  626. *outNewIsBetter = isBetter; \
  627. *outNewIsWorse = isWorse; \
  628. return;
  629. int numUsedParams = 0;
  630. int prevNumUsedParams = 0;
  631. bool usedExtendedForm = false;
  632. bool prevUsedExtendedForm = false;
  633. bool isBetter = false;
  634. bool isWorse = false;
  635. int argIdx;
  636. BfMethodDef* prevMethodDef = prevMethodInstance->mMethodDef;
  637. BfMethodDef* newMethodDef = newMethodInstance->mMethodDef;
  638. if (prevMethodDef == mBackupMethodDef)
  639. {
  640. // This can happen for extension methods and such
  641. *outNewIsBetter = true;
  642. *outNewIsWorse = false;
  643. return;
  644. }
  645. if (newMethodDef->mExplicitInterface != prevMethodDef->mExplicitInterface)
  646. {
  647. if (mModule->CompareMethodSignatures(newMethodInstance, prevMethodInstance))
  648. {
  649. SET_BETTER_OR_WORSE(newMethodDef->mExplicitInterface != NULL, prevMethodDef->mExplicitInterface != NULL);
  650. *outNewIsBetter = isBetter;
  651. *outNewIsWorse = isWorse;
  652. return;
  653. }
  654. }
  655. bool anyIsExtension = false;
  656. int newImplicitParamCount = newMethodInstance->GetImplicitParamCount();
  657. if (newMethodInstance->mMethodDef->mHasAppend)
  658. newImplicitParamCount++;
  659. if (newMethodInstance->mMethodDef->mMethodType == BfMethodType_Extension)
  660. {
  661. newImplicitParamCount++;
  662. anyIsExtension = true;
  663. }
  664. int prevImplicitParamCount = prevMethodInstance->GetImplicitParamCount();
  665. if (prevMethodInstance->mMethodDef->mHasAppend)
  666. prevImplicitParamCount++;
  667. if (prevMethodInstance->mMethodDef->mMethodType == BfMethodType_Extension)
  668. {
  669. prevImplicitParamCount++;
  670. anyIsExtension = true;
  671. }
  672. int newMethodParamCount = newMethodInstance->GetParamCount();
  673. int prevMethodParamCount = prevMethodInstance->GetParamCount();
  674. bool hadEnoughArgs = newMethodParamCount - newImplicitParamCount < (int)mArguments.size();
  675. bool prevHadEnoughArgs = prevMethodParamCount - prevImplicitParamCount < (int)mArguments.size();
  676. RETURN_BETTER_OR_WORSE(hadEnoughArgs, prevHadEnoughArgs);
  677. bool chainSkip = (newMethodInstance->mChainType == BfMethodChainType_ChainMember) || (newMethodInstance->mChainType == BfMethodChainType_ChainSkip);
  678. bool prevChainSkip = (prevMethodInstance->mChainType == BfMethodChainType_ChainMember) || (prevMethodInstance->mChainType == BfMethodChainType_ChainSkip);
  679. RETURN_BETTER_OR_WORSE(!chainSkip, !prevChainSkip);
  680. if ((!isBetter) && (!isWorse))
  681. {
  682. bool betterByGenericParam = false;
  683. bool worseByGenericParam = false;
  684. bool betterByConstExprParam = false;
  685. bool worseByConstExprParam = false;
  686. bool someArgWasBetter = false;
  687. bool someArgWasWorse = false;
  688. for (argIdx = anyIsExtension ? -1 : 0; argIdx < (int)mArguments.size(); argIdx++)
  689. {
  690. BfTypedValue arg;
  691. BfResolvedArg* resolvedArg = NULL;
  692. bool wasArgDeferred = false;
  693. if (argIdx == -1)
  694. {
  695. arg = mTarget;
  696. }
  697. else
  698. {
  699. resolvedArg = &mArguments[argIdx];
  700. wasArgDeferred = resolvedArg->mArgFlags != 0;
  701. arg = resolvedArg->mTypedValue;
  702. }
  703. int newArgIdx = argIdx + newImplicitParamCount;
  704. int prevArgIdx = argIdx + prevImplicitParamCount;
  705. if (newArgIdx >= newMethodParamCount)
  706. break;
  707. if (prevArgIdx >= prevMethodParamCount)
  708. break;
  709. bool wasGenericParam = (newArgIdx >= 0) && newMethodInstance->WasGenericParam(newArgIdx);
  710. bool prevWasGenericParam = (prevArgIdx >= 0) && prevMethodInstance->WasGenericParam(prevArgIdx);
  711. BfType* paramType = newMethodInstance->GetParamType(newArgIdx, true);
  712. BfType* prevParamType = prevMethodInstance->GetParamType(prevArgIdx, true);
  713. numUsedParams++;
  714. prevNumUsedParams++;
  715. BfType* origParamType = paramType;
  716. BfType* origPrevParamType = prevParamType;
  717. bool paramWasConstExpr = false;
  718. bool prevParamWasConstExpr = false;
  719. bool paramWasUnspecialized = paramType->IsUnspecializedType();
  720. if ((genericArgumentsSubstitute != NULL) && (paramWasUnspecialized))
  721. {
  722. paramType = mModule->ResolveGenericType(paramType, NULL, genericArgumentsSubstitute, allowSpecializeFail);
  723. paramType = mModule->FixIntUnknown(paramType);
  724. }
  725. if (paramType->IsConstExprValue())
  726. {
  727. prevParamWasConstExpr = true;
  728. paramType = ((BfConstExprValueType*)paramType)->mType;
  729. }
  730. bool prevParamWasUnspecialized = prevParamType->IsUnspecializedType();
  731. if ((prevGenericArgumentsSubstitute != NULL) && (prevParamWasUnspecialized))
  732. {
  733. prevParamType = mModule->ResolveGenericType(prevParamType, NULL, prevGenericArgumentsSubstitute, allowSpecializeFail);
  734. prevParamType = mModule->FixIntUnknown(prevParamType);
  735. }
  736. if (prevParamType->IsConstExprValue())
  737. {
  738. prevParamWasConstExpr = true;
  739. prevParamType = ((BfConstExprValueType*)prevParamType)->mType;
  740. }
  741. bool paramsEquivalent = paramType == prevParamType;
  742. if ((prevParamType == NULL) || (paramType == NULL))
  743. {
  744. SET_BETTER_OR_WORSE(paramType != NULL, prevParamType != NULL);
  745. }
  746. else if (paramType != prevParamType)
  747. {
  748. bool isUnspecializedParam = paramType->IsUnspecializedType();
  749. bool isPrevUnspecializedParam = prevParamType->IsUnspecializedType();
  750. SET_BETTER_OR_WORSE((!isUnspecializedParam) && (!paramType->IsVar()),
  751. (!isPrevUnspecializedParam) && (!prevParamType->IsVar()));
  752. // Why did we have this !isUnspecializedParam check? We need the 'canCast' logic still
  753. if ((!isBetter) && (!isWorse) /*&& (!isUnspecializedParam) && (!isPrevUnspecializedParam)*/)
  754. {
  755. SET_BETTER_OR_WORSE((paramType != NULL) && (!paramType->IsUnspecializedType()),
  756. (prevParamType != NULL) && (!prevParamType->IsUnspecializedType()));
  757. if ((!isBetter) && (!isWorse))
  758. {
  759. // The resolved argument type may actually match for both considered functions. IE:
  760. // Method(int8 val) and Method(int16 val) called with Method(0) will create arguments that match their param types
  761. if ((!wasArgDeferred) && (!wasGenericParam) && (IsType(arg, paramType)) && ((resolvedArg == NULL) || (prevParamType != resolvedArg->mBestBoundType)))
  762. isBetter = true;
  763. //else if ((!prevWasGenericParam) && (IsType(arg, prevParamType)) && (!IsType(arg, paramType)))
  764. else if ((!wasArgDeferred) && (!prevWasGenericParam) && (IsType(arg, prevParamType)) && ((resolvedArg == NULL) || (paramType != resolvedArg->mBestBoundType)))
  765. isWorse = true;
  766. else
  767. {
  768. bool canCastFromCurToPrev = mModule->CanCast(mModule->GetFakeTypedValue(paramType), prevParamType);
  769. bool canCastFromPrevToCur = mModule->CanCast(mModule->GetFakeTypedValue(prevParamType), paramType);
  770. if ((canCastFromCurToPrev) && (canCastFromPrevToCur))
  771. paramsEquivalent = true;
  772. if ((canCastFromCurToPrev) && (!canCastFromPrevToCur))
  773. isBetter = true;
  774. else if ((canCastFromPrevToCur) && (!canCastFromCurToPrev))
  775. isWorse = true;
  776. else if ((paramType->IsIntegral()) && (prevParamType->IsIntegral()))
  777. {
  778. if (paramType == arg.mType)
  779. isBetter = true;
  780. else if (prevParamType == arg.mType)
  781. isWorse = true;
  782. else
  783. {
  784. if (paramType->mSize < prevParamType->mSize)
  785. isBetter = true;
  786. else if (paramType->mSize > prevParamType->mSize)
  787. isWorse = true;
  788. else if (paramType->IsSigned())
  789. isBetter = true;
  790. else
  791. isWorse = true;
  792. }
  793. }
  794. else if ((wasArgDeferred) && ((paramType->IsIntegral()) || (prevParamType->IsIntegral())))
  795. {
  796. SET_BETTER_OR_WORSE(paramType->IsIntegral(), prevParamType->IsIntegral());
  797. }
  798. }
  799. }
  800. }
  801. }
  802. if ((!isBetter) && (!isWorse) && (paramsEquivalent))
  803. {
  804. if ((origParamType != origPrevParamType) && (paramWasConstExpr) && (!prevParamWasConstExpr))
  805. betterByConstExprParam = true;
  806. else if ((origParamType != origPrevParamType) && (!paramWasConstExpr) && (prevParamWasConstExpr))
  807. worseByConstExprParam = true;
  808. else if (((paramWasUnspecialized) || (prevParamWasUnspecialized)))
  809. {
  810. int origTypeMoreSpecific = GetMostSpecificType(origParamType, origPrevParamType);
  811. if (origTypeMoreSpecific == 0)
  812. betterByGenericParam = true;
  813. else if (origTypeMoreSpecific == 1)
  814. worseByGenericParam = true;
  815. }
  816. }
  817. if ((newArgIdx >= 0) && (newMethodInstance->GetParamKind(newArgIdx) == BfParamKind_Params))
  818. usedExtendedForm = true;
  819. if ((prevArgIdx >= 0) && (prevMethodInstance->GetParamKind(prevArgIdx) == BfParamKind_Params))
  820. prevUsedExtendedForm = true;
  821. if ((usedExtendedForm) || (prevUsedExtendedForm))
  822. break;
  823. someArgWasBetter |= isBetter;
  824. someArgWasWorse |= isWorse;
  825. isBetter = false;
  826. isWorse = false;
  827. }
  828. isBetter |= someArgWasBetter;
  829. isWorse |= someArgWasWorse;
  830. if ((!isBetter) && (!isWorse))
  831. {
  832. // Don't allow ambiguity
  833. if ((betterByGenericParam && !worseByGenericParam) ||
  834. (!betterByGenericParam && worseByGenericParam))
  835. {
  836. isBetter = betterByGenericParam;
  837. isWorse = worseByGenericParam;
  838. }
  839. }
  840. if ((!isBetter) && (!isWorse))
  841. {
  842. // Don't allow ambiguity
  843. if ((betterByConstExprParam && !worseByConstExprParam) ||
  844. (!betterByConstExprParam && worseByConstExprParam))
  845. {
  846. isBetter = betterByConstExprParam;
  847. isWorse = worseByConstExprParam;
  848. }
  849. }
  850. if ((isBetter) || (isWorse))
  851. {
  852. RETURN_RESULTS;
  853. }
  854. }
  855. // Check for unused extended params as next param - that still counts as using extended form
  856. usedExtendedForm = newMethodInstance->HasParamsArray();
  857. prevUsedExtendedForm = prevMethodInstance->HasParamsArray();
  858. RETURN_BETTER_OR_WORSE(newMethodInstance->GetNumGenericArguments() == 0, prevMethodInstance->GetNumGenericArguments() == 0);
  859. // Not using generic delegate params is better
  860. RETURN_BETTER_OR_WORSE(!newMethodInstance->mHadGenericDelegateParams, !prevMethodInstance->mHadGenericDelegateParams);
  861. // Normal form trumps extended form
  862. RETURN_BETTER_OR_WORSE(!usedExtendedForm, !prevUsedExtendedForm);
  863. // More used params trumps less params
  864. int paramDiff = (int) numUsedParams - (int) prevNumUsedParams;
  865. RETURN_BETTER_OR_WORSE(paramDiff > 0, paramDiff < 0);
  866. // Fewer defaults trumps more defaults
  867. // Since we know the number of used params is the same (previous check), we infer that the rest are defaults
  868. paramDiff = (int) newMethodInstance->GetParamCount() - (int) prevMethodInstance->GetParamCount();
  869. RETURN_BETTER_OR_WORSE(paramDiff < 0, paramDiff > 0);
  870. BfMethodInstance* typeUnspecNewMethodInstance = mModule->GetUnspecializedMethodInstance(newMethodInstance, true);
  871. BfMethodInstance* typeUnspecPrevMethodInstance = mModule->GetUnspecializedMethodInstance(prevMethodInstance, true);
  872. // Check specificity of args
  873. std::function<void(BfType*, BfType*)> _CompareParamTypes = [&](BfType* newType, BfType* prevType)
  874. {
  875. if ((newType->IsGenericParam()) && (prevType->IsGenericParam()))
  876. {
  877. auto newGenericParamType = (BfGenericParamType*)newType;
  878. auto prevGenericParamType = (BfGenericParamType*)prevType;
  879. if ((newGenericParamType->mGenericParamKind == BfGenericParamKind_Method) && (prevGenericParamType->mGenericParamKind == BfGenericParamKind_Method))
  880. {
  881. auto newMethodGenericParam = typeUnspecNewMethodInstance->mMethodInfoEx->mGenericParams[newGenericParamType->mGenericParamIdx];
  882. auto prevMethodGenericParam = typeUnspecPrevMethodInstance->mMethodInfoEx->mGenericParams[prevGenericParamType->mGenericParamIdx];
  883. SET_BETTER_OR_WORSE(mModule->AreConstraintsSubset(prevMethodGenericParam, newMethodGenericParam), mModule->AreConstraintsSubset(newMethodGenericParam, prevMethodGenericParam));
  884. }
  885. }
  886. else if (newType == prevType)
  887. {
  888. if ((newType->IsUnspecializedType()) && (newType->IsGenericTypeInstance()))
  889. {
  890. BfTypeInstance* newGenericType = (BfTypeInstance*)newType;
  891. BfTypeInstance* prevGenericType = (BfTypeInstance*)prevType;
  892. for (int genericArgIdx = 0; genericArgIdx < (int)newGenericType->mGenericTypeInfo->mTypeGenericArguments.size(); genericArgIdx++)
  893. {
  894. _CompareParamTypes(newGenericType->mGenericTypeInfo->mTypeGenericArguments[genericArgIdx], prevGenericType->mGenericTypeInfo->mTypeGenericArguments[genericArgIdx]);
  895. }
  896. }
  897. }
  898. else
  899. {
  900. //TODO: Why did we need this?
  901. //isBetter |= mModule->IsTypeMoreSpecific(newType, prevType);
  902. //isWorse |= mModule->IsTypeMoreSpecific(prevType, newType);
  903. }
  904. };
  905. int paramCheckCount = (int)BF_MIN(newMethodInstance->GetParamCount() - newImplicitParamCount, prevMethodInstance->GetParamCount() - prevImplicitParamCount);
  906. for (argIdx = 0; argIdx < (int)paramCheckCount/*mArguments.size()*/; argIdx++)
  907. {
  908. int newArgIdx = argIdx + newImplicitParamCount;
  909. int prevArgIdx = argIdx + prevImplicitParamCount;
  910. _CompareParamTypes(typeUnspecNewMethodInstance->GetParamType(newArgIdx), typeUnspecPrevMethodInstance->GetParamType(prevArgIdx));
  911. }
  912. // Do generic constraint subset test directly to handle cases like "NotDisposed<T>()" vs "NotDisposed<T>() where T : IDisposable"
  913. if ((newMethodInstance->GetNumGenericArguments() > 0) && (newMethodInstance->GetNumGenericArguments() == prevMethodInstance->GetNumGenericArguments()))
  914. {
  915. for (int genericParamIdx = 0; genericParamIdx < (int)newMethodInstance->GetNumGenericArguments(); genericParamIdx++)
  916. {
  917. auto newMethodGenericParam = newMethodInstance->mMethodInfoEx->mGenericParams[genericParamIdx];
  918. auto prevMethodGenericParam = prevMethodInstance->mMethodInfoEx->mGenericParams[genericParamIdx];
  919. SET_BETTER_OR_WORSE(mModule->AreConstraintsSubset(prevMethodGenericParam, newMethodGenericParam), mModule->AreConstraintsSubset(newMethodGenericParam, prevMethodGenericParam));
  920. }
  921. if ((!isBetter) && (!isWorse))
  922. {
  923. SET_BETTER_OR_WORSE(newMethodInstance->HasExternConstraints(), prevMethodInstance->HasExternConstraints());
  924. }
  925. }
  926. if ((isBetter) || (isWorse))
  927. {
  928. RETURN_RESULTS;
  929. }
  930. if ((newMethodInstance->mMethodDef->mExternalConstraints.size() != 0) || (prevMethodInstance->mMethodDef->mExternalConstraints.size() != 0))
  931. {
  932. struct GenericParamPair
  933. {
  934. BfGenericMethodParamInstance* mParams[2];
  935. GenericParamPair()
  936. {
  937. mParams[0] = NULL;
  938. mParams[1] = NULL;
  939. }
  940. };
  941. Dictionary<BfType*, GenericParamPair> externConstraints;
  942. auto _GetParams = [&](int idx, BfMethodInstance* methodInstance)
  943. {
  944. for (int externConstraintIdx = 0; externConstraintIdx < (int)methodInstance->mMethodDef->mExternalConstraints.size(); externConstraintIdx++)
  945. {
  946. auto genericParam = methodInstance->mMethodInfoEx->mGenericParams[methodInstance->mMethodDef->mGenericParams.size() + externConstraintIdx];
  947. BF_ASSERT(genericParam->mExternType != NULL);
  948. GenericParamPair* pairPtr = NULL;
  949. externConstraints.TryAdd(genericParam->mExternType, NULL, &pairPtr);
  950. pairPtr->mParams[idx] = genericParam;
  951. }
  952. };
  953. _GetParams(0, newMethodInstance);
  954. _GetParams(0, prevMethodInstance);
  955. for (auto kv : externConstraints)
  956. {
  957. SET_BETTER_OR_WORSE(mModule->AreConstraintsSubset(kv.mValue.mParams[1], kv.mValue.mParams[0]), mModule->AreConstraintsSubset(kv.mValue.mParams[0], kv.mValue.mParams[1]));
  958. }
  959. if ((isBetter) || (isWorse))
  960. {
  961. RETURN_RESULTS;
  962. }
  963. }
  964. // Does one have a body and one doesn't? Obvious!
  965. isBetter = prevMethodDef->IsEmptyPartial();
  966. isWorse = newMethodDef->IsEmptyPartial();
  967. if ((isBetter) && (isWorse))
  968. {
  969. // If both are empty partials then just bind to either
  970. isWorse = true;
  971. RETURN_RESULTS;
  972. }
  973. // For operators, prefer explicit comparison over '<=>' comparison operator
  974. if ((!isBetter) && (!isWorse))
  975. {
  976. if ((prevMethodDef->mIsOperator) && (newMethodDef->mIsOperator))
  977. {
  978. bool newIsComparison = ((BfOperatorDeclaration*)newMethodDef->mMethodDeclaration)->mBinOp == BfBinaryOp_Compare;
  979. bool prevIsComparison = ((BfOperatorDeclaration*)prevMethodDef->mMethodDeclaration)->mBinOp == BfBinaryOp_Compare;
  980. RETURN_BETTER_OR_WORSE(!newIsComparison, !prevIsComparison);
  981. }
  982. }
  983. // For extensions, select the version in the most-specific project (only applicable for ctors)
  984. if ((!isBetter) && (!isWorse))
  985. {
  986. auto newProject = newMethodDef->mDeclaringType->mProject;
  987. auto prevProject = prevMethodDef->mDeclaringType->mProject;
  988. if (newProject != prevProject)
  989. {
  990. RETURN_BETTER_OR_WORSE(newProject->ContainsReference(prevProject), prevProject->ContainsReference(newProject));
  991. }
  992. }
  993. // If we have conditional type extensions that both define an implementation for a method, use the most-specific conditional extension constraints
  994. auto owner = newMethodInstance->GetOwner();
  995. if ((newMethodDef->mDeclaringType != prevMethodDef->mDeclaringType) && (owner->IsGenericTypeInstance()))
  996. {
  997. auto genericOwner = (BfTypeInstance*)owner;
  998. if (genericOwner->mGenericTypeInfo->mGenericExtensionInfo != NULL)
  999. {
  1000. BfGenericExtensionEntry* newGenericExtesionEntry = NULL;
  1001. BfGenericExtensionEntry* prevGenericExtesionEntry = NULL;
  1002. if ((genericOwner->mGenericTypeInfo->mGenericExtensionInfo->mExtensionMap.TryGetValue(newMethodDef->mDeclaringType, &newGenericExtesionEntry)) &&
  1003. (genericOwner->mGenericTypeInfo->mGenericExtensionInfo->mExtensionMap.TryGetValue(prevMethodDef->mDeclaringType, &prevGenericExtesionEntry)))
  1004. {
  1005. if ((newGenericExtesionEntry->mGenericParams.size() == prevGenericExtesionEntry->mGenericParams.size()))
  1006. {
  1007. for (int genericParamIdx = 0; genericParamIdx < (int)newGenericExtesionEntry->mGenericParams.size(); genericParamIdx++)
  1008. {
  1009. auto newMethodGenericParam = newGenericExtesionEntry->mGenericParams[genericParamIdx];
  1010. auto prevMethodGenericParam = prevGenericExtesionEntry->mGenericParams[genericParamIdx];
  1011. SET_BETTER_OR_WORSE(mModule->AreConstraintsSubset(prevMethodGenericParam, newMethodGenericParam), mModule->AreConstraintsSubset(newMethodGenericParam, prevMethodGenericParam));
  1012. }
  1013. }
  1014. if ((isBetter) || (isWorse))
  1015. {
  1016. RETURN_RESULTS;
  1017. }
  1018. }
  1019. }
  1020. }
  1021. RETURN_BETTER_OR_WORSE(newMethodDef->mCheckedKind == mCheckedKind, prevMethodDef->mCheckedKind == mCheckedKind);
  1022. RETURN_BETTER_OR_WORSE(newMethodDef->mCommutableKind != BfCommutableKind_Reverse, prevMethodDef->mCommutableKind != BfCommutableKind_Reverse);
  1023. // If one of these methods is local to the current extension then choose that one
  1024. auto activeDef = mModule->GetActiveTypeDef();
  1025. RETURN_BETTER_OR_WORSE(newMethodDef->mDeclaringType == activeDef, prevMethodDef->mDeclaringType == activeDef);
  1026. RETURN_BETTER_OR_WORSE(newMethodDef->mDeclaringType->IsExtension(), prevMethodDef->mDeclaringType->IsExtension());
  1027. RETURN_BETTER_OR_WORSE(newMethodDef->mIsMutating, prevMethodDef->mIsMutating);
  1028. if (newMethodDef->mHasComptime != prevMethodDef->mHasComptime)
  1029. {
  1030. bool isComptime = (mModule->mIsComptimeModule) || ((mBfEvalExprFlags & BfEvalExprFlags_Comptime) != 0);
  1031. RETURN_BETTER_OR_WORSE(newMethodDef->mHasComptime == isComptime, prevMethodDef->mHasComptime == isComptime);
  1032. }
  1033. RETURN_RESULTS;
  1034. }
  1035. BfTypedValue BfMethodMatcher::ResolveArgTypedValue(BfResolvedArg& resolvedArg, BfType* checkType, BfTypeVector* genericArgumentsSubstitute, BfType *origCheckType, BfResolveArgFlags flags)
  1036. {
  1037. BfTypedValue argTypedValue = resolvedArg.mTypedValue;
  1038. if ((resolvedArg.mArgFlags & BfArgFlag_DelegateBindAttempt) != 0)
  1039. {
  1040. BfExprEvaluator exprEvaluator(mModule);
  1041. exprEvaluator.mExpectingType = checkType;
  1042. BF_ASSERT(resolvedArg.mExpression->IsA<BfDelegateBindExpression>());
  1043. auto delegateBindExpr = BfNodeDynCast<BfDelegateBindExpression>(resolvedArg.mExpression);
  1044. BfMethodInstance* boundMethodInstance = NULL;
  1045. auto bindType = checkType;
  1046. if ((bindType == NULL) && (origCheckType != NULL) && (!origCheckType->IsUnspecializedTypeVariation()))
  1047. bindType = checkType;
  1048. if (exprEvaluator.CanBindDelegate(delegateBindExpr, &boundMethodInstance, bindType, genericArgumentsSubstitute))
  1049. {
  1050. if (delegateBindExpr->mNewToken == NULL)
  1051. {
  1052. if (boundMethodInstance->GetOwner()->IsFunction())
  1053. {
  1054. return BfTypedValue(mModule->mBfIRBuilder->GetFakeVal(), boundMethodInstance->GetOwner());
  1055. }
  1056. else if ((boundMethodInstance->mDisallowCalling) || ((flags & BfResolveArgFlag_FromGeneric) == 0))
  1057. {
  1058. argTypedValue = BfTypedValue(mModule->mBfIRBuilder->GetFakeVal(), checkType);
  1059. }
  1060. else
  1061. {
  1062. resolvedArg.mExpectedType = checkType;
  1063. auto methodRefType = mModule->CreateMethodRefType(boundMethodInstance);
  1064. mModule->AddDependency(methodRefType, mModule->mCurTypeInstance, BfDependencyMap::DependencyFlag_Calls);
  1065. mModule->AddCallDependency(boundMethodInstance);
  1066. argTypedValue = BfTypedValue(mModule->mBfIRBuilder->GetFakeVal(), methodRefType);
  1067. }
  1068. }
  1069. else
  1070. argTypedValue = BfTypedValue(BfTypedValueKind_UntypedValue);
  1071. }
  1072. }
  1073. else if ((resolvedArg.mArgFlags & BfArgFlag_LambdaBindAttempt) != 0)
  1074. {
  1075. if ((argTypedValue) && (argTypedValue.mType->IsMethodRef()) &&
  1076. ((checkType == NULL) || (!checkType->IsMethodRef())))
  1077. {
  1078. // This may be from a previous checkMethod, clear it out
  1079. argTypedValue = BfTypedValue();
  1080. }
  1081. BfExprEvaluator exprEvaluator(mModule);
  1082. exprEvaluator.mExpectingType = checkType;
  1083. BF_ASSERT(resolvedArg.mExpression->IsA<BfLambdaBindExpression>());
  1084. auto lambdaBindExpr = (BfLambdaBindExpression*)resolvedArg.mExpression;
  1085. if ((checkType != NULL) && (checkType->IsDelegate()))
  1086. {
  1087. BfMethodInstance* methodInstance = mModule->GetRawMethodInstanceAtIdx(checkType->ToTypeInstance(), 0, "Invoke");
  1088. if (methodInstance != NULL)
  1089. {
  1090. if (methodInstance->GetParamCount() == (int)lambdaBindExpr->mParams.size())
  1091. {
  1092. if (lambdaBindExpr->mNewToken == NULL)
  1093. {
  1094. if (!resolvedArg.mTypedValue)
  1095. {
  1096. // Resolve for real
  1097. resolvedArg.mTypedValue = mModule->CreateValueFromExpression(lambdaBindExpr, checkType, (BfEvalExprFlags)((mBfEvalExprFlags & BfEvalExprFlags_InheritFlags) | BfEvalExprFlags_NoCast | BfEvalExprFlags_NoAutoComplete));
  1098. }
  1099. argTypedValue = resolvedArg.mTypedValue;
  1100. }
  1101. else
  1102. argTypedValue = BfTypedValue(BfTypedValueKind_UntypedValue);
  1103. //argTypedValue = BfTypedValue(mModule->mBfIRBuilder->GetFakeVal(), checkType);
  1104. }
  1105. }
  1106. }
  1107. else if ((checkType == NULL) && (origCheckType != NULL) && (origCheckType->IsUnspecializedTypeVariation()) && (genericArgumentsSubstitute != NULL) && (origCheckType->IsDelegateOrFunction()))
  1108. {
  1109. BfMethodInstance* methodInstance = mModule->GetRawMethodInstanceAtIdx(origCheckType->ToTypeInstance(), 0, "Invoke");
  1110. if (methodInstance != NULL)
  1111. {
  1112. if ((methodInstance->mReturnType->IsGenericParam()) && (((BfGenericParamType*)methodInstance->mReturnType)->mGenericParamKind == BfGenericParamKind_Method))
  1113. {
  1114. bool isValid = true;
  1115. int returnMethodGenericArgIdx = ((BfGenericParamType*)methodInstance->mReturnType)->mGenericParamIdx;
  1116. if ((*genericArgumentsSubstitute)[returnMethodGenericArgIdx] != NULL)
  1117. {
  1118. isValid = false;
  1119. }
  1120. if (methodInstance->mParams.size() != (int)lambdaBindExpr->mParams.size())
  1121. isValid = false;
  1122. for (auto& param : methodInstance->mParams)
  1123. {
  1124. if (param.mResolvedType->IsGenericParam())
  1125. {
  1126. auto genericParamType = (BfGenericParamType*)param.mResolvedType;
  1127. if ((genericParamType->mGenericParamKind == BfGenericParamKind_Method) && ((*genericArgumentsSubstitute)[genericParamType->mGenericParamIdx] == NULL))
  1128. {
  1129. isValid = false;
  1130. }
  1131. }
  1132. }
  1133. if (isValid)
  1134. {
  1135. bool success = false;
  1136. (*genericArgumentsSubstitute)[returnMethodGenericArgIdx] = mModule->GetPrimitiveType(BfTypeCode_None);
  1137. auto tryType = mModule->ResolveGenericType(origCheckType, NULL, genericArgumentsSubstitute);
  1138. if (tryType != NULL)
  1139. {
  1140. auto inferredReturnType = mModule->CreateValueFromExpression(lambdaBindExpr, tryType, (BfEvalExprFlags)((mBfEvalExprFlags & BfEvalExprFlags_InheritFlags) | BfEvalExprFlags_NoCast | BfEvalExprFlags_InferReturnType | BfEvalExprFlags_NoAutoComplete));
  1141. if (inferredReturnType.mType != NULL)
  1142. {
  1143. (*genericArgumentsSubstitute)[returnMethodGenericArgIdx] = inferredReturnType.mType;
  1144. if (((flags & BfResolveArgFlag_FromGenericParam) != 0) && (lambdaBindExpr->mNewToken == NULL))
  1145. {
  1146. auto resolvedType = mModule->ResolveGenericType(origCheckType, NULL, genericArgumentsSubstitute);
  1147. if (resolvedType != NULL)
  1148. {
  1149. // Resolve for real
  1150. resolvedArg.mTypedValue = mModule->CreateValueFromExpression(lambdaBindExpr, resolvedType, (BfEvalExprFlags)((mBfEvalExprFlags & BfEvalExprFlags_InheritFlags) | BfEvalExprFlags_NoCast | BfEvalExprFlags_NoAutoComplete));
  1151. argTypedValue = resolvedArg.mTypedValue;
  1152. }
  1153. }
  1154. success = true;
  1155. }
  1156. }
  1157. if (!success)
  1158. {
  1159. // Put back
  1160. (*genericArgumentsSubstitute)[returnMethodGenericArgIdx] = NULL;
  1161. }
  1162. }
  1163. }
  1164. }
  1165. }
  1166. }
  1167. else if ((resolvedArg.mArgFlags & BfArgFlag_UnqualifiedDotAttempt) != 0)
  1168. {
  1169. if ((checkType != NULL) && (checkType->IsPayloadEnum()))
  1170. {
  1171. // Should we actually check the member name?
  1172. argTypedValue = BfTypedValue(BfTypedValueKind_UntypedValue);
  1173. }
  1174. }
  1175. else if ((resolvedArg.mArgFlags & BfArgFlag_UntypedDefault) != 0)
  1176. {
  1177. if (checkType != NULL)
  1178. argTypedValue = BfTypedValue(BfTypedValueKind_UntypedValue);
  1179. }
  1180. else if ((resolvedArg.mArgFlags & BfArgFlag_DeferredEval) != 0)
  1181. {
  1182. if (resolvedArg.mExpression != NULL)
  1183. {
  1184. if ((resolvedArg.mExpectedType != checkType) || (resolvedArg.mExpectedType == NULL)) // Did our last check match for this type?
  1185. {
  1186. SetAndRestoreValue<bool> prevIgnoreWrites(mModule->mBfIRBuilder->mIgnoreWrites, true);
  1187. SetAndRestoreValue<bool> prevIgnoreError(mModule->mIgnoreErrors, true);
  1188. bool prevNoBind = false;
  1189. if (mModule->mCurMethodState != NULL)
  1190. {
  1191. prevNoBind = mModule->mCurMethodState->mNoBind;
  1192. mModule->mCurMethodState->mNoBind = true;
  1193. }
  1194. auto prevBlock = mModule->mBfIRBuilder->GetInsertBlock();
  1195. BfExprEvaluator exprEvaluator(mModule);
  1196. exprEvaluator.mBfEvalExprFlags = (BfEvalExprFlags)(mBfEvalExprFlags & BfEvalExprFlags_InheritFlags);
  1197. exprEvaluator.mBfEvalExprFlags = (BfEvalExprFlags)(exprEvaluator.mBfEvalExprFlags | BfEvalExprFlags_AllowIntUnknown | BfEvalExprFlags_NoAutoComplete);
  1198. if ((resolvedArg.mArgFlags & BfArgFlag_ParamsExpr) != 0)
  1199. exprEvaluator.mBfEvalExprFlags = (BfEvalExprFlags)(exprEvaluator.mBfEvalExprFlags | BfEvalExprFlags_AllowParamsExpr);
  1200. auto expectType = checkType;
  1201. if (expectType != NULL)
  1202. {
  1203. if (expectType->IsRef())
  1204. {
  1205. auto refType = (BfRefType*)expectType;
  1206. expectType = refType->mElementType;
  1207. }
  1208. if ((genericArgumentsSubstitute != NULL) && (expectType->IsUnspecializedType()))
  1209. expectType = mModule->ResolveGenericType(expectType, NULL, genericArgumentsSubstitute, true);
  1210. }
  1211. exprEvaluator.mExpectingType = expectType;
  1212. exprEvaluator.Evaluate(resolvedArg.mExpression);
  1213. argTypedValue = exprEvaluator.GetResult();
  1214. if ((argTypedValue) && (argTypedValue.mType->IsVar()))
  1215. argTypedValue = BfTypedValue();
  1216. if (mModule->mCurMethodState != NULL)
  1217. mModule->mCurMethodState->mNoBind = prevNoBind;
  1218. if ((argTypedValue) && (!argTypedValue.mType->IsVar()))
  1219. {
  1220. if (checkType != NULL)
  1221. resolvedArg.mExpectedType = checkType;
  1222. auto storeTypedValue = argTypedValue;
  1223. if ((storeTypedValue.mValue) & (!storeTypedValue.mValue.IsFake()))
  1224. {
  1225. // We actually want to ensure that this cached value is a fake val. There are potential cases where a fake val
  1226. // won't be generated but we should throw an error, so we need to make sure we actually re-evaluate when the call
  1227. // is generated
  1228. //storeTypedValue.mValue = mModule->mBfIRBuilder->GetFakeVal();
  1229. resolvedArg.mWantsRecalc = true;
  1230. }
  1231. resolvedArg.mTypedValue = storeTypedValue;
  1232. //BF_ASSERT(argTypedValue.mValue.mId != -1);
  1233. }
  1234. mModule->mBfIRBuilder->SetInsertPoint(prevBlock);
  1235. }
  1236. }
  1237. }
  1238. else if ((resolvedArg.mArgFlags & BfArgFlag_VariableDeclaration) != 0)
  1239. {
  1240. if ((checkType != NULL) && (checkType->IsRef()))
  1241. argTypedValue = BfTypedValue(BfTypedValueKind_UntypedValue);
  1242. }
  1243. return argTypedValue;
  1244. }
  1245. bool BfMethodMatcher::WantsCheckMethod(BfProtectionCheckFlags& flags, BfTypeInstance* startTypeInstance, BfTypeInstance* checkTypeInstance, BfMethodDef* checkMethod)
  1246. {
  1247. MatchFailKind matchFailKind = MatchFailKind_None;
  1248. if (!mModule->CheckProtection(flags, checkTypeInstance, checkMethod->mDeclaringType->mProject, checkMethod->mProtection, startTypeInstance))
  1249. {
  1250. if ((mBypassVirtual) &&
  1251. ((checkMethod->mProtection == BfProtection_Protected) || (checkMethod->mProtection == BfProtection_ProtectedInternal)) &&
  1252. (mModule->TypeIsSubTypeOf(mModule->mCurTypeInstance, startTypeInstance)))
  1253. {
  1254. // Allow explicit 'base' call
  1255. }
  1256. else
  1257. {
  1258. return false;
  1259. }
  1260. }
  1261. if (mCheckedKind != checkMethod->mCheckedKind)
  1262. {
  1263. bool passes = true;
  1264. if (mCheckedKind != BfCheckedKind_NotSet)
  1265. {
  1266. passes = false;
  1267. }
  1268. else
  1269. {
  1270. auto defaultCheckedKind = mModule->GetDefaultCheckedKind();
  1271. if (defaultCheckedKind != checkMethod->mCheckedKind)
  1272. passes = false;
  1273. }
  1274. if (!passes)
  1275. {
  1276. return false;
  1277. }
  1278. }
  1279. return true;
  1280. }
  1281. bool BfMethodMatcher::InferFromGenericConstraints(BfMethodInstance* methodInstance, BfGenericParamInstance* genericParamInst, BfTypeVector* methodGenericArgs)
  1282. {
  1283. if (!genericParamInst->mExternType->IsGenericParam())
  1284. return false;
  1285. auto genericParamType = (BfGenericParamType*)genericParamInst->mExternType;
  1286. if (genericParamType->mGenericParamKind != BfGenericParamKind_Method)
  1287. return false;
  1288. BfType* checkArgType = NULL;
  1289. for (auto& checkOpConstraint : genericParamInst->mOperatorConstraints)
  1290. {
  1291. auto leftType = checkOpConstraint.mLeftType;
  1292. if ((leftType != NULL) && (leftType->IsUnspecializedType()))
  1293. leftType = mModule->ResolveGenericType(leftType, NULL, methodGenericArgs);
  1294. if (leftType != NULL)
  1295. leftType = mModule->FixIntUnknown(leftType);
  1296. auto rightType = checkOpConstraint.mRightType;
  1297. if ((rightType != NULL) && (rightType->IsUnspecializedType()))
  1298. rightType = mModule->ResolveGenericType(rightType, NULL, methodGenericArgs);
  1299. if (rightType != NULL)
  1300. rightType = mModule->FixIntUnknown(rightType);
  1301. BfConstraintState constraintSet;
  1302. constraintSet.mPrevState = mModule->mContext->mCurConstraintState;
  1303. constraintSet.mGenericParamInstance = genericParamInst;
  1304. constraintSet.mLeftType = leftType;
  1305. constraintSet.mRightType = rightType;
  1306. SetAndRestoreValue<BfConstraintState*> prevConstraintSet(mModule->mContext->mCurConstraintState, &constraintSet);
  1307. if (!mModule->CheckConstraintState(NULL))
  1308. return false;
  1309. if (checkOpConstraint.mBinaryOp != BfBinaryOp_None)
  1310. {
  1311. if ((leftType == NULL) || (rightType == NULL))
  1312. continue;
  1313. BfExprEvaluator exprEvaluator(mModule);
  1314. BfTypedValue leftValue(mModule->mBfIRBuilder->GetFakeVal(), leftType);
  1315. BfTypedValue rightValue(mModule->mBfIRBuilder->GetFakeVal(), rightType);
  1316. //
  1317. {
  1318. SetAndRestoreValue<bool> prevIgnoreErrors(mModule->mIgnoreErrors, true);
  1319. SetAndRestoreValue<bool> prevIgnoreWrites(mModule->mBfIRBuilder->mIgnoreWrites, true);
  1320. exprEvaluator.PerformBinaryOperation(NULL, NULL, checkOpConstraint.mBinaryOp, NULL, BfBinOpFlag_NoClassify, leftValue, rightValue);
  1321. }
  1322. if (exprEvaluator.mResult)
  1323. checkArgType = exprEvaluator.mResult.mType;
  1324. }
  1325. else
  1326. {
  1327. if (rightType == NULL)
  1328. continue;
  1329. BfTypedValue rightValue(mModule->mBfIRBuilder->GetFakeVal(), rightType);
  1330. StringT<128> failedOpName;
  1331. if (checkOpConstraint.mCastToken == BfToken_Implicit)
  1332. {
  1333. }
  1334. else
  1335. {
  1336. SetAndRestoreValue<bool> prevIgnoreErrors(mModule->mIgnoreErrors, true);
  1337. SetAndRestoreValue<bool> prevIgnoreWrites(mModule->mBfIRBuilder->mIgnoreWrites, true);
  1338. if (checkOpConstraint.mCastToken == BfToken_Explicit)
  1339. {
  1340. }
  1341. else
  1342. {
  1343. BfExprEvaluator exprEvaluator(mModule);
  1344. exprEvaluator.mResult = rightValue;
  1345. exprEvaluator.PerformUnaryOperation(NULL, checkOpConstraint.mUnaryOp, NULL, BfUnaryOpFlag_IsConstraintCheck);
  1346. if (exprEvaluator.mResult)
  1347. checkArgType = exprEvaluator.mResult.mType;
  1348. }
  1349. }
  1350. }
  1351. }
  1352. if ((checkArgType == NULL) && ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_ComptypeExpr) != 0))
  1353. {
  1354. for (auto comptypeConstraint : genericParamInst->mComptypeConstraint)
  1355. {
  1356. BfConstraintState constraintSet;
  1357. constraintSet.mPrevState = mModule->mContext->mCurConstraintState;
  1358. constraintSet.mGenericParamInstance = genericParamInst;
  1359. constraintSet.mMethodInstance = methodInstance;
  1360. constraintSet.mMethodGenericArgsOverride = methodGenericArgs;
  1361. SetAndRestoreValue<BfConstraintState*> prevConstraintSet(mModule->mContext->mCurConstraintState, &constraintSet);
  1362. if (!mModule->CheckConstraintState(NULL))
  1363. return false;
  1364. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mModule->mCurMethodInstance, methodInstance);
  1365. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mModule->mCurTypeInstance, methodInstance->GetOwner());
  1366. SetAndRestoreValue<bool> prevIgnoreErrors(mModule->mIgnoreErrors, true);
  1367. checkArgType = mModule->ResolveTypeRef(comptypeConstraint);
  1368. }
  1369. }
  1370. if (checkArgType == NULL)
  1371. return false;
  1372. if (checkArgType->IsVar())
  1373. return false;
  1374. (*methodGenericArgs)[genericParamType->mGenericParamIdx] = checkArgType;
  1375. return true;
  1376. }
  1377. bool BfMethodMatcher::CheckMethod(BfTypeInstance* targetTypeInstance, BfTypeInstance* typeInstance, BfMethodDef* checkMethod, bool isFailurePass)
  1378. {
  1379. BP_ZONE("BfMethodMatcher::CheckMethod");
  1380. BackupMatchKind curMatchKind = BackupMatchKind_None;
  1381. bool hadMatch = false;
  1382. // Never consider overrides - they only get found at original method declaration
  1383. // mBypassVirtual gets set when we are doing an explicit "base" call, or when we are a struct --
  1384. // because on structs we know the exact type
  1385. if ((checkMethod->mIsOverride) && (!mBypassVirtual) && (!typeInstance->IsValueType()))
  1386. return false;
  1387. mMethodCheckCount++;
  1388. BfMethodInstance* methodInstance = mModule->GetRawMethodInstance(typeInstance, checkMethod);
  1389. if (methodInstance == NULL)
  1390. {
  1391. BFMODULE_FATAL(mModule, "Failed to get raw method in BfMethodMatcher::CheckMethod");
  1392. return false;
  1393. }
  1394. BfMethodInstance* typeUnspecMethodInstance = mModule->GetUnspecializedMethodInstance(methodInstance, true);
  1395. BfTypeVector* typeGenericArguments = NULL;
  1396. if (typeInstance->mGenericTypeInfo != NULL)
  1397. typeGenericArguments = &typeInstance->mGenericTypeInfo->mTypeGenericArguments;
  1398. if ((mInterfaceMethodInstance != NULL) && (methodInstance->GetExplicitInterface() != NULL))
  1399. {
  1400. BfTypeInstance* wantInterface = mInterfaceMethodInstance->mMethodInstanceGroup->mOwner;
  1401. if (wantInterface != methodInstance->GetExplicitInterface())
  1402. return false;
  1403. }
  1404. if ((checkMethod->mIsVirtual) && (!checkMethod->mIsOverride) && (!mBypassVirtual) &&
  1405. (targetTypeInstance != NULL) && (targetTypeInstance->IsObject()))
  1406. {
  1407. mModule->PopulateType(targetTypeInstance, BfPopulateType_DataAndMethods);
  1408. if ((methodInstance->mVirtualTableIdx < targetTypeInstance->mVirtualMethodTable.mSize) && (methodInstance->mVirtualTableIdx >= 0))
  1409. {
  1410. BfVirtualMethodEntry& vEntry = targetTypeInstance->mVirtualMethodTable[methodInstance->mVirtualTableIdx];
  1411. auto implMethod = (BfMethodInstance*)vEntry.mImplementingMethod;
  1412. if ((implMethod != methodInstance) && (implMethod != NULL))
  1413. {
  1414. SetAndRestoreValue<bool> prevBypassVirtual(mBypassVirtual, true);
  1415. return CheckMethod(targetTypeInstance, implMethod->GetOwner(), implMethod->mMethodDef, isFailurePass);
  1416. }
  1417. }
  1418. else
  1419. {
  1420. // Being in autocomplete mode is the only excuse for not having the virtual method table slotted
  1421. if ((!mModule->mCompiler->IsAutocomplete()) && (!targetTypeInstance->mTypeFailed) && (!targetTypeInstance->IsUnspecializedTypeVariation()))
  1422. {
  1423. mModule->AssertErrorState();
  1424. }
  1425. }
  1426. }
  1427. BfGenericInferContext genericInferContext;
  1428. genericInferContext.mModule = mModule;
  1429. genericInferContext.mCheckMethodGenericArguments = &mCheckMethodGenericArguments;
  1430. HashSet<int> allowEmptyGenericSet;
  1431. BfAutoComplete* autoComplete = NULL;
  1432. if ((mModule->mCompiler->mResolvePassData != NULL) && (!isFailurePass) && ((mBfEvalExprFlags & BfEvalExprFlags_NoAutoComplete) == 0))
  1433. autoComplete = mModule->mCompiler->mResolvePassData->mAutoComplete;
  1434. if (checkMethod->mMethodType != BfMethodType_Extension)
  1435. {
  1436. if (((checkMethod->mIsStatic) && (!mAllowStatic)) ||
  1437. ((!checkMethod->mIsStatic) && (!mAllowNonStatic)))
  1438. {
  1439. if (!typeInstance->IsFunction())
  1440. autoComplete = NULL;
  1441. }
  1442. }
  1443. if ((autoComplete != NULL) && (autoComplete->mIsCapturingMethodMatchInfo))
  1444. {
  1445. BfAutoComplete::MethodMatchEntry methodMatchEntry;
  1446. methodMatchEntry.mMethodDef = checkMethod;
  1447. methodMatchEntry.mTypeInstance = typeInstance;
  1448. methodMatchEntry.mCurMethodInstance = mModule->mCurMethodInstance;
  1449. autoComplete->mMethodMatchInfo->mInstanceList.push_back(methodMatchEntry);
  1450. }
  1451. BfTypeVector* genericArgumentsSubstitute = NULL;
  1452. int argIdx = 0;
  1453. int argMatchCount = 0;
  1454. bool needInferGenericParams = (checkMethod->mGenericParams.size() != 0) && (!mHadExplicitGenericArguments);
  1455. int paramIdx = 0;
  1456. BfType* paramsElementType = NULL;
  1457. if (checkMethod->mHasAppend)
  1458. paramIdx++;
  1459. int uniqueGenericStartIdx = mModule->GetLocalInferrableGenericArgCount(checkMethod);
  1460. if ((mHadExplicitGenericArguments) && (checkMethod->mGenericParams.size() != mExplicitMethodGenericArguments.size() + uniqueGenericStartIdx))
  1461. goto NoMatch;
  1462. for (auto& checkGenericArgRef : mCheckMethodGenericArguments)
  1463. checkGenericArgRef = NULL;
  1464. mCheckMethodGenericArguments.resize(checkMethod->mGenericParams.size());
  1465. for (auto& genericArgRef : mCheckMethodGenericArguments)
  1466. genericArgRef = NULL;
  1467. if (mHadExplicitGenericArguments)
  1468. {
  1469. if (uniqueGenericStartIdx > 0)
  1470. {
  1471. genericArgumentsSubstitute = &mCheckMethodGenericArguments;
  1472. mCheckMethodGenericArguments.clear();
  1473. mCheckMethodGenericArguments.reserve(mExplicitMethodGenericArguments.size() + uniqueGenericStartIdx);
  1474. for (int i = 0; i < uniqueGenericStartIdx; i++)
  1475. mCheckMethodGenericArguments.Add(NULL);
  1476. for (int i = 0; i < (int)mExplicitMethodGenericArguments.size(); i++)
  1477. mCheckMethodGenericArguments.Add(mExplicitMethodGenericArguments[i]);
  1478. }
  1479. else
  1480. {
  1481. genericArgumentsSubstitute = &mExplicitMethodGenericArguments;
  1482. }
  1483. }
  1484. else if (needInferGenericParams)
  1485. genericArgumentsSubstitute = &mCheckMethodGenericArguments;
  1486. if ((checkMethod->mIsMutating) && (targetTypeInstance != NULL) && (targetTypeInstance->IsValueType()) &&
  1487. ((mTarget.IsReadOnly()) || (!mTarget.IsAddr())) &&
  1488. (!targetTypeInstance->IsValuelessType()))
  1489. {
  1490. goto NoMatch;
  1491. }
  1492. if (mSkipImplicitParams)
  1493. {
  1494. //paramOfs = methodInstance->GetImplicitParamCount();
  1495. //paramIdx += paramOfs;
  1496. }
  1497. if (needInferGenericParams)
  1498. {
  1499. genericInferContext.mPrevArgValues.resize(checkMethod->mGenericParams.size());
  1500. int paramOfs = methodInstance->GetImplicitParamCount();
  1501. int paramCount = methodInstance->GetParamCount();
  1502. SizedArray<int, 8> deferredArgs;
  1503. int argIdx = 0;
  1504. int paramIdx = 0;
  1505. if (checkMethod->mHasAppend)
  1506. paramIdx++;
  1507. if (checkMethod->mMethodType == BfMethodType_Extension)
  1508. {
  1509. argIdx--;
  1510. }
  1511. paramIdx += paramOfs;
  1512. bool hadInferFailure = false;
  1513. int inferParamOffset = paramOfs - argIdx;
  1514. enum ResultKind
  1515. {
  1516. ResultKind_Ok,
  1517. ResultKind_Failed,
  1518. ResultKind_Deferred,
  1519. };
  1520. auto _CheckArg = [&](int argIdx)
  1521. {
  1522. paramIdx = argIdx + inferParamOffset;
  1523. auto wantType = methodInstance->GetParamType(paramIdx);
  1524. auto checkType = wantType;
  1525. auto origCheckType = checkType;
  1526. if (checkType->IsGenericParam())
  1527. {
  1528. BfGenericParamInstance* genericParamInstance = NULL;
  1529. auto genericParamType = (BfGenericParamType*)checkType;
  1530. checkType = NULL;
  1531. if (genericParamType->mGenericParamKind == BfGenericParamKind_Method)
  1532. {
  1533. if ((genericArgumentsSubstitute != NULL) && (genericParamType->mGenericParamIdx < (int)genericArgumentsSubstitute->size()))
  1534. checkType = (*genericArgumentsSubstitute)[genericParamType->mGenericParamIdx];
  1535. genericParamInstance = methodInstance->mMethodInfoEx->mGenericParams[genericParamType->mGenericParamIdx];
  1536. }
  1537. else
  1538. genericParamInstance = mModule->GetGenericParamInstance(genericParamType);
  1539. if (checkType == NULL)
  1540. {
  1541. checkType = genericParamInstance->mTypeConstraint;
  1542. origCheckType = checkType; // We can do "ResolveGenericType" on this type
  1543. }
  1544. }
  1545. bool attemptedGenericResolve = false;
  1546. if ((checkType != NULL) && (genericArgumentsSubstitute != NULL) && (checkType->IsUnspecializedType()))
  1547. {
  1548. attemptedGenericResolve = true;
  1549. checkType = mModule->ResolveGenericType(origCheckType, NULL, genericArgumentsSubstitute);
  1550. }
  1551. if (wantType->IsUnspecializedType())
  1552. {
  1553. BfTypedValue argTypedValue;
  1554. if (argIdx == -1)
  1555. {
  1556. if (mOrigTarget)
  1557. argTypedValue = mOrigTarget;
  1558. else
  1559. argTypedValue = mTarget;
  1560. }
  1561. else
  1562. {
  1563. BfResolveArgFlags flags = BfResolveArgFlag_FromGeneric;
  1564. if (wantType->IsGenericParam())
  1565. flags = (BfResolveArgFlags)(flags | BfResolveArgFlag_FromGenericParam);
  1566. argTypedValue = ResolveArgTypedValue(mArguments[argIdx], checkType, genericArgumentsSubstitute, origCheckType, flags);
  1567. }
  1568. if (!argTypedValue.IsUntypedValue())
  1569. {
  1570. auto type = argTypedValue.mType;
  1571. if (!argTypedValue)
  1572. {
  1573. if ((checkType == NULL) && (attemptedGenericResolve) && (genericInferContext.GetUnresolvedCount() >= 2))
  1574. {
  1575. deferredArgs.Add(argIdx);
  1576. return ResultKind_Deferred;
  1577. }
  1578. return ResultKind_Failed;
  1579. }
  1580. if (type->IsVar())
  1581. mHasVarArguments = true;
  1582. genericInferContext.mCheckedTypeSet.Clear();
  1583. if (!genericInferContext.InferGenericArgument(methodInstance, type, wantType, argTypedValue.mValue))
  1584. return ResultKind_Failed;
  1585. }
  1586. }
  1587. return ResultKind_Ok;
  1588. };
  1589. for (; argIdx < (int)mArguments.size(); argIdx++)
  1590. {
  1591. paramIdx = argIdx + inferParamOffset;
  1592. if (paramIdx >= paramCount)
  1593. break; // Possible for delegate 'params' type methods
  1594. auto resultKind = _CheckArg(argIdx);
  1595. if (resultKind == ResultKind_Failed)
  1596. goto NoMatch;
  1597. }
  1598. if (!deferredArgs.IsEmpty())
  1599. {
  1600. genericInferContext.InferGenericArguments(methodInstance);
  1601. }
  1602. while (!deferredArgs.IsEmpty())
  1603. {
  1604. int prevDeferredSize = (int)deferredArgs.size();
  1605. for (int i = 0; i < prevDeferredSize; i++)
  1606. {
  1607. auto resultKind = _CheckArg(deferredArgs[i]);
  1608. if (resultKind == ResultKind_Failed)
  1609. goto NoMatch;
  1610. }
  1611. deferredArgs.RemoveRange(0, prevDeferredSize);
  1612. if (prevDeferredSize == deferredArgs.size())
  1613. {
  1614. // No progress
  1615. goto NoMatch;
  1616. }
  1617. }
  1618. //
  1619. {
  1620. int paramIdx = (int)mArguments.size() + paramOfs;
  1621. while (paramIdx < checkMethod->mParams.size())
  1622. {
  1623. if ((paramIdx < methodInstance->mDefaultValues.size()) && (methodInstance->mDefaultValues[paramIdx]))
  1624. {
  1625. auto wantType = methodInstance->GetParamType(paramIdx);
  1626. auto checkType = wantType;
  1627. if (checkType->IsGenericParam())
  1628. {
  1629. BfGenericParamInstance* genericParamInstance = NULL;
  1630. auto genericParamType = (BfGenericParamType*)checkType;
  1631. if (genericParamType->mGenericParamKind == BfGenericParamKind_Method)
  1632. {
  1633. if ((genericArgumentsSubstitute != NULL) && (genericParamType->mGenericParamIdx < (int)genericArgumentsSubstitute->size()))
  1634. checkType = (*genericArgumentsSubstitute)[genericParamType->mGenericParamIdx];
  1635. genericParamInstance = methodInstance->mMethodInfoEx->mGenericParams[genericParamType->mGenericParamIdx];
  1636. if ((genericParamInstance->mGenericParamFlags & BfGenericParamFlag_Const) != 0)
  1637. {
  1638. if (mCheckMethodGenericArguments[genericParamType->mGenericParamIdx] == NULL)
  1639. allowEmptyGenericSet.Add(genericParamType->mGenericParamIdx);
  1640. }
  1641. }
  1642. }
  1643. }
  1644. paramIdx++;
  1645. }
  1646. }
  1647. // while (true)
  1648. // {
  1649. //
  1650. // }
  1651. //
  1652. bool failed = false;
  1653. bool inferredAllGenericArguments = false;
  1654. for (int pass = 0; true; pass++)
  1655. {
  1656. bool madeProgress = false;
  1657. bool hasUninferred = false;
  1658. failed = false;
  1659. for (int genericArgIdx = uniqueGenericStartIdx; genericArgIdx < (int)checkMethod->mGenericParams.size(); genericArgIdx++)
  1660. {
  1661. auto& genericArg = mCheckMethodGenericArguments[genericArgIdx];
  1662. if (genericArg == NULL)
  1663. {
  1664. auto genericParam = methodInstance->mMethodInfoEx->mGenericParams[genericArgIdx];
  1665. InferFromGenericConstraints(methodInstance, genericParam, &mCheckMethodGenericArguments);
  1666. if (genericArg != NULL)
  1667. {
  1668. if (inferredAllGenericArguments)
  1669. genericInferContext.InferGenericArguments(methodInstance, genericArgIdx);
  1670. madeProgress = true;
  1671. }
  1672. hasUninferred = true;
  1673. if (!allowEmptyGenericSet.Contains(genericArgIdx))
  1674. failed = true;
  1675. }
  1676. }
  1677. if (!hasUninferred)
  1678. break;
  1679. if (inferredAllGenericArguments)
  1680. {
  1681. if (!madeProgress)
  1682. break;
  1683. }
  1684. genericInferContext.InferGenericArguments(methodInstance);
  1685. inferredAllGenericArguments = true;
  1686. }
  1687. if (failed)
  1688. goto NoMatch;
  1689. }
  1690. if (checkMethod->mMethodType == BfMethodType_Extension)
  1691. argIdx--;
  1692. // Iterate through params
  1693. while (true)
  1694. {
  1695. // Too many arguments
  1696. if (paramIdx >= (int)methodInstance->GetParamCount())
  1697. {
  1698. break;
  1699. }
  1700. bool isDeferredEval = false;
  1701. if ((argIdx >= 0) && (methodInstance->GetParamKind(paramIdx) == BfParamKind_Params) && (paramsElementType == NULL))
  1702. {
  1703. if (argIdx >= (int) mArguments.size())
  1704. break; // No params
  1705. BfTypedValue argTypedValue = ResolveArgTypedValue(mArguments[argIdx], NULL, genericArgumentsSubstitute);
  1706. if (!argTypedValue)
  1707. goto NoMatch;
  1708. if ((!argTypedValue.HasType()) && (!mArguments[argIdx].IsDeferredEval()))
  1709. goto NoMatch;
  1710. auto paramsArrayType = methodInstance->GetParamType(paramIdx);
  1711. if ((mArguments[argIdx].mArgFlags & BfArgFlag_ParamsExpr) != 0)
  1712. {
  1713. // Direct-pass params
  1714. if ((argTypedValue.IsUntypedValue()) || (mModule->CanCast(argTypedValue, paramsArrayType)))
  1715. {
  1716. argIdx++;
  1717. argMatchCount++;
  1718. paramIdx++;
  1719. break;
  1720. }
  1721. goto NoMatch;
  1722. }
  1723. if ((paramsArrayType->IsArray()) || (paramsArrayType->IsInstanceOf(mModule->mCompiler->mSpanTypeDef)))
  1724. {
  1725. paramsElementType = paramsArrayType->GetUnderlyingType();
  1726. while (argIdx < (int)mArguments.size())
  1727. {
  1728. argTypedValue = ResolveArgTypedValue(mArguments[argIdx], paramsElementType, genericArgumentsSubstitute);
  1729. if (!argTypedValue.HasType())
  1730. goto NoMatch;
  1731. if (!mModule->CanCast(argTypedValue, paramsElementType))
  1732. goto NoMatch;
  1733. argIdx++;
  1734. argMatchCount++;
  1735. }
  1736. }
  1737. else
  1738. goto NoMatch;
  1739. break;
  1740. }
  1741. if (methodInstance->IsImplicitCapture(paramIdx))
  1742. {
  1743. paramIdx++;
  1744. continue;
  1745. }
  1746. if (argIdx >= (int) mArguments.size())
  1747. {
  1748. // We have defaults the rest of the way, so that's cool
  1749. if (methodInstance->GetParamInitializer(paramIdx) != NULL)
  1750. break;
  1751. // We have unused params left over
  1752. goto NoMatch;
  1753. }
  1754. auto wantType = methodInstance->GetParamType(paramIdx);
  1755. if ((genericArgumentsSubstitute != NULL) && (wantType->IsUnspecializedType()))
  1756. {
  1757. wantType = typeUnspecMethodInstance->GetParamType(paramIdx);
  1758. auto resolvedType = mModule->ResolveGenericType(wantType, typeGenericArguments, genericArgumentsSubstitute, false);
  1759. if (resolvedType == NULL)
  1760. goto NoMatch;
  1761. wantType = resolvedType;
  1762. }
  1763. if (wantType->IsSelf())
  1764. wantType = typeInstance;
  1765. if ((argIdx >= 0) && ((mArguments[argIdx].mArgFlags & BfArgFlag_ParamsExpr) != 0))
  1766. {
  1767. // We had a 'params' expression but this method didn't have a params slot in this parameter
  1768. goto NoMatch;
  1769. }
  1770. BfTypedValue argTypedValue;
  1771. if (argIdx == -1)
  1772. argTypedValue = mTarget;
  1773. else
  1774. argTypedValue = ResolveArgTypedValue(mArguments[argIdx], wantType, genericArgumentsSubstitute);
  1775. if (!argTypedValue.IsUntypedValue())
  1776. {
  1777. if (!argTypedValue.HasType())
  1778. {
  1779. // Check to see if this is the last argument and that it's a potential enum match
  1780. if ((wantType->IsEnum()) && (argIdx == mArguments.size() - 1))
  1781. {
  1782. if (auto memberRefExpr = BfNodeDynCast<BfMemberReferenceExpression>(mArguments[argIdx].mExpression))
  1783. {
  1784. if (memberRefExpr->mTarget == NULL)
  1785. {
  1786. // Is dot expression
  1787. curMatchKind = BackupMatchKind_PartialLastArgMatch;
  1788. }
  1789. }
  1790. }
  1791. goto NoMatch;
  1792. }
  1793. else
  1794. {
  1795. if ((wantType->IsRef()) && (!argTypedValue.mType->IsRef()) &&
  1796. ((mAllowImplicitRef) || (wantType->IsIn())))
  1797. wantType = wantType->GetUnderlyingType();
  1798. if (!mModule->CanCast(argTypedValue, wantType))
  1799. goto NoMatch;
  1800. }
  1801. }
  1802. paramIdx++;
  1803. argIdx++;
  1804. argMatchCount++;
  1805. if ((autoComplete != NULL) && (autoComplete->mIsCapturingMethodMatchInfo))
  1806. {
  1807. auto methodMatchInfo = autoComplete->mMethodMatchInfo;
  1808. if (!methodMatchInfo->mHadExactMatch)
  1809. {
  1810. bool isBetter = false;
  1811. bool isWorse = false;
  1812. int methodIdx = (int)methodMatchInfo->mInstanceList.size() - 1;
  1813. if ((methodMatchInfo->mBestIdx != -1) && (methodMatchInfo->mBestIdx < (int)methodMatchInfo->mInstanceList.size()))
  1814. {
  1815. auto prevMethodMatchEntry = &methodMatchInfo->mInstanceList[methodMatchInfo->mBestIdx];
  1816. if (checkMethod->mParams.size() < mArguments.size())
  1817. {
  1818. isWorse = true;
  1819. }
  1820. else if ((prevMethodMatchEntry->mMethodDef != NULL) && (prevMethodMatchEntry->mMethodDef->mParams.size() < (int) mArguments.size()))
  1821. {
  1822. isBetter = true;
  1823. }
  1824. }
  1825. }
  1826. }
  1827. }
  1828. // Too many arguments (not all incoming arguments processed)
  1829. if (argIdx < (int)mArguments.size())
  1830. {
  1831. if (!methodInstance->IsVarArgs())
  1832. goto NoMatch;
  1833. }
  1834. if ((genericArgumentsSubstitute != NULL) && (genericArgumentsSubstitute->size() != 0))
  1835. {
  1836. for (int checkGenericIdx = uniqueGenericStartIdx; checkGenericIdx < (int)genericArgumentsSubstitute->size(); checkGenericIdx++)
  1837. {
  1838. auto& genericParams = methodInstance->mMethodInfoEx->mGenericParams;
  1839. auto genericArg = (*genericArgumentsSubstitute)[checkGenericIdx];
  1840. if (genericArg == NULL)
  1841. {
  1842. if (allowEmptyGenericSet.Contains(checkGenericIdx))
  1843. continue;
  1844. goto NoMatch;
  1845. }
  1846. if (genericArg == NULL)
  1847. goto NoMatch;
  1848. if (!mModule->CheckGenericConstraints(BfGenericParamSource(methodInstance), genericArg, NULL, genericParams[checkGenericIdx], genericArgumentsSubstitute, NULL))
  1849. goto NoMatch;
  1850. }
  1851. }
  1852. for (int externConstraintIdx = 0; externConstraintIdx < (int)checkMethod->mExternalConstraints.size(); externConstraintIdx++)
  1853. {
  1854. auto genericParam = methodInstance->mMethodInfoEx->mGenericParams[checkMethod->mGenericParams.size() + externConstraintIdx];
  1855. BF_ASSERT(genericParam->mExternType != NULL);
  1856. if (!mModule->CheckGenericConstraints(BfGenericParamSource(methodInstance), genericParam->mExternType, NULL, genericParam, genericArgumentsSubstitute, NULL))
  1857. goto NoMatch;
  1858. }
  1859. // Method is applicable, check to see which method is better
  1860. if (mBestMethodDef != NULL)
  1861. {
  1862. bool isBetter = false;
  1863. bool isWorse = false;
  1864. BfMethodInstance* prevMethodInstance = mModule->GetRawMethodInstance(mBestMethodTypeInstance, mBestMethodDef);
  1865. bool allowSpecializeFail = mModule->mCurTypeInstance->IsUnspecializedType();
  1866. if (mModule->mCurMethodInstance != NULL)
  1867. allowSpecializeFail = mModule->mCurMethodInstance->mIsUnspecialized;
  1868. // if (mModule->mModuleName == "BeefTest_TestProgram")
  1869. // {
  1870. // OutputDebugStrF("?Prv: %s\n %s\n?New: %s\n %s\n\n",
  1871. // mModule->MethodToString(prevMethodInstance, BfMethodNameFlag_None, &mBestMethodGenericArguments).c_str(),
  1872. // mModule->MethodToString(prevMethodInstance, BfMethodNameFlag_None).c_str(),
  1873. // mModule->MethodToString(methodInstance, BfMethodNameFlag_None, genericArgumentsSubstitute).c_str(),
  1874. // mModule->MethodToString(methodInstance, BfMethodNameFlag_None).c_str());
  1875. // }
  1876. CompareMethods(prevMethodInstance, &mBestMethodGenericArguments, methodInstance, genericArgumentsSubstitute, &isBetter, &isWorse, allowSpecializeFail);
  1877. // if (mModule->mModuleName == "BeefTest_TestProgram")
  1878. // {
  1879. // OutputDebugStrF("%sPrv: %s\n %s\n%sNew: %s\n %s\n\n",
  1880. // isWorse ? "*" : " ", mModule->MethodToString(prevMethodInstance, BfMethodNameFlag_None, &mBestMethodGenericArguments).c_str(),
  1881. // mModule->MethodToString(prevMethodInstance, BfMethodNameFlag_None).c_str(),
  1882. // isBetter ? "*" : " ", mModule->MethodToString(methodInstance, BfMethodNameFlag_None, genericArgumentsSubstitute).c_str(),
  1883. // mModule->MethodToString(methodInstance, BfMethodNameFlag_None).c_str());
  1884. // }
  1885. // If we had both a 'better' and 'worse', that's ambiguous because the methods are each better in different ways (not allowed)
  1886. // And if neither better nor worse then they are equally good, which is not allowed either
  1887. if (((!isBetter) && (!isWorse)) || ((isBetter) && (isWorse)))
  1888. {
  1889. if (mHasVarArguments)
  1890. {
  1891. if (methodInstance->mReturnType != prevMethodInstance->mReturnType)
  1892. mHadVarConflictingReturnType = true;
  1893. }
  1894. else
  1895. {
  1896. BfAmbiguousEntry ambiguousEntry;
  1897. ambiguousEntry.mMethodInstance = methodInstance;
  1898. if (genericArgumentsSubstitute != NULL)
  1899. ambiguousEntry.mBestMethodGenericArguments = *genericArgumentsSubstitute;
  1900. if (methodInstance->mMethodDef->mGenericParams.size() != 0)
  1901. {
  1902. BF_ASSERT(!ambiguousEntry.mBestMethodGenericArguments.empty());
  1903. }
  1904. mAmbiguousEntries.push_back(ambiguousEntry);
  1905. goto Done;
  1906. }
  1907. }
  1908. if (!isBetter)
  1909. goto Done;
  1910. }
  1911. if ((autoComplete != NULL) && (autoComplete->mIsCapturingMethodMatchInfo))
  1912. {
  1913. auto methodMatchInfo = autoComplete->mMethodMatchInfo;
  1914. // Try to persist with previous partial match, if we have one - this keeps us from locking onto
  1915. // an incorrect method just because it had the current number of params that we've typed so far
  1916. if (methodMatchInfo->mPrevBestIdx == -1)
  1917. {
  1918. methodMatchInfo->mHadExactMatch = true;
  1919. methodMatchInfo->mBestIdx = (int) methodMatchInfo->mInstanceList.size() - 1;
  1920. }
  1921. }
  1922. mAmbiguousEntries.Clear();
  1923. hadMatch = true;
  1924. mBestMethodDef = checkMethod;
  1925. mBestRawMethodInstance = methodInstance;
  1926. for (auto& arg : mArguments)
  1927. arg.mBestBoundType = arg.mTypedValue.mType;
  1928. NoMatch:
  1929. if (!hadMatch)
  1930. {
  1931. if (mBestMethodDef != NULL)
  1932. return false;
  1933. if (checkMethod->mMethodType == BfMethodType_Extension)
  1934. {
  1935. auto thisParam = methodInstance->GetParamType(0);
  1936. auto resolveThisParam = mModule->ResolveGenericType(thisParam, NULL, &mCheckMethodGenericArguments);
  1937. if (resolveThisParam == NULL)
  1938. return false;
  1939. if (!mModule->CanCast(mTarget, resolveThisParam, BfCastFlags_Explicit))
  1940. return false;
  1941. }
  1942. if (mBackupMethodDef != NULL)
  1943. {
  1944. int prevParamDiff = (int)mBackupMethodDef->GetExplicitParamCount() - (int)mArguments.size();
  1945. int paramDiff = (int)checkMethod->GetExplicitParamCount() - (int)mArguments.size();
  1946. if ((prevParamDiff < 0) && (prevParamDiff > paramDiff))
  1947. return false;
  1948. if ((prevParamDiff >= 0) && (paramDiff < 0))
  1949. return false;
  1950. if (argMatchCount < mBackupArgMatchCount)
  1951. return false;
  1952. else if (argMatchCount == mBackupArgMatchCount)
  1953. {
  1954. if (curMatchKind < mBackupMatchKind)
  1955. return false;
  1956. // We search from the most specific type, so don't prefer a less specific type
  1957. if (mBestMethodTypeInstance != typeInstance)
  1958. return false;
  1959. }
  1960. }
  1961. if ((autoComplete != NULL) && (autoComplete->mIsCapturingMethodMatchInfo))
  1962. {
  1963. auto methodMatchInfo = autoComplete->mMethodMatchInfo;
  1964. if ((methodMatchInfo->mPrevBestIdx == -1) && (!methodMatchInfo->mHadExactMatch))
  1965. {
  1966. methodMatchInfo->mBestIdx = (int)methodMatchInfo->mInstanceList.size() - 1;
  1967. }
  1968. }
  1969. mBackupMatchKind = curMatchKind;
  1970. mBackupMethodDef = checkMethod;
  1971. mBackupArgMatchCount = argMatchCount;
  1972. // Lie temporarily to store at least one candidate (but mBestMethodDef is still NULL)
  1973. hadMatch = true;
  1974. }
  1975. if (hadMatch)
  1976. {
  1977. mBestMethodTypeInstance = typeInstance;
  1978. if (genericArgumentsSubstitute != &mBestMethodGenericArguments)
  1979. {
  1980. if (genericArgumentsSubstitute != NULL)
  1981. {
  1982. for (auto& genericArg : *genericArgumentsSubstitute)
  1983. genericArg = mModule->FixIntUnknown(genericArg);
  1984. mBestMethodGenericArguments = *genericArgumentsSubstitute;
  1985. // #ifdef _DEBUG
  1986. // for (auto arg : mBestMethodGenericArguments)
  1987. // BF_ASSERT((arg == NULL) || (!arg->IsVar()));
  1988. // #endif
  1989. }
  1990. else
  1991. mBestMethodGenericArguments.clear();
  1992. }
  1993. }
  1994. Done:
  1995. if ((autoComplete != NULL) && (autoComplete->mIsCapturingMethodMatchInfo) && (genericArgumentsSubstitute != NULL))
  1996. {
  1997. auto methodMatchInfo = autoComplete->mMethodMatchInfo;
  1998. if (!methodMatchInfo->mInstanceList.IsEmpty())
  1999. {
  2000. methodMatchInfo->mInstanceList[methodMatchInfo->mInstanceList.size() - 1].mGenericArguments = *genericArgumentsSubstitute;
  2001. }
  2002. }
  2003. return mBestMethodDef == checkMethod;
  2004. }
  2005. void BfMethodMatcher::FlushAmbiguityError()
  2006. {
  2007. if (!mAmbiguousEntries.empty())
  2008. {
  2009. if (mModule->PreFail())
  2010. {
  2011. BfError* error;
  2012. if (!mMethodName.empty())
  2013. error = mModule->Fail(StrFormat("Ambiguous method call for '%s'", mMethodName.c_str()), mTargetSrc);
  2014. else
  2015. error = mModule->Fail("Ambiguous method call", mTargetSrc);
  2016. if (error != NULL)
  2017. {
  2018. auto unspecializedType = mModule->GetUnspecializedTypeInstance(mBestMethodTypeInstance);
  2019. BfMethodInstance* bestMethodInstance = mModule->GetRawMethodInstance(unspecializedType, mBestMethodDef);
  2020. BfTypeVector* typeGenericArguments = NULL;
  2021. if (mBestMethodTypeInstance->mGenericTypeInfo != NULL)
  2022. typeGenericArguments = &mBestMethodTypeInstance->mGenericTypeInfo->mTypeGenericArguments;
  2023. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("'%s' is a candidate", mModule->MethodToString(bestMethodInstance, BfMethodNameFlag_ResolveGenericParamNames,
  2024. typeGenericArguments, mBestMethodGenericArguments.empty() ? NULL : &mBestMethodGenericArguments).c_str()),
  2025. bestMethodInstance->mMethodDef->GetRefNode());
  2026. for (auto& ambiguousEntry : mAmbiguousEntries)
  2027. {
  2028. auto typeInstance = ambiguousEntry.mMethodInstance->GetOwner();
  2029. auto unspecTypeMethodInstance = mModule->GetUnspecializedMethodInstance(ambiguousEntry.mMethodInstance, true);
  2030. BfTypeVector* typeGenericArguments = NULL;
  2031. if (typeInstance->mGenericTypeInfo != NULL)
  2032. typeGenericArguments = &typeInstance->mGenericTypeInfo->mTypeGenericArguments;
  2033. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("'%s' is a candidate", mModule->MethodToString(unspecTypeMethodInstance, BfMethodNameFlag_ResolveGenericParamNames,
  2034. typeGenericArguments, ambiguousEntry.mBestMethodGenericArguments.empty() ? NULL : &ambiguousEntry.mBestMethodGenericArguments).c_str()),
  2035. ambiguousEntry.mMethodInstance->mMethodDef->GetRefNode());
  2036. }
  2037. }
  2038. }
  2039. mAmbiguousEntries.Clear();
  2040. }
  2041. }
  2042. bool BfMethodMatcher::IsType(BfTypedValue& typedVal, BfType* type)
  2043. {
  2044. if (typedVal.mType == type)
  2045. return true;
  2046. if (!typedVal)
  2047. return false;
  2048. if (!typedVal.mType->IsPrimitiveType())
  2049. return false;
  2050. if (!type->IsPrimitiveType())
  2051. return false;
  2052. auto fromPrimType = typedVal.mType->ToPrimitiveType();
  2053. if ((fromPrimType->mTypeDef->mTypeCode != BfTypeCode_IntUnknown) &&
  2054. (fromPrimType->mTypeDef->mTypeCode != BfTypeCode_UIntUnknown))
  2055. return false;
  2056. auto constant = mModule->mBfIRBuilder->GetConstant(typedVal.mValue);
  2057. if (constant == NULL)
  2058. return false;
  2059. auto toPrimType = type->ToPrimitiveType();
  2060. if (!mModule->mBfIRBuilder->IsInt(toPrimType->mTypeDef->mTypeCode))
  2061. return false;
  2062. if (type->mSize == 8)
  2063. return false;
  2064. int64 minVal = -(1LL << (8 * type->mSize - 1));
  2065. int64 maxVal = (1LL << (8 * type->mSize - 1)) - 1;
  2066. if ((constant->mInt64 >= minVal) && (constant->mInt64 <= maxVal))
  2067. return true;
  2068. return false;
  2069. }
  2070. // This method checks all base classes before checking interfaces. Is that correct?
  2071. bool BfMethodMatcher::CheckType(BfTypeInstance* typeInstance, BfTypedValue target, bool isFailurePass, bool forceOuterCheck)
  2072. {
  2073. BfMethodDef* prevBesstMethodDef = mBestMethodDef;
  2074. auto curTypeInst = typeInstance;
  2075. auto curTypeDef = typeInstance->mTypeDef;
  2076. int checkInterfaceIdx = 0;
  2077. bool targetIsBase = target.IsBase();
  2078. bool checkExtensionBase = false;
  2079. if (targetIsBase)
  2080. {
  2081. if ((curTypeInst == mModule->mCurTypeInstance) && (curTypeInst->mTypeDef->mIsCombinedPartial))
  2082. {
  2083. checkExtensionBase = true;
  2084. }
  2085. else
  2086. {
  2087. curTypeInst = curTypeInst->mBaseType;
  2088. }
  2089. }
  2090. BfTypeInstance* targetTypeInstance = NULL;
  2091. if (target.mType != NULL)
  2092. targetTypeInstance = target.mType->ToTypeInstance();
  2093. while (true)
  2094. {
  2095. bool doSearch = true;
  2096. if ((mMethodType == BfMethodType_Extension) && (!curTypeDef->mHasExtensionMethods))
  2097. doSearch = false;
  2098. BfMethodDef* nextMethodDef = NULL;
  2099. if (doSearch)
  2100. {
  2101. curTypeDef->PopulateMemberSets();
  2102. BfMemberSetEntry* entry;
  2103. if (curTypeDef->mMethodSet.TryGetWith(mMethodName, &entry))
  2104. nextMethodDef = (BfMethodDef*)entry->mMemberDef;
  2105. }
  2106. BfProtectionCheckFlags protectionCheckFlags = BfProtectionCheckFlag_None;
  2107. if (target)
  2108. {
  2109. if (mBypassVirtual)
  2110. {
  2111. // Not an "instance lookup"
  2112. }
  2113. else
  2114. {
  2115. protectionCheckFlags = (BfProtectionCheckFlags)(protectionCheckFlags | BfProtectionCheckFlag_InstanceLookup);
  2116. }
  2117. }
  2118. while (nextMethodDef != NULL)
  2119. {
  2120. bool allowExplicitInterface = curTypeInst->IsInterface() && mBypassVirtual;
  2121. auto activeTypeDef = mModule->GetActiveTypeDef();
  2122. auto visibleProjectSet = mModule->GetVisibleProjectSet();
  2123. bool isDelegate = typeInstance->IsDelegate();
  2124. auto checkMethod = nextMethodDef;
  2125. nextMethodDef = nextMethodDef->mNextWithSameName;
  2126. if (mModule->mContext->mResolvingVarField)
  2127. {
  2128. bool isResolvingVarField = false;
  2129. auto checkTypeState = mModule->mContext->mCurTypeState;
  2130. while (checkTypeState != NULL)
  2131. {
  2132. if ((checkTypeState->mResolveKind == BfTypeState::ResolveKind_ResolvingVarType) &&
  2133. (checkTypeState->mTypeInstance == typeInstance))
  2134. isResolvingVarField = true;
  2135. checkTypeState = checkTypeState->mPrevState;
  2136. }
  2137. if (isResolvingVarField)
  2138. {
  2139. // Don't even consider - we can't do method calls on ourselves when we are resolving var fields, because
  2140. // we are not allowed to generate methods when our field types are unknown. We may fix this in the future,
  2141. // but currently it breaks out expected order of operations. One issue is that our call signatures change
  2142. // depending on whether we are valueless or splattable, which depend on underlying type information
  2143. break;
  2144. }
  2145. }
  2146. if ((checkExtensionBase) && (curTypeInst == mModule->mCurTypeInstance))
  2147. {
  2148. // Accept either a method in the same project but that's the root definition, OR a method that's in a dependent project
  2149. bool accept = false;
  2150. if (activeTypeDef->mProject == checkMethod->mDeclaringType->mProject)
  2151. accept = (activeTypeDef->IsExtension()) && (!checkMethod->mDeclaringType->IsExtension());
  2152. else
  2153. accept = activeTypeDef->mProject->ContainsReference(checkMethod->mDeclaringType->mProject);
  2154. if (!accept)
  2155. continue;
  2156. }
  2157. if ((!allowExplicitInterface) && (checkMethod->mExplicitInterface != NULL) && (mInterfaceMethodInstance == NULL))
  2158. {
  2159. continue;
  2160. }
  2161. if (checkMethod->mMethodType != mMethodType)
  2162. continue;
  2163. // if (checkMethod->mName != mMethodName)
  2164. // continue;
  2165. if ((checkMethod->mDeclaringType->IsExtension()) && (mModule->mAttributeState != NULL) && (mModule->mAttributeState->mCustomAttributes != NULL) &&
  2166. (mModule->mAttributeState->mCustomAttributes->Contains(mModule->mCompiler->mNoExtensionAttributeTypeDef)))
  2167. {
  2168. mModule->mAttributeState->mUsed = true;
  2169. continue;
  2170. }
  2171. if (!isDelegate)
  2172. {
  2173. if ((!curTypeInst->IsTypeMemberIncluded(checkMethod->mDeclaringType, activeTypeDef, mModule)) ||
  2174. (!curTypeInst->IsTypeMemberAccessible(checkMethod->mDeclaringType, visibleProjectSet)))
  2175. continue;
  2176. }
  2177. MatchFailKind matchFailKind = MatchFailKind_None;
  2178. if (!mModule->CheckProtection(protectionCheckFlags, curTypeInst, checkMethod->mDeclaringType->mProject, checkMethod->mProtection, typeInstance))
  2179. {
  2180. if ((mBypassVirtual) &&
  2181. ((checkMethod->mProtection == BfProtection_Protected) || (checkMethod->mProtection == BfProtection_ProtectedInternal)) &&
  2182. (mModule->TypeIsSubTypeOf(mModule->mCurTypeInstance, typeInstance)))
  2183. {
  2184. // Allow explicit 'base' call
  2185. }
  2186. else
  2187. {
  2188. if (!isFailurePass)
  2189. continue;
  2190. matchFailKind = MatchFailKind_Protection;
  2191. }
  2192. }
  2193. if (mCheckedKind != checkMethod->mCheckedKind)
  2194. {
  2195. bool passes = true;
  2196. if (mCheckedKind != BfCheckedKind_NotSet)
  2197. {
  2198. passes = false;
  2199. }
  2200. else
  2201. {
  2202. auto defaultCheckedKind = mModule->GetDefaultCheckedKind();
  2203. if (defaultCheckedKind != checkMethod->mCheckedKind)
  2204. passes = false;
  2205. }
  2206. if (!passes)
  2207. {
  2208. if (!isFailurePass)
  2209. continue;
  2210. matchFailKind = MatchFailKind_CheckedMismatch;
  2211. }
  2212. }
  2213. CheckMethod(targetTypeInstance, curTypeInst, checkMethod, isFailurePass);
  2214. if ((isFailurePass) &&
  2215. ((mBestMethodDef == checkMethod) || (mBackupMethodDef == checkMethod)))
  2216. mMatchFailKind = matchFailKind;
  2217. }
  2218. if ((mBestMethodDef != NULL) && (mMethodType != BfMethodType_Extension))
  2219. {
  2220. if (mAutoFlushAmbiguityErrors)
  2221. FlushAmbiguityError();
  2222. return true;
  2223. }
  2224. auto baseType = curTypeInst->mBaseType;
  2225. if (baseType == NULL)
  2226. {
  2227. //TODO: Why were we doing the interface checking?
  2228. if ((curTypeInst->IsInterface()) && (curTypeInst == target.mType))
  2229. {
  2230. // When we are directly calling on interfaces rather than indirectly matching through binding
  2231. baseType = mModule->mContext->mBfObjectType;
  2232. }
  2233. else if ((curTypeInst != mModule->mContext->mBfObjectType) && (!curTypeInst->IsInterface()))
  2234. {
  2235. // This can happen for structs
  2236. baseType = mModule->mContext->mBfObjectType;
  2237. }
  2238. else if ((typeInstance->IsInterface()) && (checkInterfaceIdx < (int)typeInstance->mInterfaces.size()))
  2239. {
  2240. baseType = typeInstance->mInterfaces[checkInterfaceIdx].mInterfaceType;
  2241. checkInterfaceIdx++;
  2242. }
  2243. else
  2244. {
  2245. break;
  2246. }
  2247. }
  2248. curTypeDef = baseType->mTypeDef;
  2249. curTypeInst = baseType;
  2250. if ((isFailurePass) && (mBackupMethodDef != NULL))
  2251. break;
  2252. }
  2253. if (mBestMethodDef == NULL)
  2254. {
  2255. // FAILED, but select the first method which will fire an actual error on param type matching
  2256. mBestMethodDef = mBackupMethodDef;
  2257. }
  2258. if (((mBestMethodDef == NULL) && (!target) && (mAllowImplicitThis)) ||
  2259. (forceOuterCheck))
  2260. {
  2261. // No explicit target - maybe this was a static call in the outer type?
  2262. auto outerType = mModule->GetOuterType(typeInstance);
  2263. if (outerType != NULL)
  2264. CheckOuterTypeStaticMethods(outerType, isFailurePass);
  2265. }
  2266. if (mAutoFlushAmbiguityErrors)
  2267. FlushAmbiguityError();
  2268. return mBestMethodDef != prevBesstMethodDef;
  2269. }
  2270. void BfMethodMatcher::TryDevirtualizeCall(BfTypedValue target, BfTypedValue* origTarget, BfTypedValue* staticResult)
  2271. {
  2272. if ((mBestMethodDef == NULL) || (target.mType == NULL))
  2273. return;
  2274. if ((mModule->mCompiler->IsAutocomplete()) || (mModule->mContext->mResolvingVarField))
  2275. return;
  2276. if ((mModule->mBfIRBuilder->mIgnoreWrites) && (!mBestMethodDef->mIsConcrete))
  2277. return;
  2278. if (mBestMethodTypeInstance->IsInterface())
  2279. {
  2280. mModule->PopulateType(mBestMethodTypeInstance, BfPopulateType_DataAndMethods);
  2281. auto activeTypeDef = mModule->GetActiveTypeDef();
  2282. // Statically map this call
  2283. auto checkType = target.mType;
  2284. if (checkType->IsPointer())
  2285. checkType = ((BfPointerType*)checkType)->mElementType;
  2286. if (checkType->IsWrappableType())
  2287. checkType = mModule->GetWrappedStructType(checkType);
  2288. if ((checkType != NULL) && (checkType->IsTypeInstance()) && (!checkType->IsInterface()))
  2289. {
  2290. BfTypeInterfaceEntry* bestIFaceEntry = NULL;
  2291. auto checkTypeInst = checkType->ToTypeInstance();
  2292. if (mBestMethodTypeInstance->mTypeDef == mModule->mCompiler->mIHashableTypeDef)
  2293. {
  2294. if ((origTarget != NULL) && (origTarget->mType->IsPointer()) && (staticResult != NULL))
  2295. {
  2296. BfTypedValue ptrVal = mModule->LoadValue(*origTarget);
  2297. *staticResult = BfTypedValue(mModule->mBfIRBuilder->CreatePtrToInt(ptrVal.mValue, BfTypeCode_IntPtr), mModule->GetPrimitiveType(BfTypeCode_IntPtr));
  2298. return;
  2299. }
  2300. }
  2301. while (checkTypeInst != NULL)
  2302. {
  2303. mModule->PopulateType(checkTypeInst, BfPopulateType_DataAndMethods);
  2304. for (auto&& iface : checkTypeInst->mInterfaces)
  2305. {
  2306. //TODO: Why did we have this check? This caused Dictionary to not be able to devirtualize
  2307. // calls to TKey GetHashCode when TKey was from a user's project...
  2308. /*if (!checkTypeInst->IsTypeMemberAccessible(iface.mDeclaringType, activeTypeDef))
  2309. continue;*/
  2310. if (iface.mInterfaceType == mBestMethodTypeInstance)
  2311. {
  2312. if (bestIFaceEntry == NULL)
  2313. {
  2314. bestIFaceEntry = &iface;
  2315. continue;
  2316. }
  2317. bool isBetter;
  2318. bool isWorse;
  2319. mModule->CompareDeclTypes(iface.mDeclaringType, bestIFaceEntry->mDeclaringType, isBetter, isWorse);
  2320. if (isBetter == isWorse)
  2321. {
  2322. // Failed
  2323. }
  2324. else
  2325. {
  2326. if (isBetter)
  2327. bestIFaceEntry = &iface;
  2328. }
  2329. }
  2330. }
  2331. if (bestIFaceEntry != NULL)
  2332. break;
  2333. checkTypeInst = checkTypeInst->mBaseType;
  2334. if ((checkTypeInst == NULL) && (checkType->HasWrappedRepresentation()))
  2335. {
  2336. auto underlyingType = checkType->GetUnderlyingType();
  2337. if ((underlyingType != NULL) && (underlyingType->IsWrappableType()))
  2338. checkTypeInst = mModule->GetWrappedStructType(underlyingType);
  2339. }
  2340. }
  2341. if (bestIFaceEntry != NULL)
  2342. {
  2343. auto ifaceMethodEntry = checkTypeInst->mInterfaceMethodTable[bestIFaceEntry->mStartInterfaceTableIdx + mBestMethodDef->mIdx];
  2344. BfMethodInstance* bestMethodInstance = ifaceMethodEntry.mMethodRef;
  2345. if (bestMethodInstance != NULL)
  2346. {
  2347. bool isMissingArg = false;
  2348. for (auto genericArg : mBestMethodGenericArguments)
  2349. {
  2350. if (genericArg == NULL)
  2351. isMissingArg = true;
  2352. }
  2353. if (!isMissingArg)
  2354. {
  2355. // Assert error state?
  2356. mBestMethodTypeInstance = ifaceMethodEntry.mMethodRef.mTypeInstance;
  2357. mBestMethodDef = bestMethodInstance->mMethodDef;
  2358. mBestMethodInstance = mModule->GetMethodInstance(mBestMethodTypeInstance, bestMethodInstance->mMethodDef, mBestMethodGenericArguments,
  2359. bestMethodInstance->mIsForeignMethodDef ? BfGetMethodInstanceFlag_ForeignMethodDef : BfGetMethodInstanceFlag_None,
  2360. bestMethodInstance->GetForeignType());
  2361. }
  2362. }
  2363. else
  2364. {
  2365. // Failed
  2366. mFakeConcreteTarget = true;
  2367. }
  2368. }
  2369. }
  2370. }
  2371. if ((target.mType->IsValueType()) && (mBestMethodTypeInstance->IsObject()) && (mBestMethodDef->mIsVirtual))
  2372. {
  2373. auto structType = target.mType->ToTypeInstance();
  2374. auto virtualMethodInstance = mModule->GetMethodInstance(mBestMethodTypeInstance, mBestMethodDef, BfTypeVector());
  2375. BF_ASSERT(virtualMethodInstance.mMethodInstance->mVirtualTableIdx != -1);
  2376. BfTypeInstance* boxedType;
  2377. if (structType->HasOverrideMethods())
  2378. {
  2379. // We don't actually need this boxed type, so just resolve it unreified
  2380. auto useModule = mModule->mContext->mUnreifiedModule;
  2381. boxedType = useModule->CreateBoxedType(target.mType);
  2382. useModule->PopulateType(boxedType, BfPopulateType_DataAndMethods);
  2383. useModule->AddDependency(boxedType, mModule->mCurTypeInstance, BfDependencyMap::DependencyFlag_WeakReference);
  2384. }
  2385. else
  2386. {
  2387. boxedType = mModule->mContext->mBfObjectType;
  2388. }
  2389. auto methodRef = boxedType->mVirtualMethodTable[virtualMethodInstance.mMethodInstance->mVirtualTableIdx];
  2390. if (methodRef.mImplementingMethod.mTypeInstance->IsBoxed())
  2391. {
  2392. auto useModule = mModule->mContext->mUnreifiedModule;
  2393. auto boxedMethodInstance = useModule->ReferenceExternalMethodInstance(methodRef.mImplementingMethod);
  2394. BfBoxedType* vBoxedType = (BfBoxedType*)methodRef.mImplementingMethod.mTypeInstance;
  2395. mBestMethodTypeInstance = vBoxedType->mElementType->ToTypeInstance();
  2396. mBestMethodInstance = mModule->GetMethodInstance(mBestMethodTypeInstance, boxedMethodInstance.mMethodInstance->mMethodDef, BfTypeVector());
  2397. mBestMethodDef = mBestMethodInstance.mMethodInstance->mMethodDef;
  2398. }
  2399. else
  2400. {
  2401. mBestMethodTypeInstance = methodRef.mImplementingMethod.mTypeInstance;
  2402. mBestMethodInstance = mModule->ReferenceExternalMethodInstance(methodRef.mImplementingMethod);
  2403. mBestMethodDef = mBestMethodInstance.mMethodInstance->mMethodDef;
  2404. }
  2405. mBypassVirtual = true;
  2406. }
  2407. }
  2408. bool BfMethodMatcher::HasVarGenerics()
  2409. {
  2410. for (auto genericArg : mBestMethodGenericArguments)
  2411. if (genericArg->IsVar())
  2412. return true;
  2413. for (auto genericArg : mExplicitMethodGenericArguments)
  2414. if (genericArg->IsVar())
  2415. return true;
  2416. return false;
  2417. }
  2418. void BfMethodMatcher::CheckOuterTypeStaticMethods(BfTypeInstance* typeInstance, bool isFailurePass)
  2419. {
  2420. bool allowPrivate = true;
  2421. bool allowProtected = true;
  2422. auto curTypeInst = typeInstance;
  2423. auto curTypeDef = typeInstance->mTypeDef;
  2424. while (true)
  2425. {
  2426. curTypeDef->PopulateMemberSets();
  2427. BfMethodDef* nextMethodDef = NULL;
  2428. BfMemberSetEntry* entry;
  2429. if (curTypeDef->mMethodSet.TryGetWith(mMethodName, &entry))
  2430. nextMethodDef = (BfMethodDef*)entry->mMemberDef;
  2431. while (nextMethodDef != NULL)
  2432. {
  2433. auto checkMethod = nextMethodDef;
  2434. nextMethodDef = nextMethodDef->mNextWithSameName;
  2435. // These can only be invoked when the target itself is the interface
  2436. if (checkMethod->mExplicitInterface != NULL)
  2437. continue;
  2438. if ((checkMethod->mMethodType != mMethodType) || (!checkMethod->mIsStatic))
  2439. continue;
  2440. if (checkMethod->mName != mMethodName)
  2441. continue;
  2442. if ((!isFailurePass) && (!mModule->CheckProtection(checkMethod->mProtection, NULL, allowProtected, allowPrivate)))
  2443. continue;
  2444. CheckMethod(typeInstance, curTypeInst, checkMethod, isFailurePass);
  2445. }
  2446. if (mBestMethodDef != NULL)
  2447. return;
  2448. auto baseType = curTypeInst->mBaseType;
  2449. if (baseType == NULL)
  2450. break;
  2451. curTypeDef = baseType->mTypeDef;
  2452. curTypeInst = baseType;
  2453. allowPrivate = false;
  2454. if ((isFailurePass) && (mBackupMethodDef != NULL))
  2455. break;
  2456. }
  2457. if (mBestMethodDef == NULL)
  2458. {
  2459. // FAILED, but select the first method which will fire an actual error on param type matching
  2460. mBestMethodDef = mBackupMethodDef;
  2461. }
  2462. if (mBestMethodDef == NULL)
  2463. {
  2464. // No explicit target - maybe this was a static call in the outer type?
  2465. auto outerType = mModule->GetOuterType(typeInstance);
  2466. if (outerType != NULL)
  2467. CheckOuterTypeStaticMethods(outerType, isFailurePass);
  2468. }
  2469. }
  2470. //////////////////////////////////////////////////////////////////////////
  2471. void BfResolvedArgs::HandleFixits(BfModule* module)
  2472. {
  2473. auto compiler = module->mCompiler;
  2474. if ((!compiler->IsAutocomplete()) || (compiler->mResolvePassData->mResolveType != BfResolveType_GetFixits))
  2475. return;
  2476. SetAndRestoreValue<bool> ignoreErrors(module->mIgnoreErrors, true);
  2477. for (int argIdx = 0; argIdx < (int)mResolvedArgs.size(); argIdx++)
  2478. {
  2479. auto& resolvedArg = mResolvedArgs[argIdx];
  2480. auto expr = BfNodeDynCast<BfExpression>(resolvedArg.mExpression);
  2481. if (expr != NULL)
  2482. {
  2483. module->CreateValueFromExpression(expr, resolvedArg.mExpectedType);
  2484. }
  2485. }
  2486. }
  2487. //////////////////////////////////////////////////////////////////////////
  2488. BfExprEvaluator::BfExprEvaluator(BfModule* module)
  2489. {
  2490. mBfEvalExprFlags = BfEvalExprFlags_None;
  2491. mModule = module;
  2492. mPropDef = NULL;
  2493. mPropSrc = NULL;
  2494. mPropGetMethodFlags = BfGetMethodInstanceFlag_None;
  2495. mPropCheckedKind = BfCheckedKind_NotSet;
  2496. mUsedAsStatement = false;
  2497. mPropDefBypassVirtual = false;
  2498. mExpectingType = NULL;
  2499. mFunctionBindResult = NULL;
  2500. mExplicitCast = false;
  2501. mDeferCallRef = NULL;
  2502. mDeferScopeAlloc = NULL;
  2503. mPrefixedAttributeState = NULL;
  2504. mResolveGenericParam = true;
  2505. mNoBind = false;
  2506. mResultLocalVar = NULL;
  2507. mResultFieldInstance = NULL;
  2508. mResultLocalVarField = 0;
  2509. mResultLocalVarFieldCount = 0;
  2510. mResultLocalVarRefNode = NULL;
  2511. mIsVolatileReference = false;
  2512. mIsHeapReference = false;
  2513. mResultIsTempComposite = false;
  2514. mAllowReadOnlyReference = false;
  2515. mInsidePendingNullable = false;
  2516. mReceivingValue = NULL;
  2517. }
  2518. BfExprEvaluator::~BfExprEvaluator()
  2519. {
  2520. }
  2521. BfAutoComplete* BfExprEvaluator::GetAutoComplete()
  2522. {
  2523. if (mModule->mCompiler->mResolvePassData == NULL)
  2524. return NULL;
  2525. if ((mBfEvalExprFlags & BfEvalExprFlags_NoAutoComplete) != 0)
  2526. return NULL;
  2527. // For local methods- only process autocomplete on capture phase
  2528. if ((mModule->mCurMethodState != NULL) && (mModule->mCurMethodState->mClosureState != NULL) && (!mModule->mCurMethodState->mClosureState->mCapturing))
  2529. return NULL;
  2530. // if ((mModule->mCurMethodInstance != NULL) && (mModule->mCurMethodInstance->mMethodDef->mIsLocalMethod))
  2531. // return NULL;
  2532. return mModule->mCompiler->mResolvePassData->mAutoComplete;
  2533. }
  2534. bool BfExprEvaluator::IsComptime()
  2535. {
  2536. return (mModule->mIsComptimeModule) || ((mBfEvalExprFlags & BfEvalExprFlags_Comptime) != 0);
  2537. }
  2538. bool BfExprEvaluator::IsComptimeEntry()
  2539. {
  2540. if (mModule->mIsComptimeModule)
  2541. return false;
  2542. return ((mBfEvalExprFlags & BfEvalExprFlags_Comptime) != 0);
  2543. }
  2544. int BfExprEvaluator::GetStructRetIdx(BfMethodInstance* methodInstance, bool forceStatic)
  2545. {
  2546. if (IsComptime())
  2547. return -1;
  2548. return methodInstance->GetStructRetIdx(forceStatic);
  2549. }
  2550. BfType* BfExprEvaluator::BindGenericType(BfAstNode* node, BfType* bindType)
  2551. {
  2552. if ((mModule->mCurMethodState == NULL) || (mModule->mCurMethodInstance == NULL) || (bindType == NULL))
  2553. return bindType;
  2554. if ((mModule->mCurMethodState->mClosureState != NULL) && (mModule->mCurMethodState->mClosureState->mCapturing))
  2555. return bindType;
  2556. if ((mBfEvalExprFlags & BfEvalExprFlags_DeclType) != 0)
  2557. return bindType;
  2558. BF_ASSERT(!mModule->mCurMethodInstance->mIsUnspecializedVariation);
  2559. auto parser = node->GetSourceData()->ToParserData();
  2560. if (parser == NULL)
  2561. return bindType;
  2562. int64 nodeId = ((int64)parser->mDataId << 32) + node->GetSrcStart();
  2563. auto genericTypeBindings = mModule->mCurMethodState->GetRootMethodState()->mGenericTypeBindings;
  2564. if (mModule->mCurMethodInstance->mIsUnspecialized)
  2565. {
  2566. if (!bindType->IsGenericParam())
  2567. return bindType;
  2568. if (genericTypeBindings == NULL)
  2569. return bindType;
  2570. (*genericTypeBindings)[nodeId] = bindType;
  2571. return bindType;
  2572. }
  2573. else
  2574. {
  2575. if (genericTypeBindings == NULL)
  2576. return bindType;
  2577. BfType** typePtr = NULL;
  2578. if (genericTypeBindings->TryGetValue(nodeId, &typePtr))
  2579. return *typePtr;
  2580. return bindType;
  2581. }
  2582. }
  2583. BfType * BfExprEvaluator::ResolveTypeRef(BfTypeReference* typeRef, BfPopulateType populateType, BfResolveTypeRefFlags resolveFlags)
  2584. {
  2585. if (mExpectingType != NULL)
  2586. {
  2587. if (auto namedTypeRef = BfNodeDynCastExact<BfNamedTypeReference>(typeRef))
  2588. {
  2589. if (namedTypeRef->ToString() == "ExpectedType")
  2590. {
  2591. return mModule->ResolveTypeResult(typeRef, mExpectingType, populateType, resolveFlags);
  2592. }
  2593. }
  2594. }
  2595. return mModule->ResolveTypeRef(typeRef, populateType, resolveFlags);
  2596. }
  2597. void BfExprEvaluator::ResolveGenericType()
  2598. {
  2599. if (mResult)
  2600. {
  2601. if (mModule->IsUnboundGeneric(mResult.mType))
  2602. mResult.mType = mModule->GetPrimitiveType(BfTypeCode_Var);
  2603. //mResult.mType = mModule->ResolveGenericType(mResult.mType, true);
  2604. }
  2605. }
  2606. void BfExprEvaluator::Evaluate(BfAstNode* astNode, bool propogateNullConditional, bool ignoreNullConditional, bool allowSplat)
  2607. {
  2608. BP_ZONE("BfExprEvaluator::Evaluate");
  2609. // ParenthesizedExpression breaks null conditional chain
  2610. if (astNode->IsExact<BfParenthesizedExpression>())
  2611. propogateNullConditional = false;
  2612. BfPendingNullConditional* pendingNullCond = NULL;
  2613. if (mModule->mCurMethodState != NULL)
  2614. {
  2615. pendingNullCond = mModule->mCurMethodState->mPendingNullConditional;
  2616. if (!propogateNullConditional)
  2617. mModule->mCurMethodState->mPendingNullConditional = NULL;
  2618. }
  2619. mInsidePendingNullable = pendingNullCond != NULL;
  2620. astNode->Accept(this);
  2621. GetResult();
  2622. if ((mResultIsTempComposite) && (mResult.IsAddr()))
  2623. mResult.mKind = BfTypedValueKind_TempAddr;
  2624. if ((!allowSplat) && (mResult.IsSplat()))
  2625. mResult = mModule->AggregateSplat(mResult);
  2626. if ((mBfEvalExprFlags & BfEvalExprFlags_AllowIntUnknown) == 0)
  2627. mModule->FixIntUnknown(mResult);
  2628. if ((!propogateNullConditional) && (mModule->mCurMethodState != NULL))
  2629. {
  2630. if (mModule->mCurMethodState->mPendingNullConditional != NULL)
  2631. mResult = mModule->FlushNullConditional(mResult, ignoreNullConditional);
  2632. mModule->mCurMethodState->mPendingNullConditional = pendingNullCond;
  2633. }
  2634. }
  2635. void BfExprEvaluator::Visit(BfErrorNode* errorNode)
  2636. {
  2637. mModule->Fail("Invalid token", errorNode);
  2638. auto autoComplete = GetAutoComplete();
  2639. if (autoComplete != NULL)
  2640. {
  2641. if (auto tokenNode = BfNodeDynCast<BfTokenNode>(errorNode->mRefNode))
  2642. return;
  2643. autoComplete->CheckIdentifier(errorNode->mRefNode, true);
  2644. }
  2645. }
  2646. void BfExprEvaluator::Visit(BfTypeReference* typeRef)
  2647. {
  2648. mResult.mType = ResolveTypeRef(typeRef, BfPopulateType_Declaration);
  2649. }
  2650. void BfExprEvaluator::Visit(BfAttributedExpression* attribExpr)
  2651. {
  2652. BfAttributeState attributeState;
  2653. attributeState.mSrc = attribExpr->mAttributes;
  2654. attributeState.mTarget = (BfAttributeTargets)(BfAttributeTargets_Invocation | BfAttributeTargets_MemberAccess);
  2655. if (auto block = BfNodeDynCast<BfBlock>(attribExpr->mExpression))
  2656. attributeState.mTarget = BfAttributeTargets_Block;
  2657. attributeState.mCustomAttributes = mModule->GetCustomAttributes(attribExpr->mAttributes, attributeState.mTarget);
  2658. SetAndRestoreValue<BfAttributeState*> prevAttributeState(mModule->mAttributeState, &attributeState);
  2659. if (auto ignoreErrorsAttrib = attributeState.mCustomAttributes->Get(mModule->mCompiler->mIgnoreErrorsAttributeTypeDef))
  2660. {
  2661. SetAndRestoreValue<bool> ignoreErrors(mModule->mIgnoreErrors, true);
  2662. if (!ignoreErrorsAttrib->mCtorArgs.IsEmpty())
  2663. {
  2664. auto constant = mModule->mCurTypeInstance->mConstHolder->GetConstant(ignoreErrorsAttrib->mCtorArgs[0]);
  2665. if (constant->mBool)
  2666. attributeState.mFlags = BfAttributeState::Flag_StopOnError;
  2667. }
  2668. VisitChild(attribExpr->mExpression);
  2669. attributeState.mUsed = true;
  2670. if ((!mResult) ||
  2671. ((mResult) && (mResult.mType->IsVar())))
  2672. {
  2673. if (!mResult)
  2674. mModule->Fail("Expression did not result in a value", attribExpr->mExpression);
  2675. // Make empty or 'var' resolve as 'false' because var is only valid if we threw errors
  2676. mResult = mModule->GetDefaultTypedValue(mModule->GetPrimitiveType(BfTypeCode_Boolean));
  2677. }
  2678. }
  2679. else
  2680. {
  2681. VisitChild(attribExpr->mExpression);
  2682. }
  2683. mModule->FinishAttributeState(&attributeState);
  2684. }
  2685. void BfExprEvaluator::Visit(BfBlock* blockExpr)
  2686. {
  2687. if (mModule->mCurMethodState == NULL)
  2688. {
  2689. mModule->Fail("Illegal use of block expression", blockExpr);
  2690. return;
  2691. }
  2692. auto autoComplete = GetAutoComplete();
  2693. if ((autoComplete != NULL) && (autoComplete->mMethodMatchInfo != NULL) && (autoComplete->IsAutocompleteNode(blockExpr)))
  2694. {
  2695. // Don't show outer method match info when our cursor is inside a block (being passed as a parameter)
  2696. autoComplete->RemoveMethodMatchInfo();
  2697. }
  2698. if (blockExpr->mChildArr.IsEmpty())
  2699. {
  2700. mModule->Fail("An empty block cannot be used as an expression", blockExpr);
  2701. return;
  2702. }
  2703. bool lastWasResultExpr = false;
  2704. if (auto lastExpr = BfNodeDynCast<BfExpressionStatement>(blockExpr->mChildArr.GetLast()))
  2705. {
  2706. if (!lastExpr->IsMissingSemicolon())
  2707. mModule->Fail("Expression blocks must end in an expression which is missing its terminating semicolon", lastExpr->mTrailingSemicolon);
  2708. }
  2709. else if (blockExpr->mChildArr.GetLast()->IsExpression())
  2710. {
  2711. // Expression
  2712. }
  2713. else
  2714. {
  2715. mModule->Fail("Expression blocks must end with an expression", blockExpr);
  2716. }
  2717. mModule->VisitEmbeddedStatement(blockExpr, this, BfNodeIsA<BfUnscopedBlock>(blockExpr) ? BfEmbeddedStatementFlags_Unscoped : BfEmbeddedStatementFlags_None);
  2718. }
  2719. bool BfExprEvaluator::CheckVariableDeclaration(BfAstNode* checkNode, bool requireSimpleIfExpr, bool exprMustBeTrue, bool silentFail)
  2720. {
  2721. BfAstNode* checkChild = checkNode;
  2722. bool childWasAndRHS = false;
  2723. bool foundIf = false;
  2724. auto parentNodeEntry = mModule->mParentNodeEntry;
  2725. if (parentNodeEntry != NULL)
  2726. {
  2727. if (BfNodeIsA<BfInvocationExpression>(parentNodeEntry->mNode))
  2728. {
  2729. checkChild = parentNodeEntry->mNode;
  2730. parentNodeEntry = parentNodeEntry->mPrev;
  2731. }
  2732. }
  2733. auto _Fail = [&](const StringImpl& errorStr, BfAstNode* node)
  2734. {
  2735. if (!silentFail)
  2736. {
  2737. auto error = mModule->Fail(errorStr, node);
  2738. if ((error != NULL) && (node != checkNode))
  2739. {
  2740. mModule->mCompiler->mPassInstance->MoreInfo("See variable declaration", checkNode);
  2741. }
  2742. }
  2743. return false;
  2744. };
  2745. while (parentNodeEntry != NULL)
  2746. {
  2747. BfAstNode* checkParent = parentNodeEntry->mNode;
  2748. if (auto binOpExpr = BfNodeDynCastExact<BfBinaryOperatorExpression>(checkParent))
  2749. {
  2750. if (binOpExpr->mOp == BfBinaryOp_ConditionalAnd)
  2751. {
  2752. // This is always okay
  2753. childWasAndRHS = (binOpExpr->mRight != NULL) && (binOpExpr->mRight->Contains(checkChild));
  2754. }
  2755. else if ((binOpExpr->mOp == BfBinaryOp_ConditionalOr) && (!exprMustBeTrue))
  2756. {
  2757. if ((binOpExpr->mRight != NULL) && (binOpExpr->mRight->Contains(checkChild)))
  2758. {
  2759. return _Fail("Conditional short-circuiting may skip variable initialization", binOpExpr->mOpToken);
  2760. }
  2761. }
  2762. else
  2763. {
  2764. if (exprMustBeTrue)
  2765. {
  2766. return _Fail("Operator cannot be used with variable initialization", binOpExpr->mOpToken);
  2767. }
  2768. }
  2769. }
  2770. else if (auto parenExpr = BfNodeDynCast<BfParenthesizedExpression>(checkParent))
  2771. {
  2772. // This is okay
  2773. }
  2774. else if (auto unaryOp = BfNodeDynCast<BfUnaryOperatorExpression>(checkParent))
  2775. {
  2776. if (exprMustBeTrue)
  2777. {
  2778. return _Fail("Operator cannot be used with variable initialization", unaryOp->mOpToken);
  2779. return false;
  2780. }
  2781. if (childWasAndRHS)
  2782. {
  2783. return _Fail("Operator may allow conditional short-circuiting to skip variable initialization", unaryOp->mOpToken);
  2784. }
  2785. }
  2786. else if (auto ifStmt = BfNodeDynCast<BfIfStatement>(checkParent))
  2787. {
  2788. // Done
  2789. foundIf = true;
  2790. break;
  2791. }
  2792. else
  2793. {
  2794. if (requireSimpleIfExpr)
  2795. {
  2796. return _Fail("Variable declaration expression can only be contained in simple 'if' expressions", checkNode);
  2797. }
  2798. break;
  2799. }
  2800. checkChild = parentNodeEntry->mNode;
  2801. parentNodeEntry = parentNodeEntry->mPrev;
  2802. }
  2803. return foundIf;
  2804. }
  2805. bool BfExprEvaluator::HasVariableDeclaration(BfAstNode* checkNode)
  2806. {
  2807. BfVarDeclChecker checker;
  2808. checker.VisitChild(checkNode);
  2809. return checker.mHasVarDecl;
  2810. }
  2811. void BfExprEvaluator::Visit(BfVariableDeclaration* varDecl)
  2812. {
  2813. mModule->UpdateExprSrcPos(varDecl);
  2814. if ((mModule->mCurMethodState == NULL) || (!mModule->mCurMethodState->mCurScope->mAllowVariableDeclarations))
  2815. {
  2816. mModule->Fail("Variable declarations are not allowed in this context", varDecl);
  2817. if (varDecl->mInitializer != NULL)
  2818. {
  2819. VisitChild(varDecl->mInitializer);
  2820. }
  2821. return;
  2822. }
  2823. CheckVariableDeclaration(varDecl, true, false, false);
  2824. if (varDecl->mInitializer == NULL)
  2825. {
  2826. mModule->Fail("Variable declarations used as expressions must have an initializer", varDecl);
  2827. }
  2828. BfTupleExpression* tupleVariableDeclaration = BfNodeDynCast<BfTupleExpression>(varDecl->mNameNode);
  2829. if (tupleVariableDeclaration != NULL)
  2830. {
  2831. mModule->Fail("Tuple variable declarations cannot be used as expressions", varDecl);
  2832. mModule->HandleTupleVariableDeclaration(varDecl);
  2833. }
  2834. else
  2835. mModule->HandleVariableDeclaration(varDecl, this);
  2836. }
  2837. void BfExprEvaluator::Visit(BfCaseExpression* caseExpr)
  2838. {
  2839. if (caseExpr->mEqualsNode != NULL)
  2840. {
  2841. mModule->Warn(0, "Deprecated case syntax", caseExpr->mEqualsNode);
  2842. }
  2843. BfTypedValue caseValAddr;
  2844. if (caseExpr->mValueExpression != NULL)
  2845. caseValAddr = mModule->CreateValueFromExpression(caseExpr->mValueExpression, NULL, (BfEvalExprFlags)(mBfEvalExprFlags & BfEvalExprFlags_InheritFlags));
  2846. if ((caseValAddr.mType != NULL) && (caseValAddr.mType->IsPointer()))
  2847. {
  2848. caseValAddr = mModule->LoadValue(caseValAddr);
  2849. caseValAddr = BfTypedValue(caseValAddr.mValue, caseValAddr.mType->GetUnderlyingType(), true);
  2850. }
  2851. if (caseValAddr.mType != NULL)
  2852. mModule->mBfIRBuilder->PopulateType(caseValAddr.mType);
  2853. if ((mModule->mCurMethodState != NULL) && (mModule->mCurMethodState->mDeferredLocalAssignData != NULL))
  2854. mModule->mCurMethodState->mDeferredLocalAssignData->BreakExtendChain();
  2855. if (auto bindExpr = BfNodeDynCast<BfEnumCaseBindExpression>(caseExpr->mCaseExpression))
  2856. {
  2857. if (caseValAddr)
  2858. {
  2859. BfTypedValue enumTagVal;
  2860. if (caseValAddr.mType->IsPayloadEnum())
  2861. {
  2862. int dscrDataIdx;
  2863. auto dscrType = caseValAddr.mType->ToTypeInstance()->GetDiscriminatorType(&dscrDataIdx);
  2864. enumTagVal = BfTypedValue(mModule->ExtractValue(caseValAddr, dscrDataIdx), dscrType);
  2865. }
  2866. else
  2867. enumTagVal = mModule->GetDefaultTypedValue(mModule->GetPrimitiveType(BfTypeCode_Int32));
  2868. mResult = mModule->HandleCaseBind(caseValAddr, enumTagVal, bindExpr);
  2869. return;
  2870. }
  2871. }
  2872. bool isPayloadEnum = (caseValAddr.mType != NULL) && (caseValAddr.mType->IsPayloadEnum());
  2873. auto tupleExpr = BfNodeDynCast<BfTupleExpression>(caseExpr->mCaseExpression);
  2874. if ((caseValAddr) &&
  2875. ((isPayloadEnum) || (tupleExpr != NULL)))
  2876. {
  2877. bool hasVariable = false;
  2878. bool hasOut = false;
  2879. bool clearOutOnMismatch = false;
  2880. if (auto invocateExpr = BfNodeDynCast<BfInvocationExpression>(caseExpr->mCaseExpression))
  2881. {
  2882. for (auto arg : invocateExpr->mArguments)
  2883. {
  2884. if (auto varDecl = BfNodeDynCast<BfVariableDeclaration>(arg))
  2885. {
  2886. hasVariable = true;
  2887. }
  2888. else if (auto unaryOpExpr = BfNodeDynCast<BfUnaryOperatorExpression>(arg))
  2889. {
  2890. if (unaryOpExpr->mOpToken->mToken == BfToken_Out)
  2891. {
  2892. hasOut = true;
  2893. }
  2894. }
  2895. }
  2896. }
  2897. if (hasVariable)
  2898. {
  2899. CheckVariableDeclaration(caseExpr, false, true, false);
  2900. }
  2901. // We can avoid clearing on mismatch if we can be sure we ONLY enter the true block on a match.
  2902. // An example of requiring clearing is: if ((result case .Ok(out val)) || (force))
  2903. if (hasOut)
  2904. clearOutOnMismatch = !CheckVariableDeclaration(caseExpr, true, true, true);
  2905. bool hadConditional = false;
  2906. if (isPayloadEnum)
  2907. {
  2908. int dscrDataIdx;
  2909. auto dscrType = caseValAddr.mType->ToTypeInstance()->GetDiscriminatorType(&dscrDataIdx);
  2910. auto enumTagVal = mModule->LoadValue(mModule->ExtractValue(caseValAddr, NULL, 2));
  2911. int uncondTagId = -1;
  2912. mResult = mModule->TryCaseEnumMatch(caseValAddr, enumTagVal, caseExpr->mCaseExpression, NULL, NULL, NULL, uncondTagId, hadConditional, clearOutOnMismatch);
  2913. }
  2914. else
  2915. {
  2916. mResult = mModule->TryCaseTupleMatch(caseValAddr, tupleExpr, NULL, NULL, NULL, hadConditional, clearOutOnMismatch);
  2917. }
  2918. if (mResult)
  2919. return;
  2920. }
  2921. if ((caseValAddr) && (caseValAddr.mType->IsVar()))
  2922. {
  2923. auto invocationExpr = BfNodeDynCast<BfInvocationExpression>(caseExpr->mCaseExpression);
  2924. if (invocationExpr != NULL)
  2925. {
  2926. for (auto expr : invocationExpr->mArguments)
  2927. {
  2928. if (expr == NULL)
  2929. continue;
  2930. if (auto varDecl = BfNodeDynCast<BfVariableDeclaration>(expr))
  2931. {
  2932. auto localVar = mModule->HandleVariableDeclaration(varDecl, BfTypedValue());
  2933. if (localVar != NULL)
  2934. localVar->mReadFromId = 0;
  2935. }
  2936. }
  2937. }
  2938. auto boolType = mModule->GetPrimitiveType(BfTypeCode_Boolean);
  2939. mResult = mModule->GetDefaultTypedValue(boolType);
  2940. return;
  2941. }
  2942. auto boolType = mModule->GetPrimitiveType(BfTypeCode_Boolean);
  2943. BfTypedValue caseMatch;
  2944. if (caseExpr->mCaseExpression != NULL)
  2945. caseMatch = mModule->CreateValueFromExpression(caseExpr->mCaseExpression, caseValAddr.mType, BfEvalExprFlags_AllowEnumId);
  2946. if ((!caseMatch) || (!caseValAddr))
  2947. {
  2948. mResult = mModule->GetDefaultTypedValue(boolType);
  2949. return;
  2950. }
  2951. if (caseValAddr.mType == caseMatch.mType)
  2952. {
  2953. if (((caseValAddr.mType->IsEnum()) && (caseValAddr.mType->IsStruct())) &&
  2954. ((caseMatch) && (caseMatch.mType->IsPayloadEnum()) && (caseMatch.mValue.IsConst())))
  2955. {
  2956. BfTypedValue enumTagVal = mModule->LoadValue(mModule->ExtractValue(caseValAddr, NULL, 2));
  2957. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateCmpEQ(enumTagVal.mValue, caseMatch.mValue), boolType);
  2958. return;
  2959. }
  2960. }
  2961. else
  2962. {
  2963. // We need to get rid of the int-const for the 'scalar match'. We get a full payload enum value so we can
  2964. // possibly use it in a user-defined comparison operator
  2965. if ((caseMatch.mType->IsStruct()) && (caseMatch.mValue.IsConst()))
  2966. {
  2967. // Is it possible this could throw an error twice? Hope not.
  2968. caseMatch = mModule->CreateValueFromExpression(caseExpr->mCaseExpression, NULL, (BfEvalExprFlags)(mBfEvalExprFlags & BfEvalExprFlags_InheritFlags));
  2969. }
  2970. }
  2971. PerformBinaryOperation(caseExpr->mCaseExpression, caseExpr->mValueExpression, BfBinaryOp_Equality, caseExpr->mEqualsNode, BfBinOpFlag_None, caseValAddr, caseMatch);
  2972. }
  2973. void BfExprEvaluator::Visit(BfTypedValueExpression* typedValueExpr)
  2974. {
  2975. mResult = typedValueExpr->mTypedValue;
  2976. }
  2977. static bool IsCharType(BfTypeCode typeCode)
  2978. {
  2979. switch (typeCode)
  2980. {
  2981. case BfTypeCode_Char8:
  2982. case BfTypeCode_Char16:
  2983. case BfTypeCode_Char32:
  2984. return true;
  2985. default:
  2986. return false;
  2987. }
  2988. }
  2989. void BfExprEvaluator::GetLiteral(BfAstNode* refNode, const BfVariant& variant)
  2990. {
  2991. switch (variant.mTypeCode)
  2992. {
  2993. case BfTypeCode_NullPtr:
  2994. {
  2995. auto nullType = mModule->ResolveTypeDef(mModule->mSystem->mTypeNullPtr);
  2996. /*mResult = BfTypedValue(ConstantPointerNull::get((PointerType*) nullType->mIRType), nullType);*/
  2997. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConstNull(), nullType);
  2998. }
  2999. break;
  3000. case BfTypeCode_CharPtr:
  3001. {
  3002. if ((mExpectingType != NULL) && (mExpectingType->IsSizedArray()))
  3003. {
  3004. auto sizedArray = (BfSizedArrayType*)mExpectingType;
  3005. if (sizedArray->mElementType == mModule->GetPrimitiveType(BfTypeCode_Char8))
  3006. {
  3007. if (variant.mString->GetLength() > sizedArray->mElementCount)
  3008. {
  3009. mModule->Fail(StrFormat("String literal is too long to fit into '%s'", mModule->TypeToString(sizedArray).c_str()), refNode);
  3010. }
  3011. Array<BfIRValue> charValues;
  3012. for (int i = 0; i < (int)BF_MIN(variant.mString->GetLength(), sizedArray->mElementCount); i++)
  3013. {
  3014. char c = (*variant.mString)[i];
  3015. charValues.Add(mModule->mBfIRBuilder->CreateConst(BfTypeCode_Char8, (int)(uint8)c));
  3016. }
  3017. if (sizedArray->mElementCount > charValues.size())
  3018. charValues.Add(mModule->mBfIRBuilder->CreateConst(BfTypeCode_Char8, 0));
  3019. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConstAgg(mModule->mBfIRBuilder->MapType(sizedArray), charValues), sizedArray);
  3020. return;
  3021. }
  3022. }
  3023. if ((mExpectingType == NULL) || (!mExpectingType->IsPointer()))
  3024. {
  3025. mResult = BfTypedValue(mModule->GetStringObjectValue(*variant.mString),
  3026. mModule->ResolveTypeDef(mModule->mCompiler->mStringTypeDef));
  3027. }
  3028. else
  3029. {
  3030. auto charType = mModule->GetPrimitiveType(BfTypeCode_Char8);
  3031. auto charPtrType = mModule->CreatePointerType(charType);
  3032. mResult = BfTypedValue(mModule->GetStringCharPtr(*variant.mString),
  3033. charPtrType);
  3034. }
  3035. }
  3036. break;
  3037. case BfTypeCode_Boolean:
  3038. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConst(variant.mTypeCode, variant.mUInt64), mModule->GetPrimitiveType(variant.mTypeCode));
  3039. break;
  3040. case BfTypeCode_Char8:
  3041. case BfTypeCode_Char16:
  3042. case BfTypeCode_Char32:
  3043. case BfTypeCode_Int8:
  3044. case BfTypeCode_UInt8:
  3045. case BfTypeCode_Int16:
  3046. case BfTypeCode_UInt16:
  3047. case BfTypeCode_Int32:
  3048. case BfTypeCode_UInt32:
  3049. case BfTypeCode_Int64:
  3050. case BfTypeCode_UInt64:
  3051. case BfTypeCode_IntPtr:
  3052. case BfTypeCode_UIntPtr:
  3053. case BfTypeCode_IntUnknown:
  3054. case BfTypeCode_UIntUnknown:
  3055. if ((mExpectingType != NULL) && (mExpectingType->IsIntegral()) && (mExpectingType->IsChar() == IsCharType(variant.mTypeCode)))
  3056. {
  3057. auto primType = (BfPrimitiveType*)mExpectingType;
  3058. if (mModule->mSystem->DoesLiteralFit(primType->mTypeDef->mTypeCode, variant.mInt64))
  3059. {
  3060. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConst(primType->mTypeDef->mTypeCode, variant.mUInt64), mExpectingType);
  3061. break;
  3062. }
  3063. }
  3064. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConst(variant.mTypeCode, variant.mUInt64), mModule->GetPrimitiveType(variant.mTypeCode));
  3065. break;
  3066. case BfTypeCode_Float:
  3067. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConst(variant.mTypeCode, variant.mSingle), mModule->GetPrimitiveType(variant.mTypeCode));
  3068. break;
  3069. case BfTypeCode_Double:
  3070. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConst(variant.mTypeCode, variant.mDouble), mModule->GetPrimitiveType(variant.mTypeCode));
  3071. break;
  3072. default:
  3073. mModule->Fail("Invalid literal", refNode);
  3074. break;
  3075. }
  3076. }
  3077. void BfExprEvaluator::Visit(BfLiteralExpression* literalExpr)
  3078. {
  3079. switch (literalExpr->mValue.mWarnType)
  3080. {
  3081. case BfWarning_BF4201_Only7Hex:
  3082. mModule->Warn(BfWarning_BF4201_Only7Hex, "Only 7 hex digits specified. Add a leading zero to clarify intention.", literalExpr);
  3083. break;
  3084. case BfWarning_BF4202_TooManyHexForInt:
  3085. 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);
  3086. break;
  3087. }
  3088. GetLiteral(literalExpr, literalExpr->mValue);
  3089. }
  3090. void BfExprEvaluator::Visit(BfStringInterpolationExpression* stringInterpolationExpression)
  3091. {
  3092. if (IsComptimeEntry())
  3093. {
  3094. mModule->Fail("Const evaluation of string interpolation not allowed", stringInterpolationExpression);
  3095. }
  3096. if ((mBfEvalExprFlags & BfEvalExprFlags_StringInterpolateFormat) != 0)
  3097. {
  3098. BfVariant variant;
  3099. variant.mTypeCode = BfTypeCode_CharPtr;
  3100. variant.mString = stringInterpolationExpression->mString;
  3101. GetLiteral(stringInterpolationExpression, variant);
  3102. return;
  3103. }
  3104. if (stringInterpolationExpression->mAllocNode != NULL)
  3105. {
  3106. auto stringType = mModule->ResolveTypeDef(mModule->mCompiler->mStringTypeDef)->ToTypeInstance();
  3107. BfTokenNode* newToken = NULL;
  3108. BfAllocTarget allocTarget = ResolveAllocTarget(stringInterpolationExpression->mAllocNode, newToken);
  3109. CreateObject(NULL, stringInterpolationExpression->mAllocNode, stringType);
  3110. BfTypedValue newString = mResult;
  3111. BF_ASSERT(newString);
  3112. SizedArray<BfExpression*, 2> argExprs;
  3113. argExprs.Add(stringInterpolationExpression);
  3114. BfSizedArray<BfExpression*> sizedArgExprs(argExprs);
  3115. BfResolvedArgs argValues(&sizedArgExprs);
  3116. ResolveArgValues(argValues, BfResolveArgsFlag_InsideStringInterpolationAlloc);
  3117. MatchMethod(stringInterpolationExpression, NULL, newString, false, false, "AppendF", argValues, NULL);
  3118. mResult = newString;
  3119. return;
  3120. }
  3121. mModule->Fail("Invalid use of string interpolation expression. Consider adding an allocation specifier such as 'scope'.", stringInterpolationExpression);
  3122. for (auto block : stringInterpolationExpression->mExpressions)
  3123. {
  3124. VisitChild(block);
  3125. }
  3126. }
  3127. BfTypedValue BfExprEvaluator::LoadLocal(BfLocalVariable* varDecl, bool allowRef)
  3128. {
  3129. if (!mModule->mIsInsideAutoComplete)
  3130. varDecl->mReadFromId = mModule->mCurMethodState->GetRootMethodState()->mCurAccessId++;
  3131. // The Beef backend prefers readonly addrs since that reduces register pressure, whereas
  3132. // LLVM prefers values to avoid memory loads. This only applies to primitive types...
  3133. bool preferValue = (varDecl->mResolvedType->IsPrimitiveType()) && (!mModule->IsTargetingBeefBackend());
  3134. BfTypedValue localResult;
  3135. if (varDecl->mIsThis)
  3136. {
  3137. return mModule->GetThis();
  3138. }
  3139. else if (varDecl->mConstValue)
  3140. {
  3141. localResult = BfTypedValue(varDecl->mConstValue, varDecl->mResolvedType, false);
  3142. }
  3143. else if (varDecl->mIsSplat)
  3144. {
  3145. if ((!preferValue) && (varDecl->mAddr))
  3146. localResult = BfTypedValue(varDecl->mAddr, varDecl->mResolvedType, BfTypedValueKind_SplatHead);
  3147. else if (!varDecl->mResolvedType->IsValuelessType())
  3148. localResult = BfTypedValue(varDecl->mValue, varDecl->mResolvedType, BfTypedValueKind_SplatHead);
  3149. else if ((varDecl->mResolvedType->IsRef()) && (!allowRef))
  3150. {
  3151. BF_ASSERT(varDecl->mResolvedType->IsValuelessType());
  3152. localResult = BfTypedValue(varDecl->mValue, varDecl->mResolvedType->GetUnderlyingType());
  3153. }
  3154. else
  3155. localResult = BfTypedValue(varDecl->mValue, varDecl->mResolvedType);
  3156. //BF_ASSERT(varDecl->mValue.IsArg());
  3157. }
  3158. else if ((varDecl->mValue) && ((varDecl->mIsReadOnly && preferValue) || (!varDecl->mAddr)))
  3159. {
  3160. if ((varDecl->mResolvedType->IsRef()) && (!allowRef))
  3161. {
  3162. BfRefType* refType = (BfRefType*)varDecl->mResolvedType;
  3163. BfType* innerType = refType->mElementType;
  3164. if (innerType->IsGenericParam())
  3165. {
  3166. if (refType->mRefKind == BfRefType::RefKind_Mut)
  3167. {
  3168. localResult = BfTypedValue(varDecl->mValue, innerType, BfTypedValueKind_MutableValue);
  3169. return localResult;
  3170. }
  3171. else
  3172. {
  3173. localResult = BfTypedValue(varDecl->mValue, innerType, BfTypedValueKind_Addr);
  3174. return localResult;
  3175. }
  3176. }
  3177. localResult = BfTypedValue(varDecl->mValue, innerType, varDecl->mIsReadOnly ? BfTypedValueKind_ReadOnlyAddr : BfTypedValueKind_Addr);
  3178. }
  3179. else
  3180. {
  3181. BfTypedValueKind kind;
  3182. if ((varDecl->mResolvedType->IsComposite()) && (varDecl->IsParam()) && (mModule->mCurMethodState->mMixinState == NULL))
  3183. kind = varDecl->mIsReadOnly ? BfTypedValueKind_ReadOnlyAddr : BfTypedValueKind_Addr;
  3184. else
  3185. kind = BfTypedValueKind_Value;
  3186. localResult = BfTypedValue(varDecl->mValue, varDecl->mResolvedType, kind);
  3187. }
  3188. }
  3189. else if (varDecl->mAddr)
  3190. {
  3191. if ((varDecl->mResolvedType->IsRef()) && (!allowRef))
  3192. {
  3193. BfRefType* refType = (BfRefType*)varDecl->mResolvedType;
  3194. BfType* innerType = refType->mElementType;
  3195. if (innerType->IsValuelessType())
  3196. {
  3197. if (refType->mRefKind == BfRefType::RefKind_Mut)
  3198. return BfTypedValue(mModule->mBfIRBuilder->GetFakeVal(), innerType, BfTypedValueKind_MutableValue);
  3199. return BfTypedValue(mModule->mBfIRBuilder->GetFakeVal(), innerType, varDecl->mIsReadOnly ? BfTypedValueKind_ReadOnlyAddr : BfTypedValueKind_Addr);
  3200. }
  3201. if (refType->mRefKind == BfRefType::RefKind_Mut)
  3202. {
  3203. if (innerType->IsGenericParam())
  3204. {
  3205. localResult = BfTypedValue(mModule->mBfIRBuilder->CreateAlignedLoad(varDecl->mAddr, varDecl->mResolvedType->mAlign), innerType, BfTypedValueKind_MutableValue);
  3206. return localResult;
  3207. }
  3208. }
  3209. localResult = BfTypedValue(mModule->mBfIRBuilder->CreateAlignedLoad(varDecl->mAddr, varDecl->mResolvedType->mAlign), innerType, varDecl->mIsReadOnly ? BfTypedValueKind_ReadOnlyAddr : BfTypedValueKind_Addr);
  3210. }
  3211. else if (varDecl->mHasLocalStructBacking)
  3212. {
  3213. // varDecl->mAddr is a "struct**"
  3214. localResult = BfTypedValue(mModule->mBfIRBuilder->CreateAlignedLoad(varDecl->mAddr, varDecl->mResolvedType->mAlign), varDecl->mResolvedType, varDecl->mIsReadOnly ? BfTypedValueKind_ReadOnlyAddr : BfTypedValueKind_Addr);
  3215. }
  3216. else
  3217. localResult = BfTypedValue(varDecl->mAddr, varDecl->mResolvedType, varDecl->mIsReadOnly ? BfTypedValueKind_ReadOnlyAddr : BfTypedValueKind_Addr);
  3218. }
  3219. else if (varDecl->mResolvedType->IsValuelessType())
  3220. {
  3221. if ((varDecl->mResolvedType->IsRef()) && (!allowRef))
  3222. {
  3223. BfRefType* refType = (BfRefType*)varDecl->mResolvedType;
  3224. BfType* innerType = refType->mElementType;
  3225. localResult = BfTypedValue(mModule->mBfIRBuilder->GetFakeVal(), innerType, true);
  3226. return localResult;
  3227. }
  3228. localResult = BfTypedValue(mModule->mBfIRBuilder->GetFakeVal(), varDecl->mResolvedType, true);
  3229. }
  3230. else if (varDecl->mCompositeCount >= 0)
  3231. {
  3232. localResult = BfTypedValue(BfIRValue(), mModule->GetPrimitiveType(BfTypeCode_None));
  3233. }
  3234. else
  3235. {
  3236. BF_ASSERT((mModule->mCurMethodState->mClosureState != NULL) || (mModule->mBfIRBuilder->mIgnoreWrites));
  3237. // Just temporary
  3238. auto varType = varDecl->mResolvedType;
  3239. auto allocType = varType;
  3240. if (varType->IsRef())
  3241. {
  3242. BfRefType* refType = (BfRefType*)varType;
  3243. allocType = refType->mElementType;
  3244. }
  3245. auto declType = varDecl->mResolvedType;
  3246. if (declType->IsRef())
  3247. {
  3248. BfRefType* refType = (BfRefType*)declType;
  3249. declType = refType->mElementType;
  3250. }
  3251. mModule->PopulateType(allocType);
  3252. varDecl->mAddr = mModule->mBfIRBuilder->CreateAlloca(mModule->mBfIRBuilder->MapType(allocType));
  3253. localResult = BfTypedValue(varDecl->mAddr, declType, true);
  3254. return localResult;
  3255. }
  3256. if ((varDecl->mIsThis) && (localResult.mKind == BfTypedValueKind_Value))
  3257. localResult.mKind = BfTypedValueKind_ThisValue;
  3258. return localResult;
  3259. }
  3260. BfTypedValue BfExprEvaluator::LookupIdentifier(BfAstNode* refNode, const StringImpl& findName, bool ignoreInitialError, bool* hadError)
  3261. {
  3262. auto identifierNode = BfNodeDynCast<BfIdentifierNode>(refNode);
  3263. if (mModule->mCurMethodState != NULL)
  3264. {
  3265. auto rootMethodState = mModule->mCurMethodState->GetRootMethodState();
  3266. auto checkMethodState = mModule->mCurMethodState;
  3267. bool isMixinOuterVariablePass = false;
  3268. while (checkMethodState != NULL)
  3269. {
  3270. BP_ZONE("LookupIdentifier:LocalVar");
  3271. BfTypeInstance* closureTypeInst = NULL;
  3272. if ((checkMethodState->mClosureState != NULL) && (checkMethodState->mClosureState->mClosureType != NULL) && (!checkMethodState->mClosureState->mCapturing))
  3273. {
  3274. closureTypeInst = mModule->mCurMethodState->mClosureState->mClosureType;
  3275. }
  3276. int varSkipCount = 0;
  3277. StringT<128> wantName;
  3278. wantName.Reference(findName);
  3279. if (findName.StartsWith('@'))
  3280. {
  3281. wantName = findName;
  3282. while (wantName.StartsWith("@"))
  3283. {
  3284. if (wantName != "@return")
  3285. varSkipCount++;
  3286. wantName.Remove(0);
  3287. }
  3288. }
  3289. if (wantName.IsEmpty())
  3290. {
  3291. mModule->Fail("Shadowed variable name expected after '@'", refNode);
  3292. }
  3293. BfLocalVarEntry* entry;
  3294. if (checkMethodState->mLocalVarSet.TryGetWith<StringImpl&>(wantName, &entry))
  3295. {
  3296. auto varDecl = entry->mLocalVar;
  3297. while ((varSkipCount > 0) && (varDecl != NULL))
  3298. {
  3299. varDecl = varDecl->mShadowedLocal;
  3300. varSkipCount--;
  3301. }
  3302. if ((varDecl != NULL) && (varDecl->mNotCaptured))
  3303. {
  3304. mModule->Fail("Local variable is not captured", refNode);
  3305. }
  3306. if ((varSkipCount == 0) && (varDecl != NULL))
  3307. {
  3308. if ((closureTypeInst != NULL) && (wantName == "this"))
  3309. break;
  3310. if ((varDecl->mCompositeCount >= 0) && ((mBfEvalExprFlags & BfEvalExprFlags_AllowParamsExpr) == 0))
  3311. {
  3312. mModule->Fail("Invalid use of 'params' parameter", refNode);
  3313. }
  3314. if (varDecl->mResolvedType->IsVoid())
  3315. {
  3316. if ((varDecl->mIsReadOnly) && (varDecl->mParamIdx == -2) && (varDecl->mParamFailed))
  3317. {
  3318. BF_ASSERT(mModule->mCurMethodInstance->mMethodDef->mMethodType == BfMethodType_CtorCalcAppend);
  3319. 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);
  3320. }
  3321. }
  3322. BfTypedValue localResult = LoadLocal(varDecl);
  3323. auto autoComplete = GetAutoComplete();
  3324. if (identifierNode != NULL)
  3325. {
  3326. if (autoComplete != NULL)
  3327. autoComplete->CheckLocalRef(identifierNode, varDecl);
  3328. if (((mModule->mCurMethodState->mClosureState == NULL) || (mModule->mCurMethodState->mClosureState->mCapturing)) &&
  3329. (mModule->mCompiler->mResolvePassData != NULL) && (mModule->mCurMethodInstance != NULL) && (!mModule->mCurMethodState->IsTemporary()))
  3330. mModule->mCompiler->mResolvePassData->HandleLocalReference(identifierNode, varDecl->mNameNode, mModule->mCurTypeInstance->mTypeDef, rootMethodState->mMethodInstance->mMethodDef, varDecl->mLocalVarId);
  3331. }
  3332. if (!isMixinOuterVariablePass)
  3333. {
  3334. mResultLocalVar = varDecl;
  3335. mResultFieldInstance = NULL;
  3336. mResultLocalVarRefNode = identifierNode;
  3337. }
  3338. return localResult;
  3339. }
  3340. }
  3341. // Check for the captured locals. It's important we do it here so we get local-first precedence still
  3342. if (closureTypeInst != NULL)
  3343. {
  3344. int varSkipCount = 0;
  3345. StringT<128> wantName;
  3346. wantName.Reference(findName);
  3347. closureTypeInst->mTypeDef->PopulateMemberSets();
  3348. BfMemberSetEntry* memberSetEntry = NULL;
  3349. if (closureTypeInst->mTypeDef->mFieldSet.TryGetWith((StringImpl&)wantName, &memberSetEntry))
  3350. {
  3351. auto fieldDef = (BfFieldDef*)memberSetEntry->mMemberDef;
  3352. while ((varSkipCount > 0) && (fieldDef != NULL))
  3353. {
  3354. fieldDef = fieldDef->mNextWithSameName;
  3355. varSkipCount--;
  3356. }
  3357. auto& field = closureTypeInst->mFieldInstances[fieldDef->mIdx];
  3358. if (!field.mResolvedType->IsValuelessType())
  3359. {
  3360. if (mModule->mCurMethodState->mClosureState->mCapturing)
  3361. {
  3362. mModule->mCurMethodState->mClosureState->mReferencedOuterClosureMembers.Add(&field);
  3363. return mModule->GetDefaultTypedValue(field.mResolvedType);
  3364. }
  3365. auto localVar = mModule->mCurMethodState->mLocals[0];
  3366. auto thisValue = localVar->mValue;
  3367. mModule->mBfIRBuilder->PopulateType(localVar->mResolvedType);
  3368. BfTypedValue result = BfTypedValue(mModule->mBfIRBuilder->CreateInBoundsGEP(thisValue, 0, field.mDataIdx), field.mResolvedType, true);
  3369. if (field.mResolvedType->IsRef())
  3370. {
  3371. auto refType = (BfRefType*)field.mResolvedType;
  3372. auto underlyingType = refType->GetUnderlyingType();
  3373. result = BfTypedValue(mModule->mBfIRBuilder->CreateLoad(result.mValue), underlyingType, true);
  3374. }
  3375. else if (fieldDef->mIsReadOnly)
  3376. result = mModule->LoadValue(result);
  3377. mResultLocalVar = localVar;
  3378. mResultFieldInstance = &field;
  3379. mResultLocalVarField = -(field.mMergedDataIdx + 1);
  3380. return result;
  3381. }
  3382. }
  3383. }
  3384. if ((checkMethodState->mClosureState != NULL) && (checkMethodState->mClosureState->mCapturing) /*&& (checkMethodState->mClosureState->mIsLocalMethod)*/)
  3385. {
  3386. checkMethodState = checkMethodState->mPrevMethodState;
  3387. continue;
  3388. }
  3389. // Allow local mixin to see outside variables during its processing -- since we don't actually "capture" those into params
  3390. bool isLocalMixinProcessing = false;
  3391. if ((checkMethodState->mClosureState != NULL) && (!checkMethodState->mClosureState->mCapturing) && (closureTypeInst == NULL) &&
  3392. (mModule->mCurMethodInstance->mMethodDef->mMethodType == BfMethodType_Mixin))
  3393. isLocalMixinProcessing = true;
  3394. if (!isLocalMixinProcessing)
  3395. break;
  3396. isMixinOuterVariablePass = true;
  3397. checkMethodState = checkMethodState->mPrevMethodState;
  3398. }
  3399. }
  3400. if ((mModule->mCurMethodInstance == NULL) && (mModule->mCurTypeInstance != NULL) && (mModule->mCurTypeInstance->IsEnum()))
  3401. {
  3402. if (findName == "_")
  3403. {
  3404. BfFieldDef* resolvingFieldDef = NULL;
  3405. auto checkTypeState = mModule->mContext->mCurTypeState;
  3406. while (checkTypeState != NULL)
  3407. {
  3408. if (checkTypeState->mCurFieldDef != NULL)
  3409. {
  3410. if (checkTypeState->mTypeInstance == mModule->mCurTypeInstance)
  3411. resolvingFieldDef = checkTypeState->mCurFieldDef;
  3412. }
  3413. checkTypeState = checkTypeState->mPrevState;
  3414. }
  3415. if ((resolvingFieldDef != NULL) && (resolvingFieldDef->mIdx > 0))
  3416. {
  3417. auto enumType = mModule->mCurTypeInstance;
  3418. if (!enumType->mFieldInstances.IsEmpty())
  3419. {
  3420. auto fieldInstance = &mModule->mCurTypeInstance->mFieldInstances[resolvingFieldDef->mIdx - 1];
  3421. if ((fieldInstance->mConstIdx != -1) &&
  3422. (fieldInstance->mResolvedType == mModule->mCurTypeInstance))
  3423. {
  3424. auto foreignConst = enumType->mConstHolder->GetConstantById(fieldInstance->mConstIdx);
  3425. auto retVal = mModule->ConstantToCurrent(foreignConst, enumType->mConstHolder, enumType);
  3426. return BfTypedValue(retVal, enumType);
  3427. }
  3428. }
  3429. }
  3430. }
  3431. }
  3432. BfTypedValue thisValue = mModule->GetThis();
  3433. bool forcedIFaceLookup = false;
  3434. if ((mModule->mCurMethodInstance != NULL) && (mModule->mCurMethodInstance->mIsForeignMethodDef))
  3435. {
  3436. thisValue.mType = mModule->mCurMethodInstance->GetForeignType();
  3437. forcedIFaceLookup = true;
  3438. }
  3439. if (thisValue)
  3440. {
  3441. if (findName == "this")
  3442. return thisValue;
  3443. if (findName == "base")
  3444. {
  3445. auto baseValue = thisValue;
  3446. if (baseValue.IsThis())
  3447. baseValue.ToBase();
  3448. if (mModule->GetActiveTypeDef()->mTypeCode != BfTypeCode_Extension)
  3449. {
  3450. MakeBaseConcrete(baseValue);
  3451. }
  3452. return baseValue;
  3453. }
  3454. if (!mModule->mCurMethodState->HasNonStaticMixin())
  3455. {
  3456. mResultLocalVar = mModule->GetThisVariable();
  3457. mResultFieldInstance = NULL;
  3458. mResultLocalVarRefNode = identifierNode;
  3459. }
  3460. }
  3461. if (!thisValue.HasType())
  3462. {
  3463. if ((mModule->mContext->mCurTypeState != NULL) && (mModule->mContext->mCurTypeState->mTypeInstance == mModule->mCurTypeInstance) &&
  3464. (mModule->mContext->mCurTypeState->mResolveKind == BfTypeState::ResolveKind_Attributes))
  3465. {
  3466. // Can't do static lookups yet
  3467. }
  3468. else
  3469. thisValue = BfTypedValue(mModule->mCurTypeInstance);
  3470. }
  3471. BfTypedValue result;
  3472. if (thisValue.HasType())
  3473. {
  3474. result = LookupField(identifierNode, thisValue, findName, BfLookupFieldFlag_IsImplicitThis);
  3475. if (mResultFieldInstance == NULL)
  3476. {
  3477. mResultLocalVar = NULL;
  3478. mResultLocalVarRefNode = NULL;
  3479. }
  3480. }
  3481. if (mPropDef != NULL)
  3482. {
  3483. if (forcedIFaceLookup)
  3484. {
  3485. if (mPropTarget == thisValue)
  3486. {
  3487. mPropDefBypassVirtual = true;
  3488. mOrigPropTarget = mModule->GetThis();
  3489. }
  3490. }
  3491. }
  3492. if ((!result) && (mPropDef == NULL))
  3493. {
  3494. if (mModule->mContext->mCurTypeState != NULL)
  3495. {
  3496. // This is not necessarily true since we changed ConstResolver
  3497. //BF_ASSERT(mModule->mCurTypeInstance == mModule->mContext->mCurTypeState->mTypeInstance);
  3498. BfGlobalLookup globalLookup;
  3499. globalLookup.mKind = BfGlobalLookup::Kind_Field;
  3500. globalLookup.mName = findName;
  3501. mModule->PopulateGlobalContainersList(globalLookup);
  3502. for (auto& globalContainer : mModule->mContext->mCurTypeState->mGlobalContainers)
  3503. {
  3504. if (globalContainer.mTypeInst == NULL)
  3505. continue;
  3506. thisValue = BfTypedValue(globalContainer.mTypeInst);
  3507. result = LookupField(identifierNode, thisValue, findName);
  3508. if ((result) || (mPropDef != NULL))
  3509. return result;
  3510. }
  3511. }
  3512. auto staticSearch = mModule->GetStaticSearch();
  3513. if (staticSearch != NULL)
  3514. {
  3515. for (auto typeInst : staticSearch->mStaticTypes)
  3516. {
  3517. thisValue = BfTypedValue(typeInst);
  3518. result = LookupField(identifierNode, thisValue, findName);
  3519. if ((result) || (mPropDef != NULL))
  3520. return result;
  3521. }
  3522. }
  3523. }
  3524. if ((!result) && (identifierNode != NULL))
  3525. result = mModule->TryLookupGenericConstVaue(identifierNode, mExpectingType);
  3526. return result;
  3527. }
  3528. BfTypedValue BfExprEvaluator::LookupIdentifier(BfIdentifierNode* identifierNode, bool ignoreInitialError, bool* hadError)
  3529. {
  3530. auto qualifiedNameNode = BfNodeDynCast<BfQualifiedNameNode>(identifierNode);
  3531. if (qualifiedNameNode != NULL)
  3532. {
  3533. LookupQualifiedName(qualifiedNameNode, ignoreInitialError, hadError);
  3534. auto qualifiedResult = mResult;
  3535. mResult = BfTypedValue();
  3536. return qualifiedResult;
  3537. }
  3538. StringT<128> identifierStr;
  3539. identifierNode->ToString(identifierStr);
  3540. return LookupIdentifier(identifierNode, identifierStr, ignoreInitialError, hadError);
  3541. }
  3542. void BfExprEvaluator::Visit(BfIdentifierNode* identifierNode)
  3543. {
  3544. auto autoComplete = GetAutoComplete();
  3545. if (autoComplete != NULL)
  3546. autoComplete->CheckIdentifier(identifierNode, true);
  3547. mResult = LookupIdentifier(identifierNode);
  3548. if ((!mResult) && (mPropDef == NULL))
  3549. {
  3550. mModule->CheckTypeRefFixit(identifierNode);
  3551. if ((autoComplete != NULL) && (autoComplete->CheckFixit(identifierNode)))
  3552. {
  3553. if (mModule->mCurMethodInstance != NULL)
  3554. {
  3555. BfType* fieldType = mExpectingType;
  3556. if (fieldType == NULL)
  3557. fieldType = mModule->mContext->mBfObjectType;
  3558. autoComplete->FixitAddMember(mModule->mCurTypeInstance, fieldType, identifierNode->ToString(), true, mModule->mCurTypeInstance);
  3559. if (!mModule->mCurMethodInstance->mMethodDef->mIsStatic)
  3560. autoComplete->FixitAddMember(mModule->mCurTypeInstance, fieldType, identifierNode->ToString(), false, mModule->mCurTypeInstance);
  3561. for (auto typeDef : mModule->mSystem->mTypeDefs)
  3562. {
  3563. if (!typeDef->mIsCombinedPartial)
  3564. continue;
  3565. if (!typeDef->IsGlobalsContainer())
  3566. continue;
  3567. typeDef->PopulateMemberSets();
  3568. String findName = identifierNode->ToString();
  3569. BfMemberSetEntry* memberSetEntry;
  3570. if ((typeDef->mMethodSet.TryGetWith(findName, &memberSetEntry)) ||
  3571. (typeDef->mFieldSet.TryGetWith(findName, &memberSetEntry)) ||
  3572. (typeDef->mPropertySet.TryGetWith(findName, &memberSetEntry)))
  3573. {
  3574. if (mModule->GetActiveTypeDef()->mProject->ContainsReference(typeDef->mProject))
  3575. autoComplete->FixitAddNamespace(identifierNode, typeDef->mNamespace.ToString());
  3576. }
  3577. }
  3578. }
  3579. }
  3580. if ((mBfEvalExprFlags & BfEvalExprFlags_NoLookupError) == 0)
  3581. mModule->Fail("Identifier not found", identifierNode);
  3582. }
  3583. }
  3584. void BfExprEvaluator::Visit(BfAttributedIdentifierNode* attrIdentifierNode)
  3585. {
  3586. if ((mModule->mAttributeState != NULL))
  3587. {
  3588. mModule->mAttributeState->mCustomAttributes = mModule->GetCustomAttributes(attrIdentifierNode->mAttributes, mModule->mAttributeState->mTarget);
  3589. VisitChild(attrIdentifierNode->mIdentifier);
  3590. }
  3591. else
  3592. {
  3593. BfAttributeState attributeState;
  3594. attributeState.mTarget = (BfAttributeTargets)(BfAttributeTargets_MemberAccess);
  3595. SetAndRestoreValue<BfAttributeState*> prevAttributeState(mModule->mAttributeState, &attributeState);
  3596. mModule->mAttributeState->mCustomAttributes = mModule->GetCustomAttributes(attrIdentifierNode->mAttributes, mModule->mAttributeState->mTarget);
  3597. VisitChild(attrIdentifierNode->mIdentifier);
  3598. }
  3599. }
  3600. static int gPropIdx = 0;
  3601. void BfExprEvaluator::FixitAddMember(BfTypeInstance* typeInst, BfType* fieldType, const StringImpl& fieldName, bool isStatic)
  3602. {
  3603. if (fieldType == NULL)
  3604. {
  3605. fieldType = mExpectingType;
  3606. }
  3607. if (fieldType != NULL)
  3608. {
  3609. if (fieldType->IsRef())
  3610. fieldType = fieldType->GetUnderlyingType();
  3611. }
  3612. mModule->mCompiler->mResolvePassData->mAutoComplete->FixitAddMember(typeInst, fieldType, fieldName, isStatic, mModule->mCurTypeInstance);
  3613. }
  3614. BfTypedValue BfExprEvaluator::LookupField(BfAstNode* targetSrc, BfTypedValue target, const StringImpl& fieldName, BfLookupFieldFlags flags)
  3615. {
  3616. if ((target.mType != NULL && (target.mType->IsGenericParam())))
  3617. {
  3618. auto genericParamInst = mModule->GetGenericParamInstance((BfGenericParamType*)target.mType);
  3619. if (target.mValue)
  3620. {
  3621. for (auto iface : genericParamInst->mInterfaceConstraints)
  3622. {
  3623. auto result = LookupField(targetSrc, BfTypedValue(target.mValue, iface), fieldName, flags);
  3624. if ((result) || (mPropDef != NULL))
  3625. {
  3626. return result;
  3627. }
  3628. }
  3629. }
  3630. if (mModule->mCurMethodInstance->mIsUnspecialized)
  3631. {
  3632. if (genericParamInst->mTypeConstraint != NULL)
  3633. target.mType = genericParamInst->mTypeConstraint;
  3634. else
  3635. target.mType = mModule->mContext->mBfObjectType;
  3636. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_Var) != 0)
  3637. {
  3638. target.mType = mModule->GetPrimitiveType(BfTypeCode_Var);
  3639. }
  3640. }
  3641. else
  3642. {
  3643. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_Var) != 0)
  3644. {
  3645. //target.mType = mModule->ResolveGenericType(mResult.mType);
  3646. }
  3647. else if (genericParamInst->mTypeConstraint != NULL)
  3648. {
  3649. target = mModule->Cast(targetSrc, target, genericParamInst->mTypeConstraint);
  3650. BF_ASSERT(target);
  3651. }
  3652. else
  3653. {
  3654. // This shouldn't occur - this would infer that we are accessing a member of Object or something...
  3655. //target.mType = mModule->ResolveGenericType(mResult.mType);
  3656. }
  3657. }
  3658. }
  3659. if ((target.mType != NULL) && (target.mType->IsVar()))
  3660. return BfTypedValue(mModule->GetDefaultValue(target.mType), target.mType, true);
  3661. BfTypeInstance* startCheckType = mModule->mCurTypeInstance;
  3662. mPropDef = NULL;
  3663. mPropDefBypassVirtual = false;
  3664. if (target)
  3665. {
  3666. if ((!target.mType->IsValueType()) && (target.IsAddr()))
  3667. target = mModule->LoadValue(target);
  3668. if (target.mType->IsPrimitiveType())
  3669. {
  3670. auto primType = (BfPrimitiveType*)target.mType;
  3671. startCheckType = mModule->GetPrimitiveStructType(primType->mTypeDef->mTypeCode);
  3672. }
  3673. else
  3674. {
  3675. startCheckType = target.mType->ToTypeInstance();
  3676. if ((startCheckType == NULL) && (target.mType->IsPointer()))
  3677. startCheckType = ((BfPointerType*) target.mType)->mElementType->ToTypeInstance();
  3678. }
  3679. //BF_ASSERT(startCheckType != NULL);
  3680. }
  3681. else if (target.mType != NULL)
  3682. {
  3683. startCheckType = target.mType->ToTypeInstance();
  3684. }
  3685. if ((startCheckType != NULL) && (startCheckType->mBaseType == NULL))
  3686. {
  3687. if (startCheckType->mDefineState == BfTypeDefineState_ResolvingBaseType)
  3688. {
  3689. // Fixes cases where we have something like 'Base[Value]' as a base typeref
  3690. return BfTypedValue();
  3691. }
  3692. mModule->PopulateType(startCheckType, BfPopulateType_BaseType);
  3693. }
  3694. if ((startCheckType != NULL) && (mModule->mContext->mCurTypeState != NULL))
  3695. {
  3696. // Don't allow lookups yet
  3697. if ((mModule->mContext->mCurTypeState->mResolveKind == BfTypeState::ResolveKind_Attributes) &&
  3698. (startCheckType == mModule->mContext->mCurTypeState->mTypeInstance))
  3699. return BfTypedValue();
  3700. }
  3701. String findName;
  3702. int varSkipCount = 0;
  3703. if (fieldName.StartsWith('@'))
  3704. {
  3705. findName = fieldName;
  3706. while (findName.StartsWith('@'))
  3707. {
  3708. findName.Remove(0);
  3709. varSkipCount++;
  3710. }
  3711. }
  3712. else
  3713. findName.Reference(fieldName);
  3714. auto activeTypeDef = mModule->GetActiveTypeDef();
  3715. for (int pass = 0; pass < 2; pass++)
  3716. {
  3717. auto curCheckType = startCheckType;
  3718. bool isFailurePass = pass == 1;
  3719. bool isBaseLookup = false;
  3720. while (curCheckType != NULL)
  3721. {
  3722. curCheckType->mTypeDef->PopulateMemberSets();
  3723. BfFieldDef* nextField = NULL;
  3724. BfMemberSetEntry* entry;
  3725. if (curCheckType->mTypeDef->mFieldSet.TryGetWith(findName, &entry))
  3726. nextField = (BfFieldDef*)entry->mMemberDef;
  3727. while ((varSkipCount > 0) && (nextField != NULL))
  3728. {
  3729. nextField = nextField->mNextWithSameName;
  3730. }
  3731. BfProtectionCheckFlags protectionCheckFlags = BfProtectionCheckFlag_None;
  3732. if (target)
  3733. {
  3734. if ((flags & (BfLookupFieldFlag_IsImplicitThis | BfLookupFieldFlag_BaseLookup)) != 0)
  3735. {
  3736. // Not an "instance lookup"
  3737. }
  3738. else
  3739. {
  3740. protectionCheckFlags = (BfProtectionCheckFlags)(protectionCheckFlags | BfProtectionCheckFlag_InstanceLookup);
  3741. }
  3742. }
  3743. BfFieldDef* matchedField = NULL;
  3744. while (nextField != NULL)
  3745. {
  3746. if ((flags & BfLookupFieldFlag_BindOnly) != 0)
  3747. break;
  3748. auto field = nextField;
  3749. nextField = nextField->mNextWithSameName;
  3750. if (((flags & BfLookupFieldFlag_IgnoreProtection) == 0) && (!isFailurePass) &&
  3751. (!mModule->CheckProtection(protectionCheckFlags, curCheckType, field->mDeclaringType->mProject, field->mProtection, startCheckType)))
  3752. {
  3753. continue;
  3754. }
  3755. bool isResolvingFields = curCheckType->mResolvingConstField || curCheckType->mResolvingVarField;
  3756. if (curCheckType->mFieldInstances.IsEmpty())
  3757. {
  3758. mModule->PopulateType(curCheckType, BfPopulateType_Data);
  3759. }
  3760. BF_ASSERT(field->mIdx < (int)curCheckType->mFieldInstances.size());
  3761. auto fieldInstance = &curCheckType->mFieldInstances[field->mIdx];
  3762. if (!fieldInstance->mFieldIncluded)
  3763. continue;
  3764. if (curCheckType->IsUnspecializedType())
  3765. {
  3766. // The check for non-unspecialized types is already handled in mFieldIncluded
  3767. if (!curCheckType->IsTypeMemberIncluded(field->mDeclaringType, activeTypeDef, mModule))
  3768. continue;
  3769. }
  3770. if (!curCheckType->IsTypeMemberAccessible(field->mDeclaringType, activeTypeDef))
  3771. continue;
  3772. if (matchedField != NULL)
  3773. {
  3774. auto error = mModule->Fail(StrFormat("Ambiguous reference to field '%s.%s'", mModule->TypeToString(curCheckType).c_str(), fieldName.c_str()), targetSrc);
  3775. if (error != NULL)
  3776. {
  3777. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("See field declaration in project '%s'", matchedField->mDeclaringType->mProject->mName.c_str()), matchedField->mFieldDeclaration);
  3778. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("See field declaration in project '%s'", field->mDeclaringType->mProject->mName.c_str()), field->mFieldDeclaration);
  3779. break;
  3780. }
  3781. }
  3782. matchedField = field;
  3783. }
  3784. if (matchedField != NULL)
  3785. {
  3786. auto field = matchedField;
  3787. auto fieldInstance = &curCheckType->mFieldInstances[field->mIdx];
  3788. bool isResolvingFields = curCheckType->mResolvingConstField || curCheckType->mResolvingVarField;
  3789. if (field->mIsVolatile)
  3790. mIsVolatileReference = true;
  3791. if (isFailurePass)
  3792. {
  3793. mModule->Fail(StrFormat("'%s.%s' is inaccessible due to its protection level", mModule->TypeToString(curCheckType).c_str(), field->mName.c_str()), targetSrc);
  3794. }
  3795. auto resolvePassData = mModule->mCompiler->mResolvePassData;
  3796. if ((resolvePassData != NULL) && (resolvePassData->mGetSymbolReferenceKind == BfGetSymbolReferenceKind_Field))
  3797. {
  3798. resolvePassData->HandleFieldReference(targetSrc, curCheckType->mTypeDef, field);
  3799. }
  3800. if ((!curCheckType->mTypeFailed) && (!isResolvingFields) && (curCheckType->IsIncomplete()))
  3801. {
  3802. if ((fieldInstance->mResolvedType == NULL) ||
  3803. (!field->mIsStatic))
  3804. mModule->PopulateType(curCheckType, BfPopulateType_Data);
  3805. }
  3806. if (fieldInstance->mResolvedType == NULL)
  3807. {
  3808. BF_ASSERT((curCheckType->mTypeFailed) || (isResolvingFields));
  3809. return BfTypedValue();
  3810. }
  3811. if (fieldInstance->mFieldIdx == -1)
  3812. {
  3813. mModule->AssertErrorState();
  3814. return BfTypedValue();
  3815. }
  3816. mResultFieldInstance = fieldInstance;
  3817. // Are we accessing a 'var' field that has not yet been resolved?
  3818. if (fieldInstance->mResolvedType->IsVar())
  3819. {
  3820. // This can happen if we have one var field referencing another var field
  3821. fieldInstance->mResolvedType = mModule->ResolveVarFieldType(curCheckType, fieldInstance, field);
  3822. if (fieldInstance->mResolvedType == NULL)
  3823. return BfTypedValue();
  3824. }
  3825. auto resolvedFieldType = fieldInstance->mResolvedType;
  3826. if (fieldInstance->mIsEnumPayloadCase)
  3827. {
  3828. resolvedFieldType = curCheckType;
  3829. }
  3830. mModule->PopulateType(resolvedFieldType, BfPopulateType_Data);
  3831. mModule->AddDependency(curCheckType, mModule->mCurTypeInstance, BfDependencyMap::DependencyFlag_ReadFields);
  3832. if (fieldInstance->mHadConstEval)
  3833. {
  3834. mModule->AddDependency(curCheckType, mModule->mCurTypeInstance, BfDependencyMap::DependencyFlag_ConstEvalConstField);
  3835. if ((mModule->mContext->mCurTypeState != NULL) && (mModule->mContext->mCurTypeState->mCurFieldDef != NULL))
  3836. {
  3837. // If we're initializing another const field then also set it as having const eval
  3838. auto resolvingFieldInstance = &mModule->mContext->mCurTypeState->mTypeInstance->mFieldInstances[mModule->mContext->mCurTypeState->mCurFieldDef->mIdx];
  3839. if (resolvingFieldInstance->GetFieldDef()->mIsConst)
  3840. resolvingFieldInstance->mHadConstEval = true;
  3841. }
  3842. }
  3843. auto autoComplete = GetAutoComplete();
  3844. if (autoComplete != NULL)
  3845. {
  3846. autoComplete->CheckFieldRef(BfNodeDynCast<BfIdentifierNode>(targetSrc), fieldInstance);
  3847. if ((autoComplete->mResolveType == BfResolveType_GetResultString) && (autoComplete->IsAutocompleteNode(targetSrc)))
  3848. {
  3849. autoComplete->mResultString = ":";
  3850. autoComplete->mResultString += mModule->TypeToString(fieldInstance->mResolvedType);
  3851. autoComplete->mResultString += " ";
  3852. autoComplete->mResultString += mModule->TypeToString(curCheckType);
  3853. autoComplete->mResultString += ".";
  3854. autoComplete->mResultString += field->mName;
  3855. if (fieldInstance->mConstIdx != -1)
  3856. {
  3857. String constStr = autoComplete->ConstantToString(curCheckType->mConstHolder, BfIRValue(BfIRValueFlags_Const, fieldInstance->mConstIdx));
  3858. if (!constStr.IsEmpty())
  3859. {
  3860. autoComplete->mResultString += " = ";
  3861. if (constStr.StartsWith(':'))
  3862. autoComplete->mResultString.Append(StringView(constStr, 1, constStr.mLength - 1));
  3863. else
  3864. autoComplete->mResultString += constStr;
  3865. }
  3866. }
  3867. auto fieldDecl = fieldInstance->GetFieldDef()->mFieldDeclaration;
  3868. if ((fieldDecl != NULL) && (fieldDecl->mDocumentation != NULL))
  3869. {
  3870. String docString;
  3871. fieldDecl->mDocumentation->GetDocString(docString);
  3872. autoComplete->mResultString += "\x03";
  3873. autoComplete->mResultString += docString;
  3874. }
  3875. }
  3876. }
  3877. if (field->mIsStatic)
  3878. {
  3879. if ((target) && ((flags & BfLookupFieldFlag_IsImplicitThis) == 0) && (!curCheckType->mTypeDef->IsGlobalsContainer()))
  3880. {
  3881. //CS0176: Member 'Program.sVal' cannot be accessed with an instance reference; qualify it with a type name instead
  3882. mModule->Fail(StrFormat("Member '%s.%s' cannot be accessed with an instance reference; qualify it with a type name instead",
  3883. mModule->TypeToString(curCheckType).c_str(), field->mName.c_str()), targetSrc);
  3884. }
  3885. // Target must be an implicit 'this', or an error (accessing a static with a non-static target).
  3886. // Not actually needed in either case since this is a static lookup.
  3887. mResultLocalVar = NULL;
  3888. }
  3889. bool isConst = false;
  3890. if (field->mIsConst)
  3891. {
  3892. isConst = true;
  3893. auto fieldDef = fieldInstance->GetFieldDef();
  3894. if ((resolvedFieldType->IsPointer()) && (fieldDef->mIsExtern))
  3895. isConst = false;
  3896. }
  3897. if (resolvedFieldType->IsValuelessType())
  3898. {
  3899. return BfTypedValue(BfIRValue::sValueless, resolvedFieldType, true);
  3900. }
  3901. if (isConst)
  3902. {
  3903. if (fieldInstance->mIsEnumPayloadCase)
  3904. {
  3905. auto dscrType = curCheckType->GetDiscriminatorType();
  3906. mModule->mBfIRBuilder->PopulateType(curCheckType);
  3907. int tagIdx = -fieldInstance->mDataIdx - 1;
  3908. if ((mBfEvalExprFlags & BfEvalExprFlags_AllowEnumId) != 0)
  3909. {
  3910. return BfTypedValue(mModule->mBfIRBuilder->CreateConst(dscrType->mTypeDef->mTypeCode, tagIdx), fieldInstance->mOwner);
  3911. }
  3912. mModule->PopulateType(fieldInstance->mOwner, BfPopulateType_Data);
  3913. // OLD:
  3914. // auto agg = mModule->CreateAlloca(fieldInstance->mOwner);
  3915. // auto gep = mModule->mBfIRBuilder->CreateInBoundsGEP(agg, 0, 2);
  3916. // mModule->mBfIRBuilder->CreateStore(mModule->mBfIRBuilder->CreateConst(dscrType->mTypeDef->mTypeCode, tagIdx), gep);
  3917. //
  3918. // if (fieldInstance->mResolvedType->mSize != 0)
  3919. // {
  3920. // mModule->FailAfter("Enum case parameters expected", targetSrc);
  3921. // }
  3922. //
  3923. // return BfTypedValue(agg, fieldInstance->mOwner, true);
  3924. //NEW
  3925. SizedArray<BfIRValue, 3> values;
  3926. values.Add(mModule->mBfIRBuilder->CreateConstAggZero(mModule->mBfIRBuilder->MapType(curCheckType->mBaseType)));
  3927. values.Add(mModule->mBfIRBuilder->CreateConstAggZero(mModule->mBfIRBuilder->MapType(curCheckType->GetUnionInnerType())));
  3928. values.Add(mModule->mBfIRBuilder->CreateConst(dscrType->mTypeDef->mTypeCode, tagIdx));
  3929. return BfTypedValue(mModule->mBfIRBuilder->CreateConstAgg(mModule->mBfIRBuilder->MapType(curCheckType), values), curCheckType);
  3930. }
  3931. if (fieldInstance->mConstIdx == -1)
  3932. {
  3933. if ((mBfEvalExprFlags & BfEvalExprFlags_DeclType) != 0)
  3934. {
  3935. // We don't need a real value
  3936. return BfTypedValue(mModule->GetDefaultValue(resolvedFieldType), resolvedFieldType);
  3937. }
  3938. curCheckType->mModule->ResolveConstField(curCheckType, fieldInstance, field);
  3939. if (fieldInstance->mConstIdx == -1)
  3940. return BfTypedValue(mModule->GetDefaultValue(resolvedFieldType), resolvedFieldType);
  3941. }
  3942. BF_ASSERT(fieldInstance->mConstIdx != -1);
  3943. auto foreignConst = curCheckType->mConstHolder->GetConstantById(fieldInstance->mConstIdx);
  3944. auto retVal = mModule->ConstantToCurrent(foreignConst, curCheckType->mConstHolder, resolvedFieldType);
  3945. return BfTypedValue(retVal, resolvedFieldType);
  3946. }
  3947. else if (field->mIsStatic)
  3948. {
  3949. mModule->CheckStaticAccess(curCheckType);
  3950. auto retVal = mModule->ReferenceStaticField(fieldInstance);
  3951. bool isStaticCtor = (mModule->mCurMethodInstance != NULL) && (mModule->mCurMethodInstance->mMethodDef->mMethodType == BfMethodType_Ctor) &&
  3952. (mModule->mCurMethodInstance->mMethodDef->mIsStatic);
  3953. if ((field->mIsReadOnly) && (!isStaticCtor))
  3954. {
  3955. if (retVal.IsAddr())
  3956. retVal.mKind = BfTypedValueKind_ReadOnlyAddr;
  3957. }
  3958. else
  3959. mIsHeapReference = true;
  3960. return retVal;
  3961. }
  3962. else if (!target)
  3963. {
  3964. if (mModule->PreFail())
  3965. {
  3966. if ((flags & BfLookupFieldFlag_CheckingOuter) != 0)
  3967. mModule->Fail(StrFormat("An instance reference is required to reference non-static outer field '%s.%s'", mModule->TypeToString(curCheckType).c_str(), field->mName.c_str()),
  3968. targetSrc);
  3969. else if ((mModule->mCurMethodInstance != NULL) && (mModule->mCurMethodInstance->mMethodDef->mMethodType == BfMethodType_CtorCalcAppend))
  3970. mModule->Fail(StrFormat("Cannot reference field '%s' before append allocations", field->mName.c_str()), targetSrc);
  3971. else
  3972. mModule->Fail(StrFormat("Cannot reference non-static field '%s' from a static method", field->mName.c_str()), targetSrc);
  3973. }
  3974. return mModule->GetDefaultTypedValue(resolvedFieldType, false, BfDefaultValueKind_Addr);
  3975. }
  3976. if ((mResultLocalVar != NULL) && (fieldInstance->mMergedDataIdx != -1))
  3977. {
  3978. if (mResultLocalVarFieldCount != 1)
  3979. {
  3980. fieldInstance->GetDataRange(mResultLocalVarField, mResultLocalVarFieldCount);
  3981. mResultLocalVarRefNode = targetSrc;
  3982. }
  3983. }
  3984. if ((curCheckType->IsIncomplete()) && (!curCheckType->mNeedsMethodProcessing))
  3985. {
  3986. BF_ASSERT(curCheckType->mTypeFailed || (mModule->mCurMethodState == NULL) || (mModule->mCurMethodState->mTempKind != BfMethodState::TempKind_None) || (mModule->mCompiler->IsAutocomplete()));
  3987. return mModule->GetDefaultTypedValue(resolvedFieldType);
  3988. }
  3989. bool isTemporary = target.IsTempAddr();
  3990. bool wantsLoadValue = false;
  3991. bool wantsReadOnly = false;
  3992. if ((field->mIsReadOnly) && (mModule->mCurMethodInstance != NULL) && ((mModule->mCurMethodInstance->mMethodDef->mMethodType != BfMethodType_Ctor) || (!target.IsThis())))
  3993. wantsReadOnly = true;
  3994. bool isComposite = target.mType->IsComposite();
  3995. if ((isComposite) && (!target.mType->IsTypedPrimitive()) && (!target.IsAddr()))
  3996. isTemporary = true;
  3997. if ((isComposite) && (!target.IsAddr()))
  3998. wantsLoadValue = true;
  3999. if ((target.mType->IsWrappableType()) && (!target.mType->IsPointer()))
  4000. {
  4001. BfTypeInstance* primStructType = mModule->GetWrappedStructType(target.mType);
  4002. BfIRValue allocaInst = mModule->CreateAlloca(primStructType, true, "tmpStruct");
  4003. BfIRValue elementAddr = mModule->mBfIRBuilder->CreateInBoundsGEP(allocaInst, 0, 1);
  4004. mModule->mBfIRBuilder->CreateStore(target.mValue, elementAddr);
  4005. target = BfTypedValue(allocaInst, primStructType, true);
  4006. }
  4007. if (target.IsCopyOnMutate())
  4008. target = mModule->CopyValue(target);
  4009. BfTypedValue targetValue;
  4010. if ((isBaseLookup) && (!target.IsSplat()))
  4011. {
  4012. if ((!isComposite) || (target.IsAddr()))
  4013. targetValue = BfTypedValue(mModule->mBfIRBuilder->CreateBitCast(target.mValue, mModule->mBfIRBuilder->MapTypeInstPtr(curCheckType)), curCheckType);
  4014. else
  4015. {
  4016. BfIRValue curVal = target.mValue;
  4017. auto baseCheckType = target.mType->ToTypeInstance();
  4018. while (baseCheckType != curCheckType)
  4019. {
  4020. curVal = mModule->mBfIRBuilder->CreateExtractValue(curVal, 0);
  4021. baseCheckType = baseCheckType->mBaseType;
  4022. }
  4023. targetValue = BfTypedValue(curVal, curCheckType);
  4024. }
  4025. }
  4026. else
  4027. targetValue = target;
  4028. bool doAccessCheck = true;
  4029. if ((mModule->mAttributeState != NULL) && (mModule->mAttributeState->mCustomAttributes != NULL) && (mModule->mAttributeState->mCustomAttributes->Contains(mModule->mCompiler->mDisableObjectAccessChecksAttributeTypeDef)))
  4030. doAccessCheck = false;
  4031. if (target.IsThis())
  4032. {
  4033. if (!mModule->mCurMethodState->mMayNeedThisAccessCheck)
  4034. doAccessCheck = false;
  4035. }
  4036. if (doAccessCheck)
  4037. mModule->EmitObjectAccessCheck(target);
  4038. if (fieldInstance->mDataIdx < 0)
  4039. {
  4040. BF_ASSERT(curCheckType->mTypeFailed);
  4041. return mModule->GetDefaultTypedValue(resolvedFieldType);
  4042. }
  4043. BfTypedValue retVal;
  4044. if (target.IsSplat())
  4045. {
  4046. retVal = mModule->ExtractValue(targetValue, fieldInstance, fieldInstance->mDataIdx);
  4047. }
  4048. else if ((target.mType->IsStruct()) && (!target.IsAddr()))
  4049. {
  4050. mModule->mBfIRBuilder->PopulateType(targetValue.mType);
  4051. retVal = BfTypedValue(mModule->mBfIRBuilder->CreateExtractValue(targetValue.mValue, fieldInstance->mDataIdx/*, field->mName*/),
  4052. resolvedFieldType);
  4053. }
  4054. else
  4055. {
  4056. mModule->mBfIRBuilder->PopulateType(curCheckType);
  4057. if ((targetValue.IsAddr()) && (!curCheckType->IsValueType()))
  4058. targetValue = mModule->LoadValue(targetValue);
  4059. retVal = BfTypedValue(mModule->mBfIRBuilder->CreateInBoundsGEP(targetValue.mValue, 0, fieldInstance->mDataIdx/*, field->mName*/),
  4060. resolvedFieldType, target.IsReadOnly() ? BfTypedValueKind_ReadOnlyAddr : BfTypedValueKind_Addr);
  4061. }
  4062. if (!retVal.IsSplat())
  4063. {
  4064. if (curCheckType->mIsUnion)
  4065. {
  4066. BfIRType llvmPtrType = mModule->mBfIRBuilder->GetPointerTo(mModule->mBfIRBuilder->MapType(resolvedFieldType));
  4067. retVal.mValue = mModule->mBfIRBuilder->CreateBitCast(retVal.mValue, llvmPtrType);
  4068. }
  4069. }
  4070. if (wantsLoadValue)
  4071. retVal = mModule->LoadValue(retVal, NULL, mIsVolatileReference);
  4072. else
  4073. {
  4074. if ((wantsReadOnly) && (retVal.IsAddr())&& (!retVal.IsReadOnly()))
  4075. retVal.mKind = BfTypedValueKind_ReadOnlyAddr;
  4076. mIsHeapReference = true;
  4077. }
  4078. if (isTemporary)
  4079. {
  4080. if (retVal.IsAddr())
  4081. retVal.mKind = BfTypedValueKind_TempAddr;
  4082. }
  4083. return retVal;
  4084. }
  4085. BfPropertyDef* nextProp = NULL;
  4086. if (curCheckType->mTypeDef->mPropertySet.TryGetWith(fieldName, &entry))
  4087. nextProp = (BfPropertyDef*)entry->mMemberDef;
  4088. if (nextProp != NULL)
  4089. {
  4090. BfCheckedKind checkedKind = BfCheckedKind_NotSet;
  4091. bool isInlined = false;
  4092. if ((mModule->mAttributeState != NULL) && (mModule->mAttributeState->mCustomAttributes != NULL))
  4093. {
  4094. if (mModule->mAttributeState->mCustomAttributes->Contains(mModule->mCompiler->mInlineAttributeTypeDef))
  4095. {
  4096. isInlined = true;
  4097. mModule->mAttributeState->mUsed = true;
  4098. }
  4099. if (mModule->mAttributeState->mCustomAttributes->Contains(mModule->mCompiler->mCheckedAttributeTypeDef))
  4100. {
  4101. checkedKind = BfCheckedKind_Checked;
  4102. mModule->mAttributeState->mUsed = true;
  4103. }
  4104. if (mModule->mAttributeState->mCustomAttributes->Contains(mModule->mCompiler->mUncheckedAttributeTypeDef))
  4105. {
  4106. checkedKind = BfCheckedKind_Unchecked;
  4107. mModule->mAttributeState->mUsed = true;
  4108. }
  4109. }
  4110. BfPropertyDef* matchedProp = NULL;
  4111. while (nextProp != NULL)
  4112. {
  4113. auto prop = nextProp;
  4114. nextProp = nextProp->mNextWithSameName;
  4115. if ((!isFailurePass) && (!mModule->CheckProtection(protectionCheckFlags, curCheckType, prop->mDeclaringType->mProject, prop->mProtection, startCheckType)))
  4116. {
  4117. continue;
  4118. }
  4119. if (!prop->mMethods.IsEmpty())
  4120. {
  4121. BfMethodDef* checkMethod = prop->mMethods[0];;
  4122. // Properties with explicit interfaces or marked as overrides can only be called indirectly
  4123. if ((checkMethod->mExplicitInterface != NULL) || (checkMethod->mIsOverride))
  4124. continue;
  4125. }
  4126. if ((!target.IsStatic()) || (prop->mIsStatic))
  4127. {
  4128. if (!mModule->IsInSpecializedSection())
  4129. {
  4130. if ((!curCheckType->IsTypeMemberIncluded(prop->mDeclaringType, activeTypeDef, mModule)) ||
  4131. (!curCheckType->IsTypeMemberAccessible(prop->mDeclaringType, mModule->GetVisibleProjectSet())))
  4132. continue;
  4133. }
  4134. if (matchedProp != NULL)
  4135. {
  4136. if (mModule->PreFail())
  4137. {
  4138. auto error = mModule->Fail(StrFormat("Ambiguous reference to property '%s.%s'", mModule->TypeToString(curCheckType).c_str(), fieldName.c_str()), targetSrc);
  4139. if (error != NULL)
  4140. {
  4141. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("See property declaration in project '%s'", matchedProp->mDeclaringType->mProject->mName.c_str()), matchedProp->mFieldDeclaration);
  4142. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("See property declaration in project '%s'", prop->mDeclaringType->mProject->mName.c_str()), prop->mFieldDeclaration);
  4143. break;
  4144. }
  4145. }
  4146. }
  4147. matchedProp = prop;
  4148. }
  4149. }
  4150. if (matchedProp != NULL)
  4151. {
  4152. auto prop = matchedProp;
  4153. gPropIdx++;
  4154. mModule->SetElementType(targetSrc, BfSourceElementType_Method);
  4155. mPropSrc = targetSrc;
  4156. mPropDef = prop;
  4157. mPropCheckedKind = checkedKind;
  4158. if (isInlined)
  4159. mPropGetMethodFlags = (BfGetMethodInstanceFlags)(mPropGetMethodFlags | BfGetMethodInstanceFlag_ForceInline);
  4160. if ((mModule->mAttributeState != NULL) && (mModule->mAttributeState->mCustomAttributes != NULL))
  4161. {
  4162. if (mModule->mAttributeState->mCustomAttributes->Contains(mModule->mCompiler->mFriendAttributeTypeDef))
  4163. {
  4164. mPropGetMethodFlags = (BfGetMethodInstanceFlags)(mPropGetMethodFlags | BfGetMethodInstanceFlag_Friend);
  4165. mModule->mAttributeState->mUsed = true;
  4166. }
  4167. if (mModule->mAttributeState->mCustomAttributes->Contains(mModule->mCompiler->mDisableObjectAccessChecksAttributeTypeDef))
  4168. {
  4169. mPropGetMethodFlags = (BfGetMethodInstanceFlags)(mPropGetMethodFlags | BfGetMethodInstanceFlag_DisableObjectAccessChecks);
  4170. mModule->mAttributeState->mUsed = true;
  4171. }
  4172. }
  4173. if (mPropDef->mIsStatic)
  4174. {
  4175. if ((target) && ((flags & BfLookupFieldFlag_IsImplicitThis) == 0) && (!curCheckType->mTypeDef->IsGlobalsContainer()))
  4176. {
  4177. //CS0176: Member 'Program.sVal' cannot be accessed with an instance reference; qualify it with a type name instead
  4178. mModule->Fail(StrFormat("Property '%s.%s' cannot be accessed with an instance reference; qualify it with a type name instead",
  4179. mModule->TypeToString(curCheckType).c_str(), mPropDef->mName.c_str()), targetSrc);
  4180. }
  4181. }
  4182. if (prop->mIsStatic)
  4183. mPropTarget = BfTypedValue(curCheckType);
  4184. else if (isBaseLookup)
  4185. {
  4186. mPropTarget = mModule->Cast(targetSrc, target, curCheckType);
  4187. BF_ASSERT(mPropTarget);
  4188. }
  4189. else
  4190. mPropTarget = target;
  4191. if (mPropTarget.mType->IsStructPtr())
  4192. {
  4193. mPropTarget = mModule->LoadValue(mPropTarget);
  4194. mPropTarget = BfTypedValue(mPropTarget.mValue, mPropTarget.mType->GetUnderlyingType(), mPropTarget.IsReadOnly() ? BfTypedValueKind_ReadOnlyAddr : BfTypedValueKind_Addr);
  4195. }
  4196. mOrigPropTarget = mPropTarget;
  4197. auto autoComplete = GetAutoComplete();
  4198. auto resolvePassData = mModule->mCompiler->mResolvePassData;
  4199. if (((autoComplete != NULL) && (autoComplete->mIsGetDefinition)) ||
  4200. ((resolvePassData != NULL) && (resolvePassData->mGetSymbolReferenceKind == BfGetSymbolReferenceKind_Property)))
  4201. {
  4202. BfPropertyDef* basePropDef = mPropDef;
  4203. BfTypeInstance* baseTypeInst = curCheckType;
  4204. mModule->GetBasePropertyDef(basePropDef, baseTypeInst);
  4205. resolvePassData->HandlePropertyReference(targetSrc, baseTypeInst->mTypeDef, basePropDef);
  4206. if ((autoComplete != NULL) && (autoComplete->IsAutocompleteNode(targetSrc)))
  4207. {
  4208. if (autoComplete->mIsGetDefinition)
  4209. autoComplete->SetDefinitionLocation(basePropDef->GetRefNode(), true);
  4210. autoComplete->mDefProp = basePropDef;
  4211. autoComplete->mDefType = baseTypeInst->mTypeDef;
  4212. }
  4213. }
  4214. if ((autoComplete != NULL) && (autoComplete->mResolveType == BfResolveType_GetResultString) && (autoComplete->IsAutocompleteNode(targetSrc)))
  4215. {
  4216. BfPropertyDef* basePropDef = mPropDef;
  4217. BfTypeInstance* baseTypeInst = curCheckType;
  4218. mModule->GetBasePropertyDef(basePropDef, baseTypeInst);
  4219. autoComplete->mResultString = ":";
  4220. autoComplete->mResultString += mModule->TypeToString(baseTypeInst);
  4221. autoComplete->mResultString += ".";
  4222. autoComplete->mResultString += basePropDef->mName;
  4223. }
  4224. // Check for direct auto-property access
  4225. if (startCheckType == mModule->mCurTypeInstance)
  4226. {
  4227. if (auto propertyDeclaration = BfNodeDynCast<BfPropertyDeclaration>(mPropDef->mFieldDeclaration))
  4228. {
  4229. if ((curCheckType->mTypeDef->HasAutoProperty(propertyDeclaration)) && (propertyDeclaration->mVirtualSpecifier == NULL))
  4230. {
  4231. bool hasSetter = GetPropertyMethodDef(mPropDef, BfMethodType_PropertySetter, BfCheckedKind_NotSet, mPropTarget) != NULL;
  4232. auto autoFieldName = curCheckType->mTypeDef->GetAutoPropertyName(propertyDeclaration);
  4233. auto result = LookupField(targetSrc, target, autoFieldName, (BfLookupFieldFlags)(BfLookupFieldFlag_IgnoreProtection | BfLookupFieldFlag_IsImplicitThis));
  4234. if (result)
  4235. {
  4236. bool needsCopy = true;
  4237. if (!hasSetter)
  4238. {
  4239. if (((mModule->mCurMethodInstance->mMethodDef->mMethodType == BfMethodType_Ctor)) &&
  4240. (startCheckType == mModule->mCurTypeInstance))
  4241. {
  4242. // Allow writing inside ctor
  4243. }
  4244. else
  4245. {
  4246. result.MakeReadOnly();
  4247. needsCopy = false;
  4248. }
  4249. }
  4250. if (result.mKind == BfTypedValueKind_Addr)
  4251. result.mKind = BfTypedValueKind_CopyOnMutateAddr;
  4252. mPropDef = NULL;
  4253. mPropSrc = NULL;
  4254. mOrigPropTarget = NULL;
  4255. return result;
  4256. }
  4257. }
  4258. }
  4259. }
  4260. SetAndRestoreValue<BfTypedValue> prevResult(mResult, target);
  4261. CheckResultForReading(mResult);
  4262. return BfTypedValue();
  4263. }
  4264. }
  4265. isBaseLookup = true;
  4266. curCheckType = curCheckType->mBaseType;
  4267. }
  4268. }
  4269. auto outerTypeDef = mModule->GetOuterType(startCheckType);
  4270. if (outerTypeDef != NULL)
  4271. {
  4272. // Check statics in outer type
  4273. return LookupField(targetSrc, BfTypedValue(outerTypeDef), fieldName, BfLookupFieldFlag_CheckingOuter);
  4274. }
  4275. return BfTypedValue();
  4276. }
  4277. void BfExprEvaluator::ResolveArgValues(BfResolvedArgs& resolvedArgs, BfResolveArgsFlags flags)
  4278. {
  4279. static int idx = 0;
  4280. idx++;
  4281. int curIdx = idx;
  4282. if (resolvedArgs.mArguments == NULL)
  4283. return;
  4284. int argCount = (int)resolvedArgs.mArguments->size();
  4285. if ((resolvedArgs.mCommas != NULL) && (resolvedArgs.mCommas->size() != 0) && (resolvedArgs.mCommas->size() >= resolvedArgs.mArguments->size()))
  4286. {
  4287. //mModule->FailAfter("Expression expected", resolvedArgs.mCommas->back());
  4288. argCount++;
  4289. }
  4290. BfAutoComplete* autoComplete = GetAutoComplete();
  4291. bool hadIgnoredFixits = false;
  4292. if (autoComplete != NULL)
  4293. {
  4294. hadIgnoredFixits = autoComplete->mIgnoreFixits;
  4295. if (flags & BfResolveArgsFlag_DeferFixits)
  4296. autoComplete->mIgnoreFixits = true;
  4297. }
  4298. int deferredArgIdx = 0;
  4299. SizedArray<BfExpression*, 8> deferredArgs;
  4300. int argIdx = 0;
  4301. while (true)
  4302. {
  4303. //printf("Args: %p %p %d\n", resolvedArgs.mArguments, resolvedArgs.mArguments->mVals, resolvedArgs.mArguments->mSize);
  4304. BfExpression* argExpr = NULL;
  4305. bool isDeferredArg = false;
  4306. int curArgIdx = -1;
  4307. if (deferredArgIdx < deferredArgs.size())
  4308. {
  4309. argExpr = deferredArgs[deferredArgIdx++];
  4310. isDeferredArg = true;
  4311. }
  4312. else if (argIdx >= argCount)
  4313. {
  4314. break;
  4315. }
  4316. else
  4317. {
  4318. curArgIdx = argIdx++;
  4319. if (curArgIdx < resolvedArgs.mArguments->size())
  4320. argExpr = (*resolvedArgs.mArguments)[curArgIdx];
  4321. }
  4322. if (argExpr == NULL)
  4323. {
  4324. if (curArgIdx == 0)
  4325. {
  4326. if (resolvedArgs.mOpenToken != NULL)
  4327. mModule->FailAfter("Expression expected", resolvedArgs.mOpenToken);
  4328. }
  4329. else if (resolvedArgs.mCommas != NULL)
  4330. mModule->FailAfter("Expression expected", (*resolvedArgs.mCommas)[curArgIdx - 1]);
  4331. }
  4332. if (auto typedValueExpr = BfNodeDynCast<BfTypedValueExpression>(argExpr))
  4333. {
  4334. BfResolvedArg resolvedArg;
  4335. resolvedArg.mTypedValue = typedValueExpr->mTypedValue;
  4336. resolvedArg.mExpression = typedValueExpr->mRefNode;
  4337. resolvedArgs.mResolvedArgs.push_back(resolvedArg);
  4338. continue;
  4339. }
  4340. BfResolvedArg resolvedArg;
  4341. if (isDeferredArg)
  4342. resolvedArg.mArgFlags = (BfArgFlags)(resolvedArg.mArgFlags | BfArgFlag_StringInterpolateArg);
  4343. BfExprEvaluator exprEvaluator(mModule);
  4344. exprEvaluator.mResolveGenericParam = (flags & BfResolveArgsFlag_AllowUnresolvedTypes) == 0;
  4345. exprEvaluator.mBfEvalExprFlags = (BfEvalExprFlags)(exprEvaluator.mBfEvalExprFlags | BfEvalExprFlags_AllowRefExpr | BfEvalExprFlags_AllowOutExpr);
  4346. bool handled = false;
  4347. bool evaluated = false;
  4348. if (auto interpolateExpr = BfNodeDynCastExact<BfStringInterpolationExpression>(argExpr))
  4349. {
  4350. if ((interpolateExpr->mAllocNode == NULL) || ((flags & BfResolveArgsFlag_InsideStringInterpolationAlloc) != 0))
  4351. {
  4352. resolvedArg.mArgFlags = (BfArgFlags)(resolvedArg.mArgFlags | BfArgFlag_StringInterpolateFormat);
  4353. for (auto innerExpr : interpolateExpr->mExpressions)
  4354. deferredArgs.Add(innerExpr);
  4355. }
  4356. }
  4357. if (auto unaryOpExpr = BfNodeDynCastExact<BfUnaryOperatorExpression>(argExpr))
  4358. {
  4359. if (unaryOpExpr->mOp == BfUnaryOp_Cascade)
  4360. {
  4361. resolvedArg.mArgFlags = (BfArgFlags)(resolvedArg.mArgFlags | BfArgFlag_Cascade);
  4362. argExpr = unaryOpExpr->mExpression;
  4363. }
  4364. }
  4365. bool deferParamEval = false;
  4366. if ((flags & BfResolveArgsFlag_DeferParamEval) != 0)
  4367. {
  4368. if (argExpr != NULL)
  4369. {
  4370. BfDeferEvalChecker deferEvalChecker;
  4371. deferEvalChecker.mDeferDelegateBind = false;
  4372. argExpr->Accept(&deferEvalChecker);
  4373. deferParamEval = deferEvalChecker.mNeedsDeferEval;
  4374. }
  4375. }
  4376. if (deferParamEval)
  4377. {
  4378. resolvedArg.mArgFlags = (BfArgFlags)(resolvedArg.mArgFlags | BfArgFlag_DeferredEval);
  4379. handled = true;
  4380. }
  4381. else if (auto delegateBindExpression = BfNodeDynCast<BfDelegateBindExpression>(argExpr))
  4382. {
  4383. resolvedArg.mArgFlags = (BfArgFlags)(resolvedArg.mArgFlags | BfArgFlag_DelegateBindAttempt);
  4384. handled = true;
  4385. }
  4386. else if (auto lambdaBindExpression = BfNodeDynCast<BfLambdaBindExpression>(argExpr))
  4387. {
  4388. resolvedArg.mArgFlags = (BfArgFlags)(resolvedArg.mArgFlags | BfArgFlag_LambdaBindAttempt);
  4389. handled = true;
  4390. }
  4391. else if (auto memberRef = BfNodeDynCast<BfMemberReferenceExpression>(argExpr))
  4392. {
  4393. if (memberRef->mTarget == NULL)
  4394. {
  4395. resolvedArg.mArgFlags = (BfArgFlags)(resolvedArg.mArgFlags | BfArgFlag_UnqualifiedDotAttempt);
  4396. handled = true;
  4397. }
  4398. }
  4399. else if (auto invokeExpr = BfNodeDynCast<BfInvocationExpression>(argExpr))
  4400. {
  4401. if (auto memberRef = BfNodeDynCast<BfMemberReferenceExpression>(invokeExpr->mTarget))
  4402. {
  4403. if (memberRef->mTarget == NULL)
  4404. {
  4405. resolvedArg.mArgFlags = (BfArgFlags)(resolvedArg.mArgFlags | BfArgFlag_UnqualifiedDotAttempt);
  4406. handled = true;
  4407. }
  4408. }
  4409. }
  4410. else if (auto defaultExpr = BfNodeDynCast<BfDefaultExpression>(argExpr))
  4411. {
  4412. if (defaultExpr->mTypeRef == NULL)
  4413. {
  4414. resolvedArg.mArgFlags = (BfArgFlags)(resolvedArg.mArgFlags | BfArgFlag_UntypedDefault);
  4415. handled = true;
  4416. }
  4417. }
  4418. else if (auto varDeclExpr = BfNodeDynCast<BfVariableDeclaration>(argExpr))
  4419. {
  4420. resolvedArg.mArgFlags = (BfArgFlags)(resolvedArg.mArgFlags | BfArgFlag_VariableDeclaration);
  4421. handled = true;
  4422. }
  4423. else if (auto unaryExpr = BfNodeDynCast<BfUnaryOperatorExpression>(argExpr))
  4424. {
  4425. if (unaryExpr->mOp == BfUnaryOp_Params)
  4426. {
  4427. resolvedArg.mArgFlags = (BfArgFlags)(resolvedArg.mArgFlags | BfArgFlag_ParamsExpr);
  4428. }
  4429. }
  4430. else if (auto uninitExpr = BfNodeDynCast<BfUninitializedExpression>(argExpr))
  4431. {
  4432. resolvedArg.mArgFlags = (BfArgFlags)(resolvedArg.mArgFlags | BfArgFlag_UninitializedExpr);
  4433. handled = true;
  4434. }
  4435. /*else if (auto castExpr = BfNodeDynCast<BfCastExpression>(argExpr))
  4436. {
  4437. if (auto namedTypeRef = BfNodeDynCastExact<BfNamedTypeReference>(castExpr->mTypeRef))
  4438. {
  4439. if (namedTypeRef->ToString() == "ExpectedType")
  4440. {
  4441. resolvedArg.mArgFlags = (BfArgFlags)(resolvedArg.mArgFlags | BfArgFlag_ExpectedTypeCast);
  4442. handled = true;
  4443. }
  4444. }
  4445. }*/
  4446. if ((argExpr != NULL) && (!handled))
  4447. {
  4448. bool deferParamValues = (flags & BfResolveArgsFlag_DeferParamValues) != 0;
  4449. SetAndRestoreValue<bool> ignoreWrites(mModule->mBfIRBuilder->mIgnoreWrites, mModule->mBfIRBuilder->mIgnoreWrites || deferParamValues);
  4450. auto prevInsertBlock = mModule->mBfIRBuilder->GetInsertBlock();
  4451. if (deferParamValues)
  4452. resolvedArg.mArgFlags = (BfArgFlags)(resolvedArg.mArgFlags | BfArgFlag_DeferredValue);
  4453. if (!evaluated)
  4454. {
  4455. exprEvaluator.mBfEvalExprFlags = (BfEvalExprFlags)(exprEvaluator.mBfEvalExprFlags | BfEvalExprFlags_AllowParamsExpr);
  4456. if ((resolvedArg.mArgFlags & BfArgFlag_StringInterpolateFormat) != 0)
  4457. exprEvaluator.mBfEvalExprFlags = (BfEvalExprFlags)(exprEvaluator.mBfEvalExprFlags | BfEvalExprFlags_StringInterpolateFormat);
  4458. exprEvaluator.Evaluate(argExpr, false, false, true);
  4459. }
  4460. if ((mModule->mCurMethodState != NULL) && (exprEvaluator.mResultLocalVar != NULL) && (exprEvaluator.mResultLocalVarRefNode != NULL))
  4461. {
  4462. auto localVar = exprEvaluator.mResultLocalVar;
  4463. int fieldIdx = mResultLocalVarField - 1;
  4464. auto methodState = mModule->mCurMethodState->GetMethodStateForLocal(localVar);
  4465. if (localVar->mCompositeCount >= 0)
  4466. {
  4467. if ((resolvedArg.mArgFlags & BfArgFlag_ParamsExpr) == 0)
  4468. mModule->Warn(0, "'params' token expected", argExpr);
  4469. for (int compositeIdx = 0; compositeIdx < localVar->mCompositeCount; compositeIdx++)
  4470. {
  4471. BfResolvedArg compositeResolvedArg;
  4472. auto compositeLocalVar = methodState->mLocals[localVar->mLocalVarIdx + compositeIdx + 1];
  4473. auto argValue = exprEvaluator.LoadLocal(compositeLocalVar, true);
  4474. if (argValue)
  4475. {
  4476. if (!argValue.mType->IsStruct())
  4477. argValue = mModule->LoadValue(argValue, NULL, exprEvaluator.mIsVolatileReference);
  4478. }
  4479. resolvedArg.mTypedValue = argValue;
  4480. resolvedArg.mExpression = argExpr;
  4481. resolvedArg.mArgFlags = (BfArgFlags)(resolvedArg.mArgFlags | BfArgFlag_FromParamComposite);
  4482. resolvedArgs.mResolvedArgs.push_back(resolvedArg);
  4483. }
  4484. continue;
  4485. }
  4486. }
  4487. exprEvaluator.CheckResultForReading(exprEvaluator.mResult);
  4488. auto argValue = exprEvaluator.mResult;
  4489. if (argValue)
  4490. {
  4491. //resolvedArg.mResolvedType = mModule->ResolveGenericType(argValue.mType);
  4492. resolvedArg.mResolvedType = argValue.mType;
  4493. if (resolvedArg.mResolvedType->IsRef())
  4494. argValue.mKind = BfTypedValueKind_Value;
  4495. else if ((!resolvedArg.mResolvedType->IsStruct()) && (!resolvedArg.mResolvedType->IsSizedArray()) && (!resolvedArg.mResolvedType->IsValuelessType()))
  4496. argValue = mModule->LoadValue(argValue, NULL, exprEvaluator.mIsVolatileReference);
  4497. }
  4498. resolvedArg.mTypedValue = argValue;
  4499. if (deferParamValues)
  4500. mModule->mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  4501. }
  4502. resolvedArg.mExpression = argExpr;
  4503. resolvedArgs.mResolvedArgs.push_back(resolvedArg);
  4504. }
  4505. if (autoComplete != NULL)
  4506. autoComplete->mIgnoreFixits = hadIgnoredFixits;
  4507. }
  4508. void BfExprEvaluator::PerformCallChecks(BfMethodInstance* methodInstance, BfAstNode* targetSrc)
  4509. {
  4510. BfCustomAttributes* customAttributes = methodInstance->GetCustomAttributes();
  4511. if (customAttributes != NULL)
  4512. mModule->CheckErrorAttributes(methodInstance->GetOwner(), methodInstance, customAttributes, targetSrc);
  4513. }
  4514. BfTypedValue BfExprEvaluator::CreateCall(BfAstNode* targetSrc, BfMethodInstance* methodInstance, BfIRValue func, bool bypassVirtual, SizedArrayImpl<BfIRValue>& irArgs, BfTypedValue* sret, bool isTailCall)
  4515. {
  4516. // static int sCallIdx = 0;
  4517. // if (!mModule->mCompiler->mIsResolveOnly)
  4518. // sCallIdx++;
  4519. // int callIdx = sCallIdx;
  4520. // if (callIdx == 0x000000E8)
  4521. // {
  4522. // NOP;
  4523. // }
  4524. auto methodDef = methodInstance->mMethodDef;
  4525. BfIRValue funcCallInst = func;
  4526. auto importCallKind = methodInstance->GetImportCallKind();
  4527. if ((funcCallInst) && (importCallKind != BfImportCallKind_None))
  4528. {
  4529. if ((funcCallInst.IsFake()) && (!mModule->mBfIRBuilder->mIgnoreWrites))
  4530. {
  4531. mModule->mFuncReferences.TryGetValue(methodInstance, &funcCallInst);
  4532. }
  4533. if ((importCallKind == BfImportCallKind_GlobalVar) &&
  4534. (methodInstance->mHotMethod == NULL) &&
  4535. (mModule->mCompiler->IsHotCompile()))
  4536. {
  4537. // This may actually be a BfImportCallKind_GlobalVar_Hot, so check it...
  4538. mModule->CheckHotMethod(methodInstance, "");
  4539. importCallKind = methodInstance->GetImportCallKind();
  4540. }
  4541. if (importCallKind == BfImportCallKind_GlobalVar_Hot)
  4542. {
  4543. //TODO: Check against NULL for calling BfLoadSharedLibraries
  4544. auto checkVal = mModule->mBfIRBuilder->CreateLoad(funcCallInst);
  4545. BfIRBlock nullBlock = mModule->mBfIRBuilder->CreateBlock("importNull");
  4546. BfIRBlock doneBlock = mModule->mBfIRBuilder->CreateBlock("importLoad");
  4547. auto condVal = mModule->mBfIRBuilder->CreateIsNull(checkVal);
  4548. mModule->mBfIRBuilder->CreateCondBr(condVal, nullBlock, doneBlock);
  4549. mModule->mBfIRBuilder->AddBlock(nullBlock);
  4550. mModule->mBfIRBuilder->SetInsertPoint(nullBlock);
  4551. auto loadSharedLibsFunc = mModule->GetBuiltInFunc(BfBuiltInFuncType_LoadSharedLibraries);
  4552. mModule->mBfIRBuilder->CreateCall(loadSharedLibsFunc, SizedArray<BfIRValue, 0>());
  4553. mModule->mBfIRBuilder->CreateBr(doneBlock);
  4554. mModule->mBfIRBuilder->AddBlock(doneBlock);
  4555. mModule->mBfIRBuilder->SetInsertPoint(doneBlock);
  4556. funcCallInst = mModule->mBfIRBuilder->CreateLoad(funcCallInst);
  4557. }
  4558. else
  4559. {
  4560. funcCallInst = mModule->mBfIRBuilder->CreateLoad(funcCallInst);
  4561. }
  4562. }
  4563. if ((methodInstance->GetOwner()->mTypeDef == mModule->mCompiler->mDeferredCallTypeDef) &&
  4564. (methodInstance->mMethodDef->mName == "Cancel"))
  4565. {
  4566. if (mModule->mCurMethodState != NULL)
  4567. mModule->mCurMethodState->mCancelledDeferredCall = true;
  4568. }
  4569. if (methodDef->mIsNoReturn)
  4570. {
  4571. mModule->mCurMethodState->SetHadReturn(true);
  4572. mModule->mCurMethodState->mLeftBlockUncond = true;
  4573. }
  4574. if (mModule->mCurTypeInstance != NULL)
  4575. {
  4576. bool isVirtual = (methodInstance->mVirtualTableIdx != -1) && (!bypassVirtual);
  4577. mModule->AddDependency(methodInstance->mMethodInstanceGroup->mOwner, mModule->mCurTypeInstance, isVirtual ? BfDependencyMap::DependencyFlag_VirtualCall : BfDependencyMap::DependencyFlag_Calls);
  4578. mModule->AddCallDependency(methodInstance, bypassVirtual);
  4579. }
  4580. if (methodInstance->GetOwner()->IsUnspecializedType())
  4581. {
  4582. BF_ASSERT((!methodInstance->mIRFunction) || (methodInstance == mModule->mCurMethodInstance));
  4583. }
  4584. if (mFunctionBindResult != NULL)
  4585. {
  4586. BF_ASSERT(mFunctionBindResult->mMethodInstance == NULL);
  4587. mFunctionBindResult->mMethodInstance = methodInstance;
  4588. for (auto arg : irArgs)
  4589. mFunctionBindResult->mIRArgs.push_back(arg);
  4590. }
  4591. BfType* origReturnType = methodInstance->mReturnType;
  4592. /*if (origReturnType->IsSelf())
  4593. {
  4594. origReturnType = methodInstance->GetOwner();
  4595. BF_ASSERT(origReturnType->IsInterface());
  4596. }*/
  4597. BfType* returnType = origReturnType;
  4598. BfTypedValue sretVal;
  4599. auto _GetDefaultReturnValue = [&]()
  4600. {
  4601. if (methodInstance->mVirtualTableIdx == -1)
  4602. {
  4603. if (methodInstance->GetOwner()->IsInterface())
  4604. {
  4605. // We're attempting to directly invoke a non-virtual interface method, if we're return an interface then
  4606. // it is a concrete interface
  4607. if (returnType->IsInterface())
  4608. returnType = mModule->CreateConcreteInterfaceType(returnType->ToTypeInstance());
  4609. }
  4610. }
  4611. if ((returnType->IsVar()) && (mExpectingType != NULL))
  4612. returnType = mExpectingType;
  4613. if (returnType->IsRef())
  4614. {
  4615. auto result = mModule->GetDefaultTypedValue(returnType->GetUnderlyingType(), true, BfDefaultValueKind_Addr);
  4616. if (methodDef->mIsReadOnly)
  4617. result.mKind = BfTypedValueKind_ReadOnlyAddr;
  4618. return result;
  4619. }
  4620. else
  4621. {
  4622. auto val = mModule->GetDefaultTypedValue(returnType, true, (GetStructRetIdx(methodInstance) != -1) ? BfDefaultValueKind_Addr : BfDefaultValueKind_Value);
  4623. if (val.mKind == BfTypedValueKind_Addr)
  4624. val.mKind = BfTypedValueKind_RestrictedTempAddr;
  4625. return val;
  4626. }
  4627. };
  4628. mModule->PopulateType(origReturnType, BfPopulateType_Data);
  4629. if (GetStructRetIdx(methodInstance) != -1)
  4630. {
  4631. // We need to ensure that mReceivingValue has the correct type, otherwise it's possible that a conversion operator needs to be applied
  4632. // This happens for returning Result<T>'s with a 'T' value
  4633. if ((sret == NULL) && (mReceivingValue != NULL) && (mReceivingValue->mType == returnType))
  4634. {
  4635. sretVal = *mReceivingValue;
  4636. sret = &sretVal;
  4637. auto ptrType = mModule->CreatePointerType(returnType);
  4638. if (returnType != sret->mType)
  4639. {
  4640. sret->mValue = mModule->mBfIRBuilder->CreateBitCast(sret->mValue, mModule->mBfIRBuilder->MapType(ptrType));
  4641. sret->mType = returnType;
  4642. }
  4643. mReceivingValue = NULL;
  4644. }
  4645. if (sret == NULL)
  4646. {
  4647. sretVal = BfTypedValue(mModule->CreateAlloca(returnType), returnType, BfTypedValueKind_RestrictedTempAddr);
  4648. sret = &sretVal;
  4649. }
  4650. }
  4651. else
  4652. {
  4653. BF_ASSERT(sret == NULL);
  4654. }
  4655. if ((mModule->mCurMethodState != NULL) && (mModule->mCurMethodState->mClosureState != NULL) && (mModule->mCurMethodState->mClosureState->mCapturing))
  4656. {
  4657. return _GetDefaultReturnValue();
  4658. }
  4659. BF_ASSERT(!methodInstance->mDisallowCalling);
  4660. if ((mModule->mCompiler->mResolvePassData != NULL) && (mModule->mCompiler->mResolvePassData->mAutoComplete != NULL))
  4661. {
  4662. bool wantQuickEval = true;
  4663. if (IsComptime())
  4664. {
  4665. auto autoComplete = mModule->mCompiler->mResolvePassData->mAutoComplete;
  4666. wantQuickEval =
  4667. ((autoComplete->mResolveType != BfResolveType_Autocomplete) &&
  4668. (autoComplete->mResolveType != BfResolveType_Autocomplete_HighPri) &&
  4669. (autoComplete->mResolveType != BfResolveType_GetResultString));
  4670. }
  4671. if (wantQuickEval)
  4672. {
  4673. // In an autocomplete pass we may have stale method references that need to be resolved
  4674. // in the full classify pass, and in the full classify pass while just refreshing internals, we
  4675. // may have NULL funcs temporarily. We simply skip generating the method call here.
  4676. if ((mBfEvalExprFlags & BfEvalExprFlags_Comptime) != 0)
  4677. {
  4678. if (methodInstance->mReturnType->IsInstanceOf(mModule->mCompiler->mSpanTypeDef))
  4679. {
  4680. if ((mExpectingType != NULL) && (mExpectingType->IsSizedArray()))
  4681. {
  4682. return BfTypedValue(mModule->mBfIRBuilder->GetUndefConstValue(mModule->mBfIRBuilder->MapType(mExpectingType)), mExpectingType);
  4683. }
  4684. }
  4685. auto returnType = methodInstance->mReturnType;
  4686. if ((returnType->IsVar()) && (mExpectingType != NULL))
  4687. returnType = mExpectingType;
  4688. if (methodInstance->mReturnType->IsValuelessType())
  4689. return BfTypedValue(mModule->mBfIRBuilder->GetFakeVal(), returnType);
  4690. return BfTypedValue(mModule->mBfIRBuilder->GetUndefConstValue(mModule->mBfIRBuilder->MapType(returnType)), returnType);
  4691. }
  4692. BfTypedValue result;
  4693. if (sret != NULL)
  4694. result = *sret;
  4695. else
  4696. result = _GetDefaultReturnValue();
  4697. return result;
  4698. }
  4699. }
  4700. bool forceBind = false;
  4701. if (mModule->mCompiler->mCEMachine != NULL)
  4702. {
  4703. bool doConstReturn = false;
  4704. if ((mBfEvalExprFlags & BfEvalExprFlags_Comptime) != 0)
  4705. {
  4706. if (mFunctionBindResult != NULL)
  4707. {
  4708. forceBind = true;
  4709. }
  4710. else if ((mBfEvalExprFlags & BfEvalExprFlags_InCascade) != 0)
  4711. {
  4712. mModule->Fail("Const evaluation not allowed with cascade operator", targetSrc);
  4713. }
  4714. else if (methodInstance->mIsUnspecialized)
  4715. {
  4716. doConstReturn = true;
  4717. }
  4718. else if (((methodInstance->mComptimeFlags & BfComptimeFlag_OnlyFromComptime) != 0) && (!mModule->mIsComptimeModule))
  4719. {
  4720. // This either generated an error already or this is just the non-const type check pass for a comptime-only method
  4721. doConstReturn = true;
  4722. }
  4723. else if ((mBfEvalExprFlags & BfEvalExprFlags_DisallowComptime) != 0)
  4724. {
  4725. doConstReturn = true;
  4726. }
  4727. else
  4728. {
  4729. CeEvalFlags evalFlags = CeEvalFlags_None;
  4730. auto constRet = mModule->mCompiler->mCEMachine->Call(targetSrc, mModule, methodInstance, irArgs, evalFlags, mExpectingType);
  4731. if (constRet)
  4732. {
  4733. BF_ASSERT(!constRet.mType->IsVar());
  4734. return constRet;
  4735. }
  4736. if (mModule->mCompiler->mFastFinish)
  4737. {
  4738. if ((mModule->mCurMethodInstance == NULL) || (!mModule->mCurMethodInstance->mIsAutocompleteMethod))
  4739. {
  4740. // We didn't properly resolve this so queue for a rebuild later
  4741. mModule->DeferRebuildType(mModule->mCurTypeInstance);
  4742. }
  4743. }
  4744. doConstReturn = true;
  4745. }
  4746. }
  4747. else if (mModule->mIsComptimeModule)
  4748. {
  4749. if (methodInstance->mIsUnspecialized)
  4750. {
  4751. doConstReturn = true;
  4752. }
  4753. else
  4754. {
  4755. mModule->mCompiler->mCEMachine->QueueMethod(methodInstance, func);
  4756. }
  4757. }
  4758. if (doConstReturn)
  4759. {
  4760. if ((returnType->IsVar()) && (mExpectingType != NULL))
  4761. returnType = mExpectingType;
  4762. if (returnType->IsRef())
  4763. {
  4764. return _GetDefaultReturnValue();
  4765. }
  4766. else
  4767. {
  4768. if (returnType->IsInstanceOf(mModule->mCompiler->mSpanTypeDef))
  4769. {
  4770. if (mExpectingType->IsUndefSizedArray())
  4771. {
  4772. if (returnType->GetUnderlyingType() == mExpectingType->GetUnderlyingType())
  4773. return mModule->GetDefaultTypedValue(mExpectingType, true, BfDefaultValueKind_Undef);
  4774. }
  4775. }
  4776. return mModule->GetDefaultTypedValue(returnType, true, BfDefaultValueKind_Undef);
  4777. }
  4778. return _GetDefaultReturnValue();
  4779. }
  4780. }
  4781. if (!forceBind)
  4782. {
  4783. if (((!func) && (methodInstance->mIsUnspecialized)) || (mModule->mBfIRBuilder->mIgnoreWrites))
  4784. {
  4785. // We don't actually submit method calls for unspecialized methods
  4786. // - this includes all methods in unspecialized types
  4787. return _GetDefaultReturnValue();
  4788. }
  4789. }
  4790. if (methodInstance->mVirtualTableIdx != -1)
  4791. {
  4792. if ((!bypassVirtual) && (mDeferCallRef == NULL))
  4793. {
  4794. if ((methodDef->mIsOverride) && (mModule->mCurMethodInstance->mIsReified))
  4795. {
  4796. // Ensure that declaring method gets referenced
  4797. auto typeInstance = methodInstance->GetOwner();
  4798. auto& vEntry = typeInstance->mVirtualMethodTable[methodInstance->mVirtualTableIdx];
  4799. BfMethodInstance* declaringMethodInstance = vEntry.mDeclaringMethod;
  4800. if ((declaringMethodInstance->mMethodInstanceGroup->mOnDemandKind < BfMethodOnDemandKind_InWorkList) || (!declaringMethodInstance->mIsReified))
  4801. mModule->GetMethodInstance(declaringMethodInstance);
  4802. }
  4803. auto funcType = mModule->mBfIRBuilder->MapMethod(methodInstance);
  4804. auto funcPtrType1 = mModule->mBfIRBuilder->GetPointerTo(funcType);
  4805. auto funcPtrType2 = mModule->mBfIRBuilder->GetPointerTo(funcPtrType1);
  4806. auto funcPtrType3 = mModule->mBfIRBuilder->GetPointerTo(funcPtrType2);
  4807. auto funcPtrType4 = mModule->mBfIRBuilder->GetPointerTo(funcPtrType3);
  4808. if (methodInstance->mMethodInstanceGroup->mOwner->IsInterface())
  4809. {
  4810. if (mModule->mIsComptimeModule)
  4811. {
  4812. funcCallInst = mModule->mBfIRBuilder->Comptime_GetInterfaceFunc(irArgs[0], methodInstance->mMethodInstanceGroup->mOwner->mTypeId, methodInstance->mMethodDef->mIdx, funcPtrType1);
  4813. }
  4814. else
  4815. {
  4816. // IFace dispatch
  4817. auto ifaceTypeInst = methodInstance->mMethodInstanceGroup->mOwner;
  4818. BfIRValue slotOfs = mModule->GetInterfaceSlotNum(methodInstance->mMethodInstanceGroup->mOwner);
  4819. auto vDataPtrPtr = mModule->mBfIRBuilder->CreateBitCast(irArgs[0], funcPtrType4);
  4820. auto vDataPtr = mModule->FixClassVData(mModule->mBfIRBuilder->CreateLoad(vDataPtrPtr/*, "vtable"*/));
  4821. auto ifacePtrPtr = mModule->mBfIRBuilder->CreateInBoundsGEP(vDataPtr, slotOfs/*, "iface"*/);
  4822. auto ifacePtr = mModule->mBfIRBuilder->CreateLoad(ifacePtrPtr);
  4823. auto funcPtr = mModule->mBfIRBuilder->CreateInBoundsGEP(ifacePtr, methodInstance->mVirtualTableIdx/*, "vfn"*/);
  4824. funcCallInst = mModule->mBfIRBuilder->CreateLoad(funcPtr);
  4825. }
  4826. }
  4827. else if (mModule->mIsComptimeModule)
  4828. {
  4829. funcCallInst = mModule->mBfIRBuilder->Comptime_GetVirtualFunc(irArgs[0], methodInstance->mVirtualTableIdx, funcPtrType1);
  4830. }
  4831. else
  4832. {
  4833. mModule->HadSlotCountDependency();
  4834. // Virtual dispatch
  4835. // int vDataIdx = 0;
  4836. // vDataIdx += 1 + methodInstance->GetOwner()->GetDynCastVDataCount() + mModule->mCompiler->mMaxInterfaceSlots;
  4837. BfIRValue vDataPtr;
  4838. BfIRValue vDataIdx;
  4839. if ((mModule->mCompiler->mOptions.mHasVDataExtender) && (mModule->mCompiler->IsHotCompile()))
  4840. {
  4841. auto typeInst = methodInstance->mMethodInstanceGroup->mOwner;
  4842. int extMethodIdx = (methodInstance->mVirtualTableIdx - typeInst->GetImplBaseVTableSize()) - typeInst->GetOrigSelfVTableSize();
  4843. if (extMethodIdx >= 0)
  4844. {
  4845. BF_ASSERT(mModule->mCompiler->IsHotCompile());
  4846. // We have grown outside our original virtual table, Load the new vdataPtr from the mHasVDataExtender
  4847. // vDataPtr = obj.vtable.extension.entry[curVersion]
  4848. BfIRValue vDataPtrPtr = mModule->mBfIRBuilder->CreateBitCast(irArgs[0], funcPtrType4);
  4849. vDataPtr = mModule->FixClassVData(mModule->mBfIRBuilder->CreateLoad(vDataPtrPtr));
  4850. // The offset of the vExt is one past the base vtable. When a base class extends its virtual table, an entry
  4851. // for that new method is inserted in mVirtualMethodTable (thus increasing the index relative to GetBaseVTableSize()),
  4852. // but the actual written vtable position doesn't change, hence offsetting from GetOrigBaseVTableSize()
  4853. #ifdef _DEBUG
  4854. int vExtIdx = typeInst->GetImplBaseVTableSize();
  4855. BF_ASSERT(typeInst->mVirtualMethodTable[vExtIdx].mDeclaringMethod.mMethodNum == -1); // A type entry with a -1 mMethodNum means it's a vtable ext slot
  4856. #endif
  4857. int vExtOfs = typeInst->GetOrigImplBaseVTableSize();
  4858. vDataIdx = mModule->mBfIRBuilder->CreateConst(BfTypeCode_Int32, 1 + mModule->mCompiler->GetDynCastVDataCount() + mModule->mCompiler->mMaxInterfaceSlots);
  4859. vDataIdx = mModule->mBfIRBuilder->CreateAdd(vDataIdx, mModule->mBfIRBuilder->CreateConst(BfTypeCode_Int32, vExtOfs));
  4860. BfIRValue extendPtr = mModule->mBfIRBuilder->CreateInBoundsGEP(vDataPtr, vDataIdx);
  4861. vDataPtr = mModule->mBfIRBuilder->CreateLoad(extendPtr);
  4862. vDataIdx = mModule->mBfIRBuilder->CreateConst(BfTypeCode_Int32, extMethodIdx);
  4863. }
  4864. else
  4865. {
  4866. // Map this new virtual index back to the original index
  4867. //vDataIdx += (methodInstance->mVirtualTableIdx - typeInst->GetBaseVTableSize()) + typeInst->GetOrigBaseVTableSize();
  4868. //vDataIdx = mModule->mBfIRBuilder->CreateConst(BfTypeCode_Int32, 1 + methodInstance->GetOwner()->GetDynCastVDataCount() + mModule->mCompiler->mMaxInterfaceSlots);
  4869. vDataIdx = mModule->mBfIRBuilder->GetConfigConst(BfIRConfigConst_VirtualMethodOfs, BfTypeCode_Int32);
  4870. vDataIdx = mModule->mBfIRBuilder->CreateAdd(vDataIdx, mModule->mBfIRBuilder->CreateConst(BfTypeCode_Int32,
  4871. (methodInstance->mVirtualTableIdx - typeInst->GetImplBaseVTableSize()) + typeInst->GetOrigImplBaseVTableSize()));
  4872. }
  4873. }
  4874. else
  4875. {
  4876. //vDataIdx += methodInstance->mVirtualTableIdx;
  4877. //vDataIdx = mModule->mBfIRBuilder->CreateConst(BfTypeCode_Int32, 1 + methodInstance->GetOwner()->GetDynCastVDataCount() + mModule->mCompiler->mMaxInterfaceSlots);
  4878. vDataIdx = mModule->mBfIRBuilder->GetConfigConst(BfIRConfigConst_VirtualMethodOfs, BfTypeCode_Int32);
  4879. vDataIdx = mModule->mBfIRBuilder->CreateAdd(vDataIdx, mModule->mBfIRBuilder->CreateConst(BfTypeCode_Int32, methodInstance->mVirtualTableIdx));
  4880. }
  4881. if (!vDataPtr)
  4882. {
  4883. BfIRValue vDataPtrPtr = mModule->mBfIRBuilder->CreateBitCast(irArgs[0], funcPtrType3);
  4884. vDataPtr = mModule->FixClassVData(mModule->mBfIRBuilder->CreateLoad(vDataPtrPtr/*, "vtable"*/));
  4885. }
  4886. auto funcPtr = mModule->mBfIRBuilder->CreateInBoundsGEP(vDataPtr, vDataIdx/*, "vfn"*/);
  4887. funcCallInst = mModule->mBfIRBuilder->CreateLoad(funcPtr);
  4888. }
  4889. }
  4890. }
  4891. else // non-virtual
  4892. {
  4893. if (methodInstance->GetOwner()->IsInterface())
  4894. {
  4895. // We're attempting to directly invoke a non-virtual interface method, this will happen during the unspecialized pass
  4896. // OR if we had an error and didn't find an implementing member in the actual target
  4897. if (!mModule->mCurMethodInstance->mIsUnspecialized)
  4898. mModule->AssertErrorState();
  4899. if (returnType->IsInterface())
  4900. returnType = mModule->CreateConcreteInterfaceType(returnType->ToTypeInstance());
  4901. return _GetDefaultReturnValue();
  4902. }
  4903. }
  4904. if (mFunctionBindResult != NULL)
  4905. {
  4906. mFunctionBindResult->mFunc = funcCallInst;
  4907. if (irArgs.size() != 0)
  4908. {
  4909. auto targetType = methodInstance->mMethodInstanceGroup->mOwner;
  4910. if ((targetType->IsValueType()) && (targetType->IsSplattable()) && (!methodDef->HasNoThisSplat()) && (!IsComptime()))
  4911. mFunctionBindResult->mTarget = BfTypedValue(irArgs[0], targetType, BfTypedValueKind_SplatHead);
  4912. else
  4913. mFunctionBindResult->mTarget = BfTypedValue(irArgs[0], targetType, targetType->IsComposite() ? BfTypedValueKind_Addr : BfTypedValueKind_Value);
  4914. }
  4915. else
  4916. {
  4917. mFunctionBindResult->mTarget = BfTypedValue();
  4918. }
  4919. return BfTypedValue();
  4920. }
  4921. if (methodInstance->mReturnType == NULL)
  4922. {
  4923. mModule->AssertErrorState();
  4924. return BfTypedValue();
  4925. }
  4926. if ((mModule->mCurMethodInstance != NULL) && (mModule->mCurMethodInstance->mIsUnspecialized))
  4927. {
  4928. // Don't actually do the call - our target may be a generic param
  4929. return _GetDefaultReturnValue();
  4930. }
  4931. if (mDeferCallRef != NULL)
  4932. {
  4933. mModule->AddDeferredCall(BfModuleMethodInstance(methodInstance, func), irArgs, mDeferScopeAlloc, mDeferCallRef);
  4934. //return _GetDefaultReturnValue();
  4935. return mModule->GetFakeTypedValue(returnType);
  4936. }
  4937. if (!funcCallInst)
  4938. {
  4939. if ((mModule->HasCompiledOutput()) || (mModule->mCompiler->mOptions.mExtraResolveChecks))
  4940. {
  4941. // This can happen either from an error, or from the resolver while doing Internals_Changed processing
  4942. mModule->AssertErrorState();
  4943. }
  4944. //return mModule->GetDefaultTypedValue(returnType,/*, true*/false, returnType->IsComposite());
  4945. return _GetDefaultReturnValue();
  4946. }
  4947. bool hasResult = !methodInstance->mReturnType->IsValuelessType();
  4948. BfIRValue firstArg;
  4949. if (irArgs.size() != 0)
  4950. firstArg = irArgs[0];
  4951. auto methodInstOwner = methodInstance->GetOwner();
  4952. auto expectCallingConvention = mModule->GetIRCallingConvention(methodInstance);
  4953. if ((methodInstOwner->IsFunction()) && (methodInstance->GetParamCount() > 0) && (methodInstance->GetParamName(0) == "this"))
  4954. {
  4955. auto paramType = methodInstance->GetParamType(0);
  4956. if (!paramType->IsValueType())
  4957. expectCallingConvention = BfIRCallingConv_ThisCall;
  4958. }
  4959. if ((methodInstance->mAlwaysInline) && (mModule->mCompiler->mOptions.mEmitLineInfo))
  4960. {
  4961. // Emit a NOP so we always have a "step over" point
  4962. mModule->EmitEnsureInstructionAt();
  4963. }
  4964. if (returnType->IsComposite())
  4965. mModule->mBfIRBuilder->PopulateType(returnType);
  4966. methodInstance->mMethodInstanceGroup->mHasEmittedReference = true;
  4967. BfIRValue callInst;
  4968. int callIRArgCount = (int)irArgs.size();
  4969. if (sret != NULL)
  4970. {
  4971. SizedArray<BfIRValue, 8> sretIRArgs;
  4972. int sretIdx = GetStructRetIdx(methodInstance);
  4973. int inIdx = 0;
  4974. for (int outIdx = 0; outIdx < irArgs.size() + 1; outIdx++)
  4975. {
  4976. if (outIdx == sretIdx)
  4977. {
  4978. sretIRArgs.Add(sret->mValue);
  4979. continue;
  4980. }
  4981. sretIRArgs.Add(irArgs[inIdx++]);
  4982. }
  4983. callInst = mModule->mBfIRBuilder->CreateCall(funcCallInst, sretIRArgs);
  4984. callIRArgCount++;
  4985. }
  4986. else
  4987. {
  4988. callInst = mModule->mBfIRBuilder->CreateCall(funcCallInst, irArgs);
  4989. if ((hasResult) && (!methodDef->mName.IsEmpty()) && (!methodInstance->mIsIntrinsic))
  4990. mModule->mBfIRBuilder->SetName(callInst, methodDef->mName);
  4991. }
  4992. if ((expectCallingConvention != BfIRCallingConv_CDecl) && (!methodInstance->mIsIntrinsic))
  4993. mModule->mBfIRBuilder->SetCallCallingConv(callInst, expectCallingConvention);
  4994. if ((methodDef->mIsNoReturn) && (!methodInstance->mIsIntrinsic))
  4995. mModule->mBfIRBuilder->Call_AddAttribute(callInst, -1, BfIRAttribute_NoReturn);
  4996. bool hadAttrs = false;
  4997. int paramIdx = 0;
  4998. bool doingThis = !methodDef->mIsStatic;
  4999. int argIdx = 0;
  5000. if (methodDef->mHasExplicitThis)
  5001. paramIdx++;
  5002. int paramCount = methodInstance->GetParamCount();
  5003. for ( ; argIdx < callIRArgCount ; )
  5004. {
  5005. if (methodInstance->mIsIntrinsic)
  5006. break;
  5007. if (argIdx == GetStructRetIdx(methodInstance))
  5008. {
  5009. mModule->mBfIRBuilder->Call_AddAttribute(callInst, argIdx + 1, BfIRAttribute_StructRet);
  5010. argIdx++;
  5011. continue;
  5012. }
  5013. auto _HandleParamType = [&] (BfType* paramType)
  5014. {
  5015. if (paramType->IsStruct())
  5016. {
  5017. if ((!doingThis) || (!methodDef->mIsMutating && methodInstance->AllowsSplatting(paramIdx)))
  5018. {
  5019. BfTypeCode loweredTypeCode = BfTypeCode_None;
  5020. BfTypeCode loweredTypeCode2 = BfTypeCode_None;
  5021. if (paramType->GetLoweredType(BfTypeUsage_Parameter, &loweredTypeCode, &loweredTypeCode2))
  5022. {
  5023. argIdx++;
  5024. if (loweredTypeCode2 != BfTypeCode_None)
  5025. argIdx++;
  5026. return; // Lowering never requires attributes
  5027. }
  5028. }
  5029. }
  5030. int addDeref = -1;
  5031. if (paramType->IsRef())
  5032. {
  5033. auto refType = (BfRefType*)paramType;
  5034. auto elementType = refType->mElementType;
  5035. mModule->PopulateType(elementType, BfPopulateType_Data);
  5036. addDeref = elementType->mSize;
  5037. if ((addDeref <= 0) && (!elementType->IsValuelessType()))
  5038. mModule->AssertErrorState();
  5039. }
  5040. if ((paramType->IsComposite()) && (!paramType->IsTypedPrimitive()))
  5041. {
  5042. if (mModule->mCompiler->mOptions.mAllowStructByVal)
  5043. {
  5044. //byval
  5045. }
  5046. else
  5047. {
  5048. mModule->PopulateType(paramType, BfPopulateType_Data);
  5049. auto typeInst = paramType->ToTypeInstance();
  5050. if ((typeInst != NULL) && (typeInst->mIsCRepr) && (typeInst->IsSplattable()) && (!IsComptime()))
  5051. {
  5052. // We're splatting
  5053. }
  5054. else
  5055. {
  5056. if (doingThis)
  5057. {
  5058. mModule->mBfIRBuilder->Call_AddAttribute(callInst, argIdx + 1, BfIRAttribute_NoCapture);
  5059. addDeref = paramType->mSize;
  5060. }
  5061. else if ((methodInstance->WantsStructsAttribByVal()) && (!paramType->IsSizedArray()))
  5062. {
  5063. mModule->mBfIRBuilder->Call_AddAttribute(callInst, argIdx + 1, BfIRAttribute_ByVal, mModule->mSystem->mPtrSize);
  5064. }
  5065. }
  5066. }
  5067. }
  5068. else if (paramType->IsPrimitiveType())
  5069. {
  5070. auto primType = (BfPrimitiveType*)paramType;
  5071. if ((primType->mTypeDef->mTypeCode == BfTypeCode_Boolean) && (!methodInstance->mIsIntrinsic))
  5072. mModule->mBfIRBuilder->Call_AddAttribute(callInst, argIdx + 1, BfIRAttribute_ZExt);
  5073. }
  5074. if (addDeref >= 0)
  5075. {
  5076. mModule->mBfIRBuilder->Call_AddAttribute(callInst, argIdx + 1, BfIRAttribute_Dereferencable, addDeref);
  5077. }
  5078. argIdx++;
  5079. };
  5080. BfType* paramType = NULL;
  5081. if (doingThis)
  5082. {
  5083. int thisIdx = methodInstance->GetThisIdx();
  5084. paramType = methodInstance->GetThisType();
  5085. if (paramType->IsValuelessType())
  5086. {
  5087. doingThis = false;
  5088. continue;
  5089. }
  5090. bool isSplatted = methodInstance->GetParamIsSplat(thisIdx) && (!IsComptime()); // (resolvedTypeRef->IsSplattable()) && (!methodDef->mIsMutating);
  5091. if (isSplatted)
  5092. {
  5093. BfTypeUtils::SplatIterate(_HandleParamType, paramType);
  5094. doingThis = false;
  5095. continue;
  5096. }
  5097. else
  5098. _HandleParamType(paramType);
  5099. }
  5100. else
  5101. {
  5102. if (paramIdx >= methodInstance->GetParamCount())
  5103. break;
  5104. paramType = methodInstance->GetParamType(paramIdx);
  5105. BfTypeCode loweredTypeCode = BfTypeCode_None;
  5106. BfTypeCode loweredTypeCode2 = BfTypeCode_None;
  5107. if (paramType->GetLoweredType(BfTypeUsage_Parameter, &loweredTypeCode, &loweredTypeCode2))
  5108. {
  5109. argIdx++;
  5110. paramIdx++;
  5111. if (loweredTypeCode2 != BfTypeCode_None)
  5112. argIdx++;
  5113. continue;
  5114. }
  5115. if ((paramType->IsValuelessType()) && (!paramType->IsMethodRef()))
  5116. {
  5117. paramIdx++;
  5118. continue;
  5119. }
  5120. if ((methodInstance->GetParamIsSplat(paramIdx)) && (!IsComptime()))
  5121. {
  5122. BfTypeUtils::SplatIterate(_HandleParamType, paramType);
  5123. paramIdx++;
  5124. continue;
  5125. }
  5126. else
  5127. _HandleParamType(methodInstance->GetParamType(paramIdx));
  5128. }
  5129. if (doingThis)
  5130. doingThis = false;
  5131. else
  5132. paramIdx++;
  5133. //argIdx++;
  5134. }
  5135. if (isTailCall)
  5136. mModule->mBfIRBuilder->SetTailCall(callInst);
  5137. if (methodDef->mIsNoReturn)
  5138. {
  5139. mModule->mBfIRBuilder->CreateUnreachable();
  5140. // For debuggability when looking back at stack trace
  5141. //mModule->ExtendLocalLifetimes(0);
  5142. if (mModule->IsTargetingBeefBackend())
  5143. {
  5144. auto checkScope = mModule->mCurMethodState->mCurScope;
  5145. while (checkScope != NULL)
  5146. {
  5147. mModule->EmitLifetimeEnds(checkScope);
  5148. checkScope = checkScope->mPrevScope;
  5149. }
  5150. // This 'fake' branch extends lifetimes of outer variable scopes
  5151. if (mModule->mCurMethodState->mIRExitBlock)
  5152. mModule->mBfIRBuilder->CreateBr_Fake(mModule->mCurMethodState->mIRExitBlock);
  5153. }
  5154. }
  5155. else
  5156. {
  5157. if (mModule->mCurMethodState != NULL)
  5158. mModule->mCurMethodState->mMayNeedThisAccessCheck = true;
  5159. }
  5160. BfTypedValue result;
  5161. if (sret != NULL)
  5162. result = *sret;
  5163. else if (hasResult)
  5164. {
  5165. BfTypeCode loweredRetType = BfTypeCode_None;
  5166. BfTypeCode loweredRetType2 = BfTypeCode_None;
  5167. if ((!IsComptime()) && (methodInstance->GetLoweredReturnType(&loweredRetType, &loweredRetType2)))
  5168. {
  5169. auto retVal = mModule->CreateAlloca(methodInstance->mReturnType);
  5170. BfIRType loweredIRType = mModule->GetIRLoweredType(loweredRetType, loweredRetType2);
  5171. loweredIRType = mModule->mBfIRBuilder->GetPointerTo(loweredIRType);
  5172. auto castedRetVal = mModule->mBfIRBuilder->CreateBitCast(retVal, loweredIRType);
  5173. mModule->mBfIRBuilder->CreateStore(callInst, castedRetVal);
  5174. result = BfTypedValue(retVal, methodInstance->mReturnType, BfTypedValueKind_RestrictedTempAddr);
  5175. }
  5176. else
  5177. result = BfTypedValue(callInst, methodInstance->mReturnType);
  5178. }
  5179. else
  5180. result = mModule->GetFakeTypedValue(methodInstance->mReturnType);
  5181. if (result.mType->IsRef())
  5182. {
  5183. result = mModule->RemoveRef(result);
  5184. if (methodDef->mIsReadOnly)
  5185. {
  5186. if (result.mKind == BfTypedValueKind_Addr)
  5187. result.mKind = BfTypedValueKind_ReadOnlyAddr;
  5188. }
  5189. }
  5190. return result;
  5191. }
  5192. BfTypedValue BfExprEvaluator::CreateCall(BfMethodMatcher* methodMatcher, BfTypedValue target)
  5193. {
  5194. auto& moduleMethodInstance = methodMatcher->mBestMethodInstance;
  5195. if (!moduleMethodInstance)
  5196. moduleMethodInstance = GetSelectedMethod(methodMatcher->mTargetSrc, methodMatcher->mBestMethodTypeInstance, methodMatcher->mBestMethodDef, *methodMatcher);
  5197. if (moduleMethodInstance.mMethodInstance == NULL)
  5198. return BfTypedValue();
  5199. if ((target) && (target.mType != moduleMethodInstance.mMethodInstance->GetOwner()))
  5200. {
  5201. auto castedTarget = mModule->Cast(methodMatcher->mTargetSrc, target, moduleMethodInstance.mMethodInstance->GetOwner());
  5202. BF_ASSERT(castedTarget);
  5203. target = castedTarget;
  5204. }
  5205. PerformCallChecks(moduleMethodInstance.mMethodInstance, methodMatcher->mTargetSrc);
  5206. BfCreateFallFlags callFlags = BfCreateFallFlags_None;
  5207. if (methodMatcher->mAllowImplicitRef)
  5208. callFlags = (BfCreateFallFlags)(callFlags | BfCreateFallFlags_AllowImplicitRef);
  5209. return CreateCall(methodMatcher->mTargetSrc, target, BfTypedValue(), methodMatcher->mBestMethodDef, moduleMethodInstance, callFlags, methodMatcher->mArguments);
  5210. }
  5211. void BfExprEvaluator::MakeBaseConcrete(BfTypedValue& typedValue)
  5212. {
  5213. if (typedValue.IsBase())
  5214. {
  5215. auto baseType = mModule->mCurTypeInstance->mBaseType;
  5216. if (baseType == NULL)
  5217. baseType = mModule->mContext->mBfObjectType;
  5218. mModule->PopulateType(baseType, BfPopulateType_Data);
  5219. typedValue = mModule->Cast(NULL, typedValue, baseType, BfCastFlags_Explicit);
  5220. }
  5221. }
  5222. void BfExprEvaluator::SplatArgs(BfTypedValue value, SizedArrayImpl<BfIRValue>& irArgs)
  5223. {
  5224. if (value.IsSplat())
  5225. {
  5226. int componentIdx = 0;
  5227. BfTypeUtils::SplatIterate([&](BfType* checkType) { irArgs.push_back(mModule->ExtractSplatValue(value, componentIdx++, checkType)); }, value.mType);
  5228. return;
  5229. }
  5230. mModule->mBfIRBuilder->PopulateType(value.mType);
  5231. std::function<void(BfTypedValue)> checkTypeLambda = [&](BfTypedValue curValue)
  5232. {
  5233. BfType* checkType = curValue.mType;
  5234. if (checkType->IsStruct())
  5235. {
  5236. auto checkTypeInstance = checkType->ToTypeInstance();
  5237. if ((checkTypeInstance->mBaseType != NULL) && (!checkTypeInstance->mBaseType->IsValuelessType()))
  5238. {
  5239. BfTypedValue baseValue;
  5240. if (curValue.IsAddr())
  5241. baseValue = BfTypedValue((!curValue.mValue) ? BfIRValue() : mModule->mBfIRBuilder->CreateInBoundsGEP(curValue.mValue, 0, 0), checkTypeInstance->mBaseType, true);
  5242. else
  5243. baseValue = BfTypedValue((!curValue.mValue) ? BfIRValue() : mModule->mBfIRBuilder->CreateExtractValue(curValue.mValue, 0), checkTypeInstance->mBaseType);
  5244. checkTypeLambda(baseValue);
  5245. }
  5246. if (checkTypeInstance->mIsUnion)
  5247. {
  5248. auto unionInnerType = checkTypeInstance->GetUnionInnerType();
  5249. if (!unionInnerType->IsValuelessType())
  5250. {
  5251. BfTypedValue unionValue = mModule->ExtractValue(curValue, NULL, 1);
  5252. checkTypeLambda(unionValue);
  5253. }
  5254. if (checkTypeInstance->IsEnum())
  5255. {
  5256. BfTypedValue dscrValue = mModule->ExtractValue(curValue, NULL, 2);
  5257. checkTypeLambda(dscrValue);
  5258. }
  5259. }
  5260. else
  5261. {
  5262. for (int fieldIdx = 0; fieldIdx < (int)checkTypeInstance->mFieldInstances.size(); fieldIdx++)
  5263. {
  5264. auto fieldInstance = (BfFieldInstance*)&checkTypeInstance->mFieldInstances[fieldIdx];
  5265. if (fieldInstance->mDataIdx >= 0)
  5266. {
  5267. BfTypedValue fieldValue = mModule->ExtractValue(curValue, fieldInstance, fieldInstance->mDataIdx);
  5268. checkTypeLambda(fieldValue);
  5269. }
  5270. }
  5271. }
  5272. }
  5273. else if (checkType->IsMethodRef())
  5274. {
  5275. BF_ASSERT(curValue.IsAddr());
  5276. BfMethodRefType* methodRefType = (BfMethodRefType*)checkType;
  5277. for (int dataIdx = 0; dataIdx < methodRefType->GetCaptureDataCount(); dataIdx++)
  5278. {
  5279. auto checkType = methodRefType->GetCaptureType(dataIdx);
  5280. if (methodRefType->WantsDataPassedAsSplat(dataIdx))
  5281. {
  5282. BF_ASSERT(dataIdx == 0);
  5283. auto ptrType = mModule->CreatePointerType(checkType);
  5284. auto elemPtr = mModule->mBfIRBuilder->CreateBitCast(curValue.mValue, mModule->mBfIRBuilder->MapType(ptrType));
  5285. checkTypeLambda(BfTypedValue(elemPtr, checkType, BfTypedValueKind_Addr));
  5286. //BfTypedValue fieldValue = mModule->ExtractValue(curValue, fieldInstance, fieldInstance->mDataIdx);
  5287. //checkTypeLambda(fieldValue);
  5288. }
  5289. else
  5290. {
  5291. auto elemVal = mModule->mBfIRBuilder->CreateInBoundsGEP(curValue.mValue, 0, dataIdx);
  5292. if (!checkType->IsComposite())
  5293. elemVal = mModule->mBfIRBuilder->CreateLoad(elemVal);
  5294. irArgs.Add(elemVal);
  5295. //irArgs.Add(mModule->ExtractValue(curValue, dataIdx));
  5296. }
  5297. }
  5298. }
  5299. else if (!checkType->IsValuelessType())
  5300. {
  5301. auto loadedVal = mModule->LoadValue(curValue);
  5302. loadedVal = mModule->PrepareConst(loadedVal);
  5303. irArgs.push_back(loadedVal.mValue);
  5304. }
  5305. };
  5306. checkTypeLambda(value);
  5307. }
  5308. void BfExprEvaluator::PushArg(BfTypedValue argVal, SizedArrayImpl<BfIRValue>& irArgs, bool disableSplat, bool disableLowering, bool isIntrinsic)
  5309. {
  5310. MakeBaseConcrete(argVal);
  5311. if (argVal.mType->IsVar())
  5312. {
  5313. argVal = mModule->GetDefaultTypedValue(mModule->mContext->mBfObjectType);
  5314. }
  5315. if (argVal.mType->IsValuelessType())
  5316. return;
  5317. bool wantSplat = false;
  5318. if ((argVal.mType->IsSplattable()) && (!disableSplat) && (!IsComptime()))
  5319. {
  5320. disableLowering = true;
  5321. auto argTypeInstance = argVal.mType->ToTypeInstance();
  5322. if (!disableSplat)
  5323. {
  5324. if ((argTypeInstance != NULL) && (argTypeInstance->mIsCRepr))
  5325. wantSplat = true;
  5326. else if ((int)irArgs.size() + argVal.mType->GetSplatCount() <= mModule->mCompiler->mOptions.mMaxSplatRegs)
  5327. wantSplat = true;
  5328. }
  5329. }
  5330. if (wantSplat)
  5331. {
  5332. SplatArgs(argVal, irArgs);
  5333. }
  5334. else
  5335. {
  5336. if (argVal.mType->IsComposite())
  5337. {
  5338. if ((mBfEvalExprFlags & BfEvalExprFlags_Comptime) != 0)
  5339. {
  5340. // Const eval entry - we want any incoming consts as they are
  5341. }
  5342. else if (isIntrinsic)
  5343. {
  5344. // We can handle composites either by value or not
  5345. }
  5346. else
  5347. argVal = mModule->MakeAddressable(argVal);
  5348. if ((!IsComptime()) && (!disableLowering) && (!isIntrinsic))
  5349. {
  5350. BfTypeCode loweredTypeCode = BfTypeCode_None;
  5351. BfTypeCode loweredTypeCode2 = BfTypeCode_None;
  5352. if (argVal.mType->GetLoweredType(BfTypeUsage_Parameter, &loweredTypeCode, &loweredTypeCode2))
  5353. {
  5354. auto primType = mModule->mBfIRBuilder->GetPrimitiveType(loweredTypeCode);
  5355. auto ptrType = mModule->mBfIRBuilder->GetPointerTo(primType);
  5356. BfIRValue primPtrVal = mModule->mBfIRBuilder->CreateBitCast(argVal.mValue, ptrType);
  5357. auto primVal = mModule->mBfIRBuilder->CreateLoad(primPtrVal);
  5358. irArgs.push_back(primVal);
  5359. if (loweredTypeCode2 != BfTypeCode_None)
  5360. {
  5361. auto primType2 = mModule->mBfIRBuilder->GetPrimitiveType(loweredTypeCode2);
  5362. auto ptrType2 = mModule->mBfIRBuilder->GetPointerTo(primType2);
  5363. BfIRValue primPtrVal2;
  5364. if (mModule->mBfIRBuilder->GetSize(loweredTypeCode) < mModule->mBfIRBuilder->GetSize(loweredTypeCode2))
  5365. primPtrVal2 = mModule->mBfIRBuilder->CreateInBoundsGEP(mModule->mBfIRBuilder->CreateBitCast(primPtrVal, ptrType2), 1);
  5366. else
  5367. primPtrVal2 = mModule->mBfIRBuilder->CreateBitCast(mModule->mBfIRBuilder->CreateInBoundsGEP(primPtrVal, 1), ptrType2);
  5368. auto primVal2 = mModule->mBfIRBuilder->CreateLoad(primPtrVal2);
  5369. irArgs.push_back(primVal2);
  5370. }
  5371. return;
  5372. }
  5373. }
  5374. }
  5375. else
  5376. argVal = mModule->LoadValue(argVal);
  5377. irArgs.push_back(argVal.mValue);
  5378. }
  5379. }
  5380. void BfExprEvaluator::PushThis(BfAstNode* targetSrc, BfTypedValue argVal, BfMethodInstance* methodInstance, SizedArrayImpl<BfIRValue>& irArgs, bool skipMutCheck)
  5381. {
  5382. MakeBaseConcrete(argVal);
  5383. auto methodDef = methodInstance->mMethodDef;
  5384. if (methodInstance->IsSkipCall())
  5385. return;
  5386. if (!argVal)
  5387. {
  5388. //BF_ASSERT(mFunctionBindResult != NULL);
  5389. return;
  5390. }
  5391. if (methodDef->mIsMutating)
  5392. {
  5393. bool checkMut = false;
  5394. if (argVal.mType->IsGenericParam())
  5395. {
  5396. // For capturing mutability
  5397. if (mResultLocalVar != NULL)
  5398. mResultLocalVar->mWrittenToId = mModule->mCurMethodState->GetRootMethodState()->mCurAccessId++;
  5399. }
  5400. if (((argVal.mType->IsComposite()) || (argVal.mType->IsTypedPrimitive())))
  5401. {
  5402. if ((argVal.IsReadOnly()) || (!argVal.IsAddr()))
  5403. {
  5404. if (!skipMutCheck)
  5405. {
  5406. String err = StrFormat("call mutating method '%s' on", mModule->MethodToString(methodInstance).c_str());
  5407. CheckModifyResult(argVal, targetSrc, err.c_str());
  5408. }
  5409. if (argVal.IsSplat())
  5410. {
  5411. argVal = mModule->AggregateSplat(argVal);
  5412. argVal = mModule->MakeAddressable(argVal);
  5413. }
  5414. }
  5415. else
  5416. {
  5417. if (mResultLocalVar != NULL)
  5418. {
  5419. // When we are capturing, we need to note that we require capturing by reference here
  5420. mResultLocalVar->mWrittenToId = mModule->mCurMethodState->GetRootMethodState()->mCurAccessId++;
  5421. }
  5422. }
  5423. }
  5424. }
  5425. if (argVal.mType->IsValuelessType())
  5426. return;
  5427. auto owner = methodInstance->GetOwner();
  5428. bool allowThisSplatting;
  5429. if (mModule->mIsComptimeModule)
  5430. allowThisSplatting = owner->IsTypedPrimitive() || owner->IsValuelessType();
  5431. else
  5432. allowThisSplatting = methodInstance->AllowsSplatting(-1);
  5433. if ((!allowThisSplatting) || (methodDef->mIsMutating))
  5434. {
  5435. argVal = mModule->MakeAddressable(argVal);
  5436. irArgs.push_back(argVal.mValue);
  5437. return;
  5438. }
  5439. auto thisType = methodInstance->GetThisType();
  5440. PushArg(argVal, irArgs, !methodInstance->AllowsSplatting(-1), thisType->IsPointer());
  5441. }
  5442. void BfExprEvaluator::FinishDeferredEvals(SizedArrayImpl<BfResolvedArg>& argValues)
  5443. {
  5444. for (int argIdx = 0; argIdx < argValues.size(); argIdx++)
  5445. {
  5446. auto& argValue = argValues[argIdx].mTypedValue;
  5447. if ((argValues[argIdx].mArgFlags & (BfArgFlag_DelegateBindAttempt | BfArgFlag_LambdaBindAttempt | BfArgFlag_UnqualifiedDotAttempt | BfArgFlag_DeferredEval)) != 0)
  5448. {
  5449. if (!argValue)
  5450. {
  5451. auto expr = BfNodeDynCast<BfExpression>(argValues[argIdx].mExpression);
  5452. if (expr != NULL)
  5453. argValue = mModule->CreateValueFromExpression(expr);
  5454. }
  5455. }
  5456. }
  5457. }
  5458. void BfExprEvaluator::FinishDeferredEvals(BfResolvedArgs& argValues)
  5459. {
  5460. for (int argIdx = 0; argIdx < (int)argValues.mResolvedArgs.size(); argIdx++)
  5461. {
  5462. auto& argValue = argValues.mResolvedArgs[argIdx].mTypedValue;
  5463. if ((argValues.mResolvedArgs[argIdx].mArgFlags & (BfArgFlag_VariableDeclaration)) != 0)
  5464. {
  5465. auto variableDeclaration = BfNodeDynCast<BfVariableDeclaration>((*argValues.mArguments)[argIdx]);
  5466. if ((variableDeclaration != NULL) && (variableDeclaration->mNameNode != NULL))
  5467. {
  5468. BfLocalVariable* localVar = new BfLocalVariable();
  5469. localVar->mName = variableDeclaration->mNameNode->ToString();
  5470. localVar->mResolvedType = mModule->GetPrimitiveType(BfTypeCode_Var);
  5471. localVar->mAddr = mModule->mBfIRBuilder->GetFakeVal();
  5472. localVar->mReadFromId = 0;
  5473. localVar->mWrittenToId = 0;
  5474. localVar->mAssignedKind = BfLocalVarAssignKind_Unconditional;
  5475. mModule->CheckVariableDef(localVar);
  5476. localVar->Init();
  5477. mModule->AddLocalVariableDef(localVar, true);
  5478. }
  5479. }
  5480. }
  5481. FinishDeferredEvals(argValues.mResolvedArgs);
  5482. }
  5483. void BfExprEvaluator::AddCallDependencies(BfMethodInstance* methodInstance)
  5484. {
  5485. if (methodInstance->mReturnType != NULL)
  5486. mModule->AddDependency(methodInstance->mReturnType, mModule->mCurTypeInstance, BfDependencyMap::DependencyFlag_LocalUsage);
  5487. for (int paramIdx = 0; paramIdx < methodInstance->GetParamCount(); paramIdx++)
  5488. {
  5489. auto paramType = methodInstance->GetParamType(paramIdx);
  5490. mModule->AddDependency(paramType, mModule->mCurTypeInstance, BfDependencyMap::DependencyFlag_LocalUsage);
  5491. }
  5492. if (methodInstance->mMethodInfoEx != NULL)
  5493. {
  5494. for (auto genericArg : methodInstance->mMethodInfoEx->mMethodGenericArguments)
  5495. {
  5496. if (genericArg->IsWrappableType())
  5497. genericArg = mModule->GetWrappedStructType(genericArg);
  5498. if (genericArg != NULL)
  5499. mModule->AddDependency(genericArg, mModule->mCurTypeInstance, BfDependencyMap::DependencyFlag_LocalUsage);
  5500. }
  5501. }
  5502. }
  5503. //TODO: delete argumentsZ
  5504. BfTypedValue BfExprEvaluator::CreateCall(BfAstNode* targetSrc, const BfTypedValue& inTarget, const BfTypedValue& origTarget, BfMethodDef* methodDef, BfModuleMethodInstance moduleMethodInstance, BfCreateFallFlags callFlags, SizedArrayImpl<BfResolvedArg>& argValues, BfTypedValue* argCascade)
  5505. {
  5506. bool bypassVirtual = (callFlags & BfCreateFallFlags_BypassVirtual) != 0;
  5507. bool skipThis = (callFlags & BfCreateFallFlags_SkipThis) != 0;;
  5508. static int sCallIdx = 0;
  5509. if (!mModule->mCompiler->mIsResolveOnly)
  5510. sCallIdx++;
  5511. int callIdx = sCallIdx;
  5512. if (callIdx == 0x000020F9)
  5513. {
  5514. NOP;
  5515. }
  5516. // Temporarily disable so we don't capture calls in params
  5517. SetAndRestoreValue<BfFunctionBindResult*> prevBindResult(mFunctionBindResult, NULL);
  5518. SetAndRestoreValue<bool> prevAllowVariableDeclarations;
  5519. if (mModule->mCurMethodState != NULL)
  5520. prevAllowVariableDeclarations.Init(mModule->mCurMethodState->mCurScope->mAllowVariableDeclarations, false);
  5521. BfMethodInstance* methodInstance = moduleMethodInstance.mMethodInstance;
  5522. SizedArray<BfIRValue, 4> irArgs;
  5523. if ((methodDef->mIsAbstract) && (bypassVirtual))
  5524. {
  5525. mModule->Fail(StrFormat("Abstract base method '%s' cannot be invoked", mModule->MethodToString(methodInstance).c_str()), targetSrc);
  5526. }
  5527. bool isSkipCall = moduleMethodInstance.mMethodInstance->IsSkipCall(bypassVirtual);
  5528. BfType* returnType = methodInstance->mReturnType;
  5529. /*if (returnType->IsSelf())
  5530. {
  5531. returnType = methodInstance->GetOwner();
  5532. BF_ASSERT(returnType->IsInterface());
  5533. }*/
  5534. Array<BfTypedValue> argCascades;
  5535. BfTypedValue target = inTarget;
  5536. if (!skipThis)
  5537. {
  5538. if ((target) && (target.mType->IsFunction()) && (methodInstance->GetOwner() == target.mType))
  5539. {
  5540. CheckResultForReading(target);
  5541. target = mModule->LoadValue(target);
  5542. auto funcType = mModule->mBfIRBuilder->MapMethod(moduleMethodInstance.mMethodInstance);
  5543. auto funcPtrType = mModule->mBfIRBuilder->GetPointerTo(funcType);
  5544. moduleMethodInstance.mFunc = mModule->mBfIRBuilder->CreateIntToPtr(target.mValue, funcPtrType);
  5545. }
  5546. else if (!methodDef->mIsStatic)
  5547. {
  5548. if ((!target) && (prevBindResult.mPrevVal != NULL))
  5549. {
  5550. auto bindResult = prevBindResult.mPrevVal;
  5551. if (bindResult->mBindType != NULL)
  5552. {
  5553. // Allow binding a function to a 'this' type even if no target is specified
  5554. auto delegateInfo = bindResult->mBindType->GetDelegateInfo();
  5555. if (delegateInfo != NULL)
  5556. {
  5557. if (delegateInfo->mHasExplicitThis)
  5558. {
  5559. target = mModule->GetDefaultTypedValue(delegateInfo->mParams[0], false, BfDefaultValueKind_Addr);
  5560. }
  5561. }
  5562. else if (bindResult->mBindType->IsFunction())
  5563. {
  5564. BfMethodInstance* invokeMethodInstance = mModule->GetRawMethodInstanceAtIdx(bindResult->mBindType->ToTypeInstance(), 0, "Invoke");
  5565. if (!invokeMethodInstance->mMethodDef->mIsStatic)
  5566. {
  5567. target = mModule->GetDefaultTypedValue(invokeMethodInstance->GetThisType(), false, BfDefaultValueKind_Addr);
  5568. }
  5569. }
  5570. }
  5571. }
  5572. if (!target)
  5573. {
  5574. FinishDeferredEvals(argValues);
  5575. auto error = mModule->Fail(StrFormat("An instance reference is required to %s the non-static method '%s'",
  5576. (prevBindResult.mPrevVal != NULL) ? "bind" : "invoke",
  5577. mModule->MethodToString(methodInstance).c_str()), targetSrc);
  5578. if ((error != NULL) && (methodInstance->mMethodDef->GetRefNode() != NULL))
  5579. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("See method declaration"), methodInstance->mMethodDef->GetRefNode());
  5580. return mModule->GetDefaultTypedValue(returnType);
  5581. }
  5582. auto prevResult = mResult;
  5583. mResult = target;
  5584. CheckResultForReading(mResult);
  5585. mResult = prevResult;
  5586. if (methodDef->mMethodType != BfMethodType_Ctor)
  5587. {
  5588. bool doAccessCheck = true;
  5589. if (target.IsThis())
  5590. {
  5591. if (!mModule->mCurMethodState->mMayNeedThisAccessCheck)
  5592. doAccessCheck = false;
  5593. }
  5594. if ((mModule->mAttributeState != NULL) && (mModule->mAttributeState->mCustomAttributes != NULL) && (mModule->mAttributeState->mCustomAttributes->Contains(mModule->mCompiler->mDisableObjectAccessChecksAttributeTypeDef)))
  5595. doAccessCheck = false;
  5596. if ((doAccessCheck) && (!isSkipCall) && (prevBindResult.mPrevVal == NULL))
  5597. mModule->EmitObjectAccessCheck(target);
  5598. }
  5599. if (((prevBindResult.mPrevVal == NULL) || (!prevBindResult.mPrevVal->mSkipThis)) &&
  5600. (!isSkipCall))
  5601. {
  5602. bool skipMutCheck = false;
  5603. if ((prevBindResult.mPrevVal != NULL) && (prevBindResult.mPrevVal->mSkipMutCheck))
  5604. {
  5605. // If we are binding a delegate, then we will end up making a copy of the target anyway
  5606. // so we don't need to do a mutability check
  5607. skipMutCheck = true;
  5608. }
  5609. if (methodDef->mMethodType == BfMethodType_Extension)
  5610. PushArg(target, irArgs);
  5611. else
  5612. PushThis(targetSrc, target, moduleMethodInstance.mMethodInstance, irArgs, skipMutCheck);
  5613. }
  5614. }
  5615. else if (methodDef->mMethodType == BfMethodType_Extension)
  5616. {
  5617. // Handled in args
  5618. }
  5619. else
  5620. {
  5621. mModule->CheckStaticAccess(methodInstance->mMethodInstanceGroup->mOwner);
  5622. if (target)
  5623. {
  5624. FinishDeferredEvals(argValues);
  5625. mModule->Fail(StrFormat("Method '%s' cannot be accessed with an instance reference; qualify it with a type name instead",
  5626. mModule->MethodToString(methodInstance).c_str()), targetSrc);
  5627. return mModule->GetDefaultTypedValue(returnType);
  5628. }
  5629. }
  5630. }
  5631. if (isSkipCall)
  5632. {
  5633. FinishDeferredEvals(argValues);
  5634. mModule->EmitEnsureInstructionAt();
  5635. return mModule->GetDefaultTypedValue(returnType);
  5636. }
  5637. int argIdx = 0;
  5638. int paramIdx = 0;
  5639. BfIRValue expandedParamAlloca;
  5640. BfTypedValue expandedParamsArray;
  5641. BfType* expandedParamsElementType = NULL;
  5642. int extendedParamIdx = 0;
  5643. AddCallDependencies(methodInstance);
  5644. auto autoComplete = GetAutoComplete();
  5645. if (autoComplete != NULL)
  5646. {
  5647. // Set to false to make sure we don't capture method match info from 'params' array creation
  5648. autoComplete->mIsCapturingMethodMatchInfo = false;
  5649. }
  5650. BfScopeData* boxScopeData = mDeferScopeAlloc;
  5651. if ((boxScopeData == NULL) && (mModule->mCurMethodState != NULL))
  5652. boxScopeData = mModule->mCurMethodState->mCurScope;
  5653. bool failed = false;
  5654. while (true)
  5655. {
  5656. int argExprIdx = argIdx;
  5657. if (methodDef->mMethodType == BfMethodType_Extension)
  5658. argExprIdx--;
  5659. bool isThis = (paramIdx == -1) || ((methodDef->mHasExplicitThis) && (paramIdx == 0));
  5660. bool isDirectPass = false;
  5661. if (paramIdx >= (int)methodInstance->GetParamCount())
  5662. {
  5663. if (methodInstance->IsVarArgs())
  5664. {
  5665. if (argExprIdx >= (int)argValues.size())
  5666. break;
  5667. BfTypedValue argValue = ResolveArgValue(argValues[argExprIdx], NULL);
  5668. if (argValue)
  5669. {
  5670. auto typeInst = argValue.mType->ToTypeInstance();
  5671. if (argValue.mType == mModule->GetPrimitiveType(BfTypeCode_Float))
  5672. argValue = mModule->Cast(argValues[argExprIdx].mExpression, argValue, mModule->GetPrimitiveType(BfTypeCode_Double));
  5673. if ((typeInst != NULL) && (typeInst->mTypeDef == mModule->mCompiler->mStringTypeDef))
  5674. {
  5675. BfType* charType = mModule->GetPrimitiveType(BfTypeCode_Char8);
  5676. BfType* charPtrType = mModule->CreatePointerType(charType);
  5677. argValue = mModule->Cast(argValues[argExprIdx].mExpression, argValue, charPtrType);
  5678. }
  5679. PushArg(argValue, irArgs, true, false);
  5680. }
  5681. argIdx++;
  5682. continue;
  5683. }
  5684. if (argExprIdx < (int)argValues.size())
  5685. {
  5686. if (mModule->PreFail())
  5687. {
  5688. BfAstNode* errorRef = argValues[argExprIdx].mExpression;
  5689. if (errorRef == NULL)
  5690. errorRef = targetSrc;
  5691. BfError* error;
  5692. if ((argValues[argExprIdx].mArgFlags & BfArgFlag_StringInterpolateArg) != 0)
  5693. {
  5694. int checkIdx = argExprIdx - 1;
  5695. while (checkIdx >= 0)
  5696. {
  5697. if ((argValues[checkIdx].mArgFlags & BfArgFlag_StringInterpolateFormat) != 0)
  5698. {
  5699. errorRef = argValues[checkIdx].mExpression;
  5700. break;
  5701. }
  5702. checkIdx--;
  5703. }
  5704. error = mModule->Fail("Expanded string interpolation generates too many arguments. If string allocation was intended then consider adding a specifier such as 'scope'.", errorRef);
  5705. }
  5706. else if ((prevBindResult.mPrevVal != NULL) && (prevBindResult.mPrevVal->mBindType != NULL))
  5707. 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);
  5708. else
  5709. error = mModule->Fail(StrFormat("Too many arguments, expected %d fewer.", (int)argValues.size() - argExprIdx), errorRef);
  5710. if ((error != NULL) && (methodInstance->mMethodDef->mMethodDeclaration != NULL))
  5711. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("See method declaration"), methodInstance->mMethodDef->GetRefNode());
  5712. }
  5713. failed = true;
  5714. break;
  5715. }
  5716. break;
  5717. }
  5718. // Only create actual params if we're not just trying to bind the function
  5719. if ((prevBindResult.mPrevVal != NULL) && (!prevBindResult.mPrevVal->mWantsArgs))
  5720. break;
  5721. BfType* wantType = NULL;
  5722. bool wantsSplat = false;
  5723. if (expandedParamsElementType != NULL)
  5724. {
  5725. wantType = expandedParamsElementType;
  5726. }
  5727. else
  5728. {
  5729. wantsSplat = methodInstance->GetParamIsSplat(paramIdx) && (!IsComptime());
  5730. if (methodInstance->IsImplicitCapture(paramIdx))
  5731. {
  5732. auto paramType = methodInstance->GetParamType(paramIdx);
  5733. if (mModule->mCurMethodInstance->IsMixin())
  5734. {
  5735. // Don't bother, also- can fail on captures
  5736. }
  5737. else
  5738. {
  5739. // static int captureIdx = 0;
  5740. // captureIdx++;
  5741. // int curCaptureIdx = captureIdx;
  5742. //
  5743. // if (curCaptureIdx == 0x91)
  5744. // {
  5745. // NOP;
  5746. // }
  5747. auto lookupVal = DoImplicitArgCapture(targetSrc, methodInstance, paramIdx, failed, BfImplicitParamKind_General, origTarget);
  5748. if (lookupVal)
  5749. {
  5750. if (wantsSplat)
  5751. {
  5752. SplatArgs(lookupVal, irArgs);
  5753. }
  5754. else if (paramType->IsRef())
  5755. {
  5756. irArgs.push_back(lookupVal.mValue);
  5757. }
  5758. else
  5759. PushArg(lookupVal, irArgs, true);
  5760. }
  5761. }
  5762. paramIdx++;
  5763. continue;
  5764. }
  5765. wantType = methodInstance->GetParamType(paramIdx);
  5766. if (wantType->IsSelf())
  5767. wantType = methodInstance->GetOwner();
  5768. if (wantType->IsVar())
  5769. {
  5770. // Case happens when we can't find the argument type
  5771. failed = true;
  5772. }
  5773. BfParamKind paramKind = methodInstance->GetParamKind(paramIdx);
  5774. if (paramKind == BfParamKind_Params)
  5775. {
  5776. //TODO: Check to see if it's a direct array pass
  5777. if (argIdx < (int)argValues.size())
  5778. {
  5779. auto argValue = argValues[argIdx].mTypedValue;
  5780. if ((argValue.IsParams()) /*&& (mModule->CanCast(argValue, wantType))*/)
  5781. isDirectPass = true;
  5782. }
  5783. if (!isDirectPass)
  5784. {
  5785. int numElements = BF_MAX((int)argValues.size() - argIdx, 0);
  5786. if (methodDef->mMethodType == BfMethodType_Extension)
  5787. numElements++;
  5788. if (IsComptimeEntry())
  5789. {
  5790. if ((wantType->IsArray()) || (wantType->IsInstanceOf(mModule->mCompiler->mSpanTypeDef)))
  5791. {
  5792. auto genericTypeInst = wantType->ToGenericTypeInstance();
  5793. expandedParamsElementType = genericTypeInst->mGenericTypeInfo->mTypeGenericArguments[0];
  5794. auto irSizedArrayType = mModule->mBfIRBuilder->GetSizedArrayType(mModule->mBfIRBuilder->MapType(expandedParamsElementType), numElements);
  5795. Array<BfIRValue> values;
  5796. for (int i = 0; i < numElements; i++)
  5797. values.Add(mModule->mBfIRBuilder->GetFakeVal());
  5798. expandedParamsArray = BfTypedValue(mModule->mBfIRBuilder->CreateConstAgg(irSizedArrayType, values), wantType);
  5799. PushArg(expandedParamsArray, irArgs);
  5800. }
  5801. }
  5802. else if (wantType->IsArray())
  5803. {
  5804. BfArrayType* arrayType = (BfArrayType*)wantType;
  5805. mModule->PopulateType(arrayType, BfPopulateType_DataAndMethods);
  5806. expandedParamsElementType = arrayType->mGenericTypeInfo->mTypeGenericArguments[0];
  5807. int arrayClassSize = arrayType->mInstSize - expandedParamsElementType->mSize;
  5808. expandedParamsArray = BfTypedValue(mModule->AllocFromType(arrayType->GetUnderlyingType(), boxScopeData, BfIRValue(), mModule->GetConstValue(numElements), 1, BfAllocFlags_None),
  5809. arrayType, false);
  5810. BfResolvedArgs resolvedArgs;
  5811. MatchConstructor(targetSrc, NULL, expandedParamsArray, arrayType, resolvedArgs, false, false);
  5812. //TODO: Assert 'length' var is at slot 1
  5813. auto arrayBits = mModule->mBfIRBuilder->CreateBitCast(expandedParamsArray.mValue, mModule->mBfIRBuilder->MapType(arrayType->mBaseType));
  5814. int arrayLengthBitCount = arrayType->GetLengthBitCount();
  5815. if (arrayLengthBitCount == 0)
  5816. {
  5817. mModule->Fail("INTERNAL ERROR: Unable to find array 'length' field", targetSrc);
  5818. return BfTypedValue();
  5819. }
  5820. auto addr = mModule->mBfIRBuilder->CreateInBoundsGEP(arrayBits, 0, 1);
  5821. if (arrayLengthBitCount == 64)
  5822. mModule->mBfIRBuilder->CreateAlignedStore(mModule->GetConstValue64(numElements), addr, 8);
  5823. else
  5824. mModule->mBfIRBuilder->CreateAlignedStore(mModule->GetConstValue32(numElements), addr, 4);
  5825. PushArg(expandedParamsArray, irArgs);
  5826. }
  5827. else if (wantType->IsInstanceOf(mModule->mCompiler->mSpanTypeDef))
  5828. {
  5829. auto genericTypeInst = wantType->ToGenericTypeInstance();
  5830. expandedParamsElementType = genericTypeInst->mGenericTypeInfo->mTypeGenericArguments[0];
  5831. expandedParamsArray = BfTypedValue(mModule->CreateAlloca(wantType), wantType, true);
  5832. expandedParamAlloca = mModule->CreateAlloca(genericTypeInst->mGenericTypeInfo->mTypeGenericArguments[0], true, NULL, mModule->GetConstValue(numElements));
  5833. mModule->mBfIRBuilder->CreateStore(expandedParamAlloca, mModule->mBfIRBuilder->CreateInBoundsGEP(expandedParamsArray.mValue, 0, 1));
  5834. mModule->mBfIRBuilder->CreateStore(mModule->GetConstValue(numElements), mModule->mBfIRBuilder->CreateInBoundsGEP(expandedParamsArray.mValue, 0, 2));
  5835. PushArg(expandedParamsArray, irArgs);
  5836. }
  5837. continue;
  5838. }
  5839. }
  5840. }
  5841. BfAstNode* arg = NULL;
  5842. bool hadMissingArg = false;
  5843. if (argExprIdx == -1)
  5844. arg = targetSrc;
  5845. if (argExprIdx >= 0)
  5846. {
  5847. if (argExprIdx < (int)argValues.size())
  5848. {
  5849. arg = argValues[argExprIdx].mExpression;
  5850. if (((argValues[argExprIdx].mArgFlags & BfArgFlag_StringInterpolateArg) != 0) && (!expandedParamsArray))
  5851. {
  5852. BfAstNode* errorRef = arg;
  5853. int checkIdx = argExprIdx - 1;
  5854. while (checkIdx >= 0)
  5855. {
  5856. if ((argValues[checkIdx].mArgFlags & BfArgFlag_StringInterpolateFormat) != 0)
  5857. {
  5858. errorRef = argValues[checkIdx].mExpression;
  5859. break;
  5860. }
  5861. checkIdx--;
  5862. }
  5863. 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);
  5864. }
  5865. if ((arg == NULL) && (argValues[argExprIdx].mExpression != NULL))
  5866. hadMissingArg = true;
  5867. }
  5868. else
  5869. hadMissingArg = true;
  5870. }
  5871. BfTypedValue argValue;
  5872. if (hadMissingArg)
  5873. {
  5874. if (expandedParamsArray)
  5875. break;
  5876. if ((argIdx >= (int) methodInstance->mDefaultValues.size()) || (!methodInstance->mDefaultValues[argIdx]))
  5877. {
  5878. BfAstNode* refNode = targetSrc;
  5879. if (argValues.size() > 0)
  5880. {
  5881. auto checkExpr = argValues.back().mExpression;
  5882. if (checkExpr != NULL)
  5883. refNode = checkExpr;
  5884. }
  5885. BfAstNode* prevNode = NULL;
  5886. if (targetSrc == NULL)
  5887. {
  5888. // We must be in BfModule::EmitCtorBody
  5889. }
  5890. else if (auto tupleExpr = BfNodeDynCastExact<BfTupleExpression>(targetSrc))
  5891. {
  5892. if (tupleExpr->mCommas.size() > 0)
  5893. prevNode = tupleExpr->mCommas.back();
  5894. else
  5895. prevNode = tupleExpr->mOpenParen;
  5896. if (tupleExpr->mCloseParen != NULL)
  5897. refNode = tupleExpr->mCloseParen;
  5898. }
  5899. else if (mModule->mParentNodeEntry != NULL)
  5900. {
  5901. if (auto objectCreateExpr = BfNodeDynCast<BfObjectCreateExpression>(mModule->mParentNodeEntry->mNode))
  5902. {
  5903. if (objectCreateExpr->mCommas.size() > 0)
  5904. prevNode = objectCreateExpr->mCommas.back();
  5905. else
  5906. prevNode = objectCreateExpr->mOpenToken;
  5907. if (objectCreateExpr->mCloseToken != NULL)
  5908. refNode = objectCreateExpr->mCloseToken;
  5909. if (auto newNode = BfNodeDynCast<BfNewNode>(objectCreateExpr->mNewNode))
  5910. {
  5911. if (newNode->mAllocNode == targetSrc)
  5912. refNode = targetSrc;
  5913. }
  5914. }
  5915. else if (auto invokeExpr = BfNodeDynCast<BfInvocationExpression>(mModule->mParentNodeEntry->mNode))
  5916. {
  5917. if (invokeExpr->mCommas.size() > 0)
  5918. prevNode = invokeExpr->mCommas.back();
  5919. else
  5920. prevNode = invokeExpr->mOpenParen;
  5921. if (invokeExpr->mCloseParen != NULL)
  5922. refNode = invokeExpr->mCloseParen;
  5923. }
  5924. }
  5925. if ((autoComplete != NULL) && (prevNode != NULL))
  5926. autoComplete->CheckEmptyStart(prevNode, wantType);
  5927. BfError* error = NULL;
  5928. if (mModule->mParentNodeEntry != NULL)
  5929. {
  5930. bool showCtorError = false;
  5931. if (auto ctorDeclaration = BfNodeDynCast<BfConstructorDeclaration>(mModule->mParentNodeEntry->mNode))
  5932. {
  5933. if (ctorDeclaration->mInitializer == NULL)
  5934. showCtorError = true;
  5935. }
  5936. if (auto typerDecl = BfNodeDynCast<BfTypeDeclaration>(mModule->mParentNodeEntry->mNode))
  5937. showCtorError = true;
  5938. if (showCtorError)
  5939. {
  5940. if (mModule->PreFail())
  5941. {
  5942. error = mModule->Fail(StrFormat("No parameterless constructor is available for base class. Consider calling base constructor '%s'.",
  5943. mModule->MethodToString(methodInstance).c_str()), refNode);
  5944. }
  5945. auto srcNode = mModule->mCurMethodInstance->mMethodDef->GetRefNode();
  5946. if ((autoComplete != NULL) && (autoComplete->CheckFixit(srcNode)))
  5947. autoComplete->FixitAddConstructor(mModule->mCurTypeInstance);
  5948. }
  5949. }
  5950. if (mModule->PreFail())
  5951. {
  5952. if (error == NULL)
  5953. error = mModule->Fail(StrFormat("Not enough parameters specified, expected %d more.", methodInstance->GetParamCount() - paramIdx), refNode);
  5954. if ((error != NULL) && (methodInstance->mMethodDef->mMethodDeclaration != NULL))
  5955. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("See method declaration"), methodInstance->mMethodDef->GetRefNode());
  5956. }
  5957. failed = true;
  5958. break;
  5959. }
  5960. auto foreignDefaultVal = methodInstance->mDefaultValues[argIdx];
  5961. auto foreignConst = methodInstance->GetOwner()->mConstHolder->GetConstant(foreignDefaultVal.mValue);
  5962. if (foreignConst->mConstType == BfConstType_AggZero)
  5963. {
  5964. // Allow this
  5965. }
  5966. else if (foreignConst->mTypeCode == BfTypeCode_NullPtr)
  5967. {
  5968. if (wantType->IsNullable())
  5969. {
  5970. argValue = mModule->GetDefaultTypedValue(wantType, false, BfDefaultValueKind_Addr);
  5971. }
  5972. }
  5973. else if (foreignConst->mConstType == BfConstType_GlobalVar)
  5974. {
  5975. auto globalVar = (BfGlobalVar*)foreignConst;
  5976. if (globalVar->mName[0] == '#')
  5977. {
  5978. if (strcmp(globalVar->mName, "#CallerLineNum") == 0)
  5979. {
  5980. argValue = BfTypedValue(mModule->GetConstValue(mModule->mCurFilePosition.mCurLine + 1), mModule->GetPrimitiveType(BfTypeCode_Int32));
  5981. }
  5982. else if (strcmp(globalVar->mName, "#CallerFilePath") == 0)
  5983. {
  5984. String filePath = "";
  5985. if (mModule->mCurFilePosition.mFileInstance != NULL)
  5986. filePath = mModule->mCurFilePosition.mFileInstance->mParser->mFileName;
  5987. argValue = BfTypedValue(mModule->GetStringObjectValue(filePath),
  5988. mModule->ResolveTypeDef(mModule->mCompiler->mStringTypeDef));
  5989. }
  5990. else if (strcmp(globalVar->mName, "#CallerFileName") == 0)
  5991. {
  5992. String filePath = "";
  5993. if (mModule->mCurFilePosition.mFileInstance != NULL)
  5994. filePath = mModule->mCurFilePosition.mFileInstance->mParser->mFileName;
  5995. argValue = BfTypedValue(mModule->GetStringObjectValue(GetFileName(filePath)),
  5996. mModule->ResolveTypeDef(mModule->mCompiler->mStringTypeDef));
  5997. }
  5998. else if (strcmp(globalVar->mName, "#CallerFileDir") == 0)
  5999. {
  6000. String filePath = "";
  6001. if (mModule->mCurFilePosition.mFileInstance != NULL)
  6002. filePath = mModule->mCurFilePosition.mFileInstance->mParser->mFileName;
  6003. argValue = BfTypedValue(mModule->GetStringObjectValue(GetFileDir(filePath)),
  6004. mModule->ResolveTypeDef(mModule->mCompiler->mStringTypeDef));
  6005. }
  6006. else if (strcmp(globalVar->mName, "#CallerMemberName") == 0)
  6007. {
  6008. String memberName = "";
  6009. if (mModule->mCurMethodInstance != NULL)
  6010. memberName = mModule->MethodToString(mModule->mCurMethodInstance);
  6011. argValue = BfTypedValue(mModule->GetStringObjectValue(memberName),
  6012. mModule->ResolveTypeDef(mModule->mCompiler->mStringTypeDef));
  6013. }
  6014. else if (strcmp(globalVar->mName, "#CallerProject") == 0)
  6015. {
  6016. String projectName = "";
  6017. if (mModule->mCurMethodInstance != NULL)
  6018. projectName = mModule->mCurMethodInstance->mMethodDef->mDeclaringType->mProject->mName;
  6019. argValue = BfTypedValue(mModule->GetStringObjectValue(projectName),
  6020. mModule->ResolveTypeDef(mModule->mCompiler->mStringTypeDef));
  6021. }
  6022. else if (strcmp(globalVar->mName, "#ProjectName") == 0)
  6023. {
  6024. String projectName = methodInstance->mMethodDef->mDeclaringType->mProject->mName;
  6025. argValue = BfTypedValue(mModule->GetStringObjectValue(projectName),
  6026. mModule->ResolveTypeDef(mModule->mCompiler->mStringTypeDef));
  6027. }
  6028. else
  6029. {
  6030. argValue = mModule->GetCompilerFieldValue(globalVar->mName);
  6031. }
  6032. }
  6033. }
  6034. else if (foreignConst->mConstType == BfConstType_GEP32_2)
  6035. {
  6036. auto constGep32_2 = (BfConstantGEP32_2*)foreignConst;
  6037. auto gepTarget = methodInstance->GetOwner()->mConstHolder->GetConstantById(constGep32_2->mTarget);
  6038. if (gepTarget->mConstType == BfConstType_GlobalVar)
  6039. {
  6040. auto globalVar = (BfGlobalVar*)gepTarget;
  6041. if (globalVar->mName[0] == '#')
  6042. {
  6043. if (strcmp(globalVar->mName, "#CallerExpression") == 0)
  6044. {
  6045. int exprIdx = constGep32_2->mIdx1;
  6046. if ((exprIdx >= 0) && (exprIdx < (int)argValues.size()))
  6047. {
  6048. auto expr = argValues[exprIdx].mExpression;
  6049. if (expr != NULL)
  6050. {
  6051. argValue = BfTypedValue(mModule->GetStringObjectValue(expr->ToString()),
  6052. mModule->ResolveTypeDef(mModule->mCompiler->mStringTypeDef));
  6053. }
  6054. }
  6055. else
  6056. {
  6057. mModule->Fail("CallerExpression index out of bounds", targetSrc);
  6058. argValue = BfTypedValue(mModule->GetStringObjectValue(""),
  6059. mModule->ResolveTypeDef(mModule->mCompiler->mStringTypeDef));
  6060. }
  6061. }
  6062. }
  6063. }
  6064. }
  6065. if (!argValue)
  6066. {
  6067. argValue = mModule->GetTypedValueFromConstant(foreignConst, methodInstance->GetOwner()->mConstHolder, foreignDefaultVal.mType);
  6068. if (!argValue)
  6069. mModule->Fail("Default parameter value failed", targetSrc);
  6070. mModule->mBfIRBuilder->PopulateType(foreignDefaultVal.mType);
  6071. }
  6072. }
  6073. else
  6074. {
  6075. if (argExprIdx == -1)
  6076. argValue = target;
  6077. else
  6078. argValue = argValues[argExprIdx].mTypedValue;
  6079. if ((argValue.IsParams()) && (!isDirectPass))
  6080. {
  6081. BfAstNode* refNode = arg;
  6082. if (auto unaryOperatorExpr = BfNodeDynCast<BfUnaryOperatorExpression>(refNode))
  6083. refNode = unaryOperatorExpr->mOpToken;
  6084. mModule->Warn(0, "Unused 'params' expression", refNode);
  6085. }
  6086. if (wantType->IsMethodRef())
  6087. {
  6088. auto expr = argValues[argExprIdx].mExpression;
  6089. if (expr != NULL)
  6090. SetMethodElementType(expr);
  6091. if (!argValue)
  6092. argValue = mModule->CreateValueFromExpression(BfNodeDynCast<BfExpression>(arg), wantType, (BfEvalExprFlags)((mBfEvalExprFlags & BfEvalExprFlags_InheritFlags) | BfEvalExprFlags_NoCast));
  6093. // Add any implicit captures now
  6094. auto methodRefType = (BfMethodRefType*)wantType;
  6095. BfMethodInstance* useMethodInstance = methodRefType->mMethodRef;
  6096. for (int dataIdx = 0; dataIdx < methodRefType->GetCaptureDataCount(); dataIdx++)
  6097. {
  6098. int paramIdx = methodRefType->GetParamIdxFromDataIdx(dataIdx);
  6099. auto lookupVal = DoImplicitArgCapture(arg, useMethodInstance, paramIdx, failed, BfImplicitParamKind_General, argValue);
  6100. if (lookupVal)
  6101. {
  6102. if (methodRefType->WantsDataPassedAsSplat(dataIdx))
  6103. SplatArgs(lookupVal, irArgs);
  6104. else
  6105. irArgs.push_back(lookupVal.mValue);
  6106. }
  6107. }
  6108. paramIdx++;
  6109. argIdx++;
  6110. continue;
  6111. }
  6112. else if (argExprIdx >= 0)
  6113. {
  6114. BfParamKind paramKind = BfParamKind_Normal;
  6115. BfIdentifierNode* paramNameNode = NULL;
  6116. if (paramIdx < methodInstance->GetParamCount())
  6117. {
  6118. paramKind = methodInstance->GetParamKind(paramIdx);
  6119. paramNameNode = methodInstance->GetParamNameNode(paramIdx);
  6120. }
  6121. argValues[argExprIdx].mExpectedType = wantType;
  6122. argValue = ResolveArgValue(argValues[argExprIdx], wantType, NULL, paramKind, paramNameNode);
  6123. }
  6124. }
  6125. if (!argValue)
  6126. {
  6127. failed = true;
  6128. }
  6129. if (argValue)
  6130. {
  6131. if ((isThis) && (argValue.mType->IsRef()))
  6132. {
  6133. // Convert a 'ref this' to a 'this*'
  6134. argValue.mType = mModule->CreatePointerType(argValue.mType->GetUnderlyingType());
  6135. }
  6136. BfAstNode* refNode = arg;
  6137. if (refNode == NULL)
  6138. refNode = targetSrc;
  6139. if ((wantType->IsRef()) && (!argValue.mType->IsRef()) &&
  6140. (((callFlags & BfCreateFallFlags_AllowImplicitRef) != 0) || (wantType->IsIn())))
  6141. argValue = mModule->ToRef(argValue, (BfRefType*)wantType);
  6142. if (mModule->mCurMethodState != NULL)
  6143. {
  6144. SetAndRestoreValue<BfScopeData*> prevScopeData(mModule->mCurMethodState->mOverrideScope, boxScopeData);
  6145. argValue = mModule->Cast(refNode, argValue, wantType);
  6146. }
  6147. else
  6148. argValue = mModule->Cast(refNode, argValue, wantType);
  6149. if (!argValue)
  6150. {
  6151. if ((argExprIdx < (int)argValues.size()) && ((argValues[argExprIdx].mArgFlags & BfArgFlag_StringInterpolateArg) != 0))
  6152. {
  6153. BfAstNode* errorRef = NULL;
  6154. int checkIdx = argExprIdx - 1;
  6155. while (checkIdx >= 0)
  6156. {
  6157. if ((argValues[checkIdx].mArgFlags & BfArgFlag_StringInterpolateFormat) != 0)
  6158. {
  6159. errorRef = argValues[checkIdx].mExpression;
  6160. break;
  6161. }
  6162. checkIdx--;
  6163. }
  6164. if (errorRef != NULL)
  6165. mModule->Warn(0, "If string allocation was intended then consider adding a specifier such as 'scope'.", errorRef);
  6166. }
  6167. failed = true;
  6168. }
  6169. else if ((wantType->IsComposite()) && (!expandedParamsArray))
  6170. {
  6171. if (methodInstance->mIsIntrinsic)
  6172. {
  6173. // Intrinsics can handle structs either by value or address
  6174. }
  6175. else
  6176. {
  6177. // We need to make a temp and get the addr of that
  6178. if ((!wantsSplat) && (!argValue.IsValuelessType()) && (!argValue.IsAddr()) && (!IsComptimeEntry()))
  6179. {
  6180. argValue = mModule->MakeAddressable(argValue);
  6181. }
  6182. }
  6183. }
  6184. else if (!wantType->IsRef())
  6185. argValue = mModule->LoadValue(argValue);
  6186. }
  6187. if ((argExprIdx != -1) && (argExprIdx < (int)argValues.size()) && ((argValues[argExprIdx].mArgFlags & BfArgFlag_Cascade) != 0))
  6188. {
  6189. mUsedAsStatement = true;
  6190. argCascades.Add(argValue);
  6191. }
  6192. if (expandedParamsArray)
  6193. {
  6194. if (argValue)
  6195. {
  6196. if (IsComptimeEntry())
  6197. {
  6198. auto constant = mModule->mBfIRBuilder->GetConstant(expandedParamsArray.mValue);
  6199. BF_ASSERT(constant->mConstType == BfConstType_Agg);
  6200. auto constAgg = (BfConstantAgg*)constant;
  6201. constAgg->mValues[extendedParamIdx] = argValue.mValue;
  6202. }
  6203. else if (expandedParamAlloca)
  6204. {
  6205. argValue = mModule->LoadValue(argValue);
  6206. auto addr = mModule->mBfIRBuilder->CreateInBoundsGEP(expandedParamAlloca, extendedParamIdx);
  6207. auto storeInst = mModule->mBfIRBuilder->CreateAlignedStore(argValue.mValue, addr, argValue.mType->mAlign);
  6208. }
  6209. else
  6210. {
  6211. auto firstElem = mModule->GetFieldByName(expandedParamsArray.mType->ToTypeInstance(), "mFirstElement");
  6212. if (firstElem != NULL)
  6213. {
  6214. argValue = mModule->LoadValue(argValue);
  6215. auto firstAddr = mModule->mBfIRBuilder->CreateInBoundsGEP(expandedParamsArray.mValue, 0, firstElem->mDataIdx);
  6216. auto indexedAddr = mModule->CreateIndexedValue(argValue.mType, firstAddr, extendedParamIdx);
  6217. if (argValue.IsSplat())
  6218. mModule->AggregateSplatIntoAddr(argValue, indexedAddr);
  6219. else
  6220. mModule->mBfIRBuilder->CreateAlignedStore(argValue.mValue, indexedAddr, argValue.mType->mAlign);
  6221. }
  6222. }
  6223. }
  6224. extendedParamIdx++;
  6225. }
  6226. else
  6227. {
  6228. if ((paramIdx == 0) && (methodInstance->GetParamName(paramIdx) == "this") && (wantType->IsPointer()))
  6229. {
  6230. auto underlyingType = wantType->GetUnderlyingType();
  6231. mModule->PopulateType(underlyingType, BfPopulateType_Data);
  6232. if ((underlyingType->IsValuelessType()) && (!underlyingType->IsVoid()))
  6233. {
  6234. // We don't actually pass a 'this' pointer for mut methods on valueless structs
  6235. argIdx++;
  6236. paramIdx++;
  6237. continue;
  6238. }
  6239. }
  6240. if (argValue)
  6241. {
  6242. if (isThis)
  6243. PushThis(targetSrc, argValue, methodInstance, irArgs);
  6244. else if (wantsSplat)
  6245. SplatArgs(argValue, irArgs);
  6246. else
  6247. PushArg(argValue, irArgs, true, false, methodInstance->mIsIntrinsic);
  6248. }
  6249. paramIdx++;
  6250. }
  6251. argIdx++;
  6252. }
  6253. if (failed)
  6254. {
  6255. // Process the other unused arguments
  6256. while (argIdx < argValues.size())
  6257. {
  6258. mModule->AssertErrorState();
  6259. auto argValue = argValues[argIdx].mTypedValue;
  6260. if ((argValues[argIdx].mArgFlags & (BfArgFlag_DelegateBindAttempt | BfArgFlag_LambdaBindAttempt | BfArgFlag_UnqualifiedDotAttempt | BfArgFlag_DeferredEval | BfArgFlag_VariableDeclaration | BfArgFlag_UninitializedExpr)) != 0)
  6261. {
  6262. if (!argValue)
  6263. {
  6264. auto expr = BfNodeDynCast<BfExpression>(argValues[argIdx].mExpression);
  6265. if (expr != NULL)
  6266. argValue = mModule->CreateValueFromExpression(expr);
  6267. }
  6268. }
  6269. argIdx++;
  6270. }
  6271. return mModule->GetDefaultTypedValue(returnType, false, BfDefaultValueKind_Addr);
  6272. }
  6273. prevBindResult.Restore();
  6274. if (!methodDef->mIsStatic)
  6275. {
  6276. bool ignoreVirtualError = (mModule->mBfIRBuilder->mIgnoreWrites) && (mModule->mCurMethodInstance != NULL) && (mModule->mCurMethodInstance->mIsForeignMethodDef);
  6277. if ((methodInstance->GetOwner()->IsInterface()) && (!target.mType->IsGenericParam()) && (!target.mType->IsConcreteInterfaceType()) &&
  6278. (!mModule->mCurTypeInstance->IsInterface()) && (!ignoreVirtualError))
  6279. {
  6280. if (methodInstance->mVirtualTableIdx == -1)
  6281. {
  6282. mModule->PopulateType(methodInstance->GetOwner(), BfPopulateType_DataAndMethods);
  6283. }
  6284. if (methodInstance->mVirtualTableIdx == -1)
  6285. {
  6286. if (methodInstance->mMethodDef->mIsConcrete)
  6287. {
  6288. 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);
  6289. }
  6290. else if (methodInstance->HasSelf())
  6291. {
  6292. 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);
  6293. }
  6294. else
  6295. {
  6296. if ((bypassVirtual) && (mModule->mCurTypeInstance->IsInterface()))
  6297. {
  6298. // Allow a base call to be defined
  6299. }
  6300. else if ((methodInstance->IsSpecializedGenericMethod()) && (origTarget) && (!origTarget.mType->IsInterface()))
  6301. {
  6302. if (!mModule->mBfIRBuilder->mIgnoreWrites)
  6303. mModule->AssertErrorState();
  6304. }
  6305. else if ((!mModule->mCurMethodInstance->mIsUnspecialized))
  6306. {
  6307. // Compiler error?
  6308. String errorString = "Unable to dynamically dispatch '%s'";
  6309. if (methodInstance->IsSpecializedGenericMethod())
  6310. errorString = "Unable to dynamically dispatch '%s' because generic methods can only be directly dispatched";
  6311. if (methodInstance->mReturnType->IsConcreteInterfaceType())
  6312. errorString = "Unable to dynamically dispatch '%s' because the concrete return type is unknown";
  6313. mModule->Fail(StrFormat(errorString.c_str(), mModule->MethodToString(methodInstance).c_str()), targetSrc);
  6314. }
  6315. //BF_ASSERT(mModule->mCurMethodInstance->mIsUnspecialized);
  6316. }
  6317. if (mFunctionBindResult != NULL)
  6318. {
  6319. mFunctionBindResult->mMethodInstance = methodInstance;
  6320. mFunctionBindResult->mTarget = target;
  6321. mFunctionBindResult->mFunc = moduleMethodInstance.mFunc;
  6322. for (auto arg : irArgs)
  6323. mFunctionBindResult->mIRArgs.push_back(arg);
  6324. }
  6325. return mModule->GetDefaultTypedValue(returnType);
  6326. }
  6327. }
  6328. }
  6329. else
  6330. {
  6331. //BF_ASSERT(!methodInstance->GetOwner()->IsInterface());
  6332. }
  6333. if (target.mType != NULL)
  6334. {
  6335. // When we call a method from a static ctor, that method could access static fields so we need to make sure
  6336. // the type has been initialized
  6337. auto targetTypeInst = target.mType->ToTypeInstance();
  6338. if (targetTypeInst != NULL)
  6339. mModule->CheckStaticAccess(targetTypeInst);
  6340. }
  6341. if (methodInstance->mReturnType == NULL)
  6342. {
  6343. mModule->AssertErrorState();
  6344. mModule->Fail("Circular reference in method instance", targetSrc);
  6345. return BfTypedValue();
  6346. }
  6347. auto func = moduleMethodInstance.mFunc;
  6348. BfTypedValue callResult = CreateCall(targetSrc, methodInstance, func, bypassVirtual, irArgs);
  6349. if (argCascades.mSize == 1)
  6350. {
  6351. if (argCascade == NULL)
  6352. return argCascades[0];
  6353. *argCascade = argCascades[0];
  6354. }
  6355. if (argCascades.mSize > 1)
  6356. {
  6357. if (argCascade == NULL)
  6358. return mModule->CreateTuple(argCascades, {});
  6359. *argCascade = mModule->CreateTuple(argCascades, {});
  6360. }
  6361. return callResult;
  6362. }
  6363. BfTypedValue BfExprEvaluator::MatchConstructor(BfAstNode* targetSrc, BfMethodBoundExpression* methodBoundExpr, BfTypedValue target, BfTypeInstance* targetType, BfResolvedArgs& argValues, bool callCtorBodyOnly, bool allowAppendAlloc, BfTypedValue* appendIndexValue)
  6364. {
  6365. // Temporarily disable so we don't capture calls in params
  6366. SetAndRestoreValue<BfFunctionBindResult*> prevBindResult(mFunctionBindResult, NULL);
  6367. static int sCtorCount = 0;
  6368. sCtorCount++;
  6369. BfMethodMatcher methodMatcher(targetSrc, mModule, "", argValues.mResolvedArgs, NULL);
  6370. methodMatcher.mBfEvalExprFlags = mBfEvalExprFlags;
  6371. BfTypeVector typeGenericArguments;
  6372. auto curTypeInst = targetType;
  6373. auto curTypeDef = targetType->mTypeDef;
  6374. BfProtectionCheckFlags protectionCheckFlags = BfProtectionCheckFlag_None;
  6375. auto activeTypeDef = mModule->GetActiveTypeDef();
  6376. auto visibleProjectSet = mModule->GetVisibleProjectSet();
  6377. bool isFailurePass = false;
  6378. for (int pass = 0; pass < 2; pass++)
  6379. {
  6380. isFailurePass = pass == 1;
  6381. curTypeDef->PopulateMemberSets();
  6382. BfMethodDef* nextMethodDef = NULL;
  6383. BfMemberSetEntry* entry;
  6384. if (curTypeDef->mMethodSet.TryGetWith(String("__BfCtor"), &entry))
  6385. nextMethodDef = (BfMethodDef*)entry->mMemberDef;
  6386. while (nextMethodDef != NULL)
  6387. {
  6388. auto checkMethod = nextMethodDef;
  6389. nextMethodDef = nextMethodDef->mNextWithSameName;
  6390. if ((isFailurePass) && (checkMethod->mMethodDeclaration == NULL))
  6391. continue; // Don't match private default ctor if there's a user-defined one
  6392. if (checkMethod->mIsStatic)
  6393. continue;
  6394. if ((checkMethod->mDeclaringType->IsExtension()) && (mModule->mAttributeState != NULL) && (mModule->mAttributeState->mCustomAttributes != NULL) &&
  6395. (mModule->mAttributeState->mCustomAttributes->Contains(mModule->mCompiler->mNoExtensionAttributeTypeDef)))
  6396. {
  6397. mModule->mAttributeState->mUsed = true;
  6398. continue;
  6399. }
  6400. if (!mModule->IsInSpecializedSection())
  6401. {
  6402. if ((!curTypeInst->IsTypeMemberIncluded(checkMethod->mDeclaringType, activeTypeDef, mModule)) ||
  6403. (!curTypeInst->IsTypeMemberAccessible(checkMethod->mDeclaringType, visibleProjectSet)))
  6404. continue;
  6405. }
  6406. auto checkProt = checkMethod->mProtection;
  6407. if (!isFailurePass)
  6408. {
  6409. if (callCtorBodyOnly)
  6410. {
  6411. if (curTypeDef != mModule->mCurTypeInstance->mTypeDef)
  6412. {
  6413. // We're calling the base class's ctor from a derived class
  6414. if (checkProt <= BfProtection_Private)
  6415. continue;
  6416. }
  6417. }
  6418. else
  6419. {
  6420. if ((checkProt == BfProtection_Protected) || (checkProt == BfProtection_ProtectedInternal)) // Treat protected constructors as private
  6421. checkProt = BfProtection_Private;
  6422. if (!mModule->CheckProtection(protectionCheckFlags, curTypeInst, checkMethod->mDeclaringType->mProject, checkProt, curTypeInst))
  6423. continue;
  6424. }
  6425. }
  6426. methodMatcher.CheckMethod(NULL, curTypeInst, checkMethod, isFailurePass);
  6427. }
  6428. if ((methodMatcher.mBestMethodDef != NULL) || (methodMatcher.mBackupMethodDef != NULL))
  6429. break;
  6430. }
  6431. if (methodMatcher.mBestMethodDef == NULL)
  6432. methodMatcher.mBestMethodDef = methodMatcher.mBackupMethodDef;
  6433. if (methodMatcher.mBestMethodDef == NULL)
  6434. {
  6435. mModule->Fail("No constructor available", targetSrc);
  6436. return BfTypedValue();
  6437. }
  6438. auto methodDef = methodMatcher.mBestMethodDef;
  6439. if (mModule->mCompiler->mResolvePassData != NULL)
  6440. mModule->mCompiler->mResolvePassData->HandleMethodReference(targetSrc, curTypeInst->mTypeDef, methodDef);
  6441. // There should always be a constructor
  6442. BF_ASSERT(methodMatcher.mBestMethodDef != NULL);
  6443. auto moduleMethodInstance = mModule->GetMethodInstance(methodMatcher.mBestMethodTypeInstance, methodMatcher.mBestMethodDef, methodMatcher.mBestMethodGenericArguments);
  6444. if (!mModule->CheckUseMethodInstance(moduleMethodInstance.mMethodInstance, targetSrc))
  6445. {
  6446. return BfTypedValue();
  6447. }
  6448. BfAutoComplete* autoComplete = GetAutoComplete();
  6449. if (autoComplete != NULL)
  6450. {
  6451. BfTypeInstance* resolvedTypeInstance = target.mType->ToTypeInstance();
  6452. auto ctorDecl = BfNodeDynCast<BfConstructorDeclaration>(methodDef->mMethodDeclaration);
  6453. if ((autoComplete->mIsGetDefinition) && (autoComplete->IsAutocompleteNode(targetSrc)) && (!BfNodeIsA<BfDelegateBindExpression>(targetSrc)))
  6454. {
  6455. if ((autoComplete->mDefMethod == NULL) && (autoComplete->mDefField == NULL) &&
  6456. (autoComplete->mDefProp == NULL)
  6457. && ((autoComplete->mDefType == NULL) || (autoComplete->mDefType == resolvedTypeInstance->mTypeDef)))
  6458. {
  6459. // Do we need to do this mDefType setting? If we do, then make sure we only get the element type of generics and such
  6460. //autoComplete->mDefType = resolvedTypeInstance->mTypeDef;
  6461. if (ctorDecl != NULL)
  6462. autoComplete->SetDefinitionLocation(ctorDecl->mThisToken, true);
  6463. else if (resolvedTypeInstance->mTypeDef->mTypeDeclaration != NULL)
  6464. autoComplete->SetDefinitionLocation(resolvedTypeInstance->mTypeDef->mTypeDeclaration->mNameNode, true);
  6465. }
  6466. }
  6467. else if ((autoComplete->mResolveType == BfResolveType_GetResultString) && (autoComplete->IsAutocompleteNode(targetSrc)) &&
  6468. (moduleMethodInstance.mMethodInstance != NULL))
  6469. {
  6470. autoComplete->mResultString = ":";
  6471. autoComplete->mResultString += mModule->MethodToString(moduleMethodInstance.mMethodInstance);
  6472. }
  6473. }
  6474. BfConstructorDeclaration* ctorDecl = (BfConstructorDeclaration*)methodMatcher.mBestMethodDef->mMethodDeclaration;
  6475. if ((methodMatcher.mBestMethodDef->mHasAppend) && (targetType->IsObject()))
  6476. {
  6477. if (!allowAppendAlloc)
  6478. {
  6479. if (mModule->mCurMethodInstance->mMethodDef->mMethodDeclaration == NULL)
  6480. mModule->Fail("Constructors with append allocations cannot be called from a default constructor. Considering adding an explicit default constructor with the [AllowAppend] specifier.", targetSrc);
  6481. else
  6482. mModule->Fail("Constructors with append allocations cannot be called from a constructor without [AllowAppend] specified.", targetSrc);
  6483. }
  6484. else
  6485. {
  6486. BfResolvedArg resolvedArg;
  6487. if (appendIndexValue != NULL)
  6488. {
  6489. resolvedArg.mTypedValue = *appendIndexValue;
  6490. }
  6491. else
  6492. {
  6493. auto intPtrType = mModule->GetPrimitiveType(BfTypeCode_IntPtr);
  6494. auto intPtrRefType = mModule->CreateRefType(intPtrType);
  6495. if (target.mValue.IsFake())
  6496. {
  6497. resolvedArg.mTypedValue = BfTypedValue(mModule->mBfIRBuilder->GetFakeVal(), intPtrRefType);
  6498. }
  6499. else
  6500. {
  6501. BFMODULE_FATAL(mModule, "Bad");
  6502. }
  6503. }
  6504. methodMatcher.mArguments.Insert(0, resolvedArg);
  6505. }
  6506. }
  6507. if (isFailurePass)
  6508. mModule->Fail(StrFormat("'%s' is inaccessible due to its protection level", mModule->MethodToString(moduleMethodInstance.mMethodInstance).c_str()), targetSrc);
  6509. prevBindResult.Restore();
  6510. return CreateCall(methodMatcher.mTargetSrc, target, BfTypedValue(), methodMatcher.mBestMethodDef, moduleMethodInstance, BfCreateFallFlags_None, methodMatcher.mArguments);
  6511. }
  6512. static int sInvocationIdx = 0;
  6513. BfTypedValue BfExprEvaluator::ResolveArgValue(BfResolvedArg& resolvedArg, BfType* wantType, BfTypedValue* receivingValue, BfParamKind paramKind, BfIdentifierNode* paramNameNode)
  6514. {
  6515. BfTypedValue argValue = resolvedArg.mTypedValue;
  6516. if ((resolvedArg.mArgFlags & (BfArgFlag_DelegateBindAttempt | BfArgFlag_LambdaBindAttempt | BfArgFlag_UnqualifiedDotAttempt | BfArgFlag_DeferredEval)) != 0)
  6517. {
  6518. if ((!argValue) || (argValue.mValue.IsFake()) || (resolvedArg.mWantsRecalc))
  6519. {
  6520. resolvedArg.mWantsRecalc = false;
  6521. auto expr = BfNodeDynCast<BfExpression>(resolvedArg.mExpression);
  6522. if (expr != NULL)
  6523. {
  6524. BfExprEvaluator exprEvaluator(mModule);
  6525. exprEvaluator.mReceivingValue = receivingValue;
  6526. BfEvalExprFlags flags = (BfEvalExprFlags)((mBfEvalExprFlags & BfEvalExprFlags_InheritFlags) | BfEvalExprFlags_NoCast);
  6527. if ((paramKind == BfParamKind_Params) || (paramKind == BfParamKind_DelegateParam))
  6528. flags = (BfEvalExprFlags)(flags | BfEvalExprFlags_AllowParamsExpr);
  6529. argValue = mModule->CreateValueFromExpression(exprEvaluator, expr, wantType, flags);
  6530. if ((argValue) && (argValue.mType != wantType) && (wantType != NULL))
  6531. {
  6532. if ((mDeferScopeAlloc != NULL) && (wantType == mModule->mContext->mBfObjectType))
  6533. {
  6534. BfAllocTarget allocTarget(mDeferScopeAlloc);
  6535. argValue = mModule->BoxValue(expr, argValue, wantType, allocTarget);
  6536. }
  6537. else
  6538. argValue = mModule->Cast(expr, argValue, wantType);
  6539. }
  6540. }
  6541. }
  6542. }
  6543. else if ((resolvedArg.mArgFlags & (BfArgFlag_DeferredValue)) != 0)
  6544. {
  6545. // We should have already had an error on the first call
  6546. SetAndRestoreValue<bool> prevIgnoreErrors(mModule->mIgnoreErrors, mModule->mHadBuildError);
  6547. auto expr = BfNodeDynCast<BfExpression>(resolvedArg.mExpression);
  6548. BF_ASSERT(expr != NULL);
  6549. argValue = mModule->CreateValueFromExpression(expr, wantType, (BfEvalExprFlags)((mBfEvalExprFlags & BfEvalExprFlags_InheritFlags) | BfEvalExprFlags_NoCast | BfEvalExprFlags_AllowRefExpr | BfEvalExprFlags_AllowOutExpr));
  6550. if ((argValue) && (wantType != NULL))
  6551. argValue = mModule->Cast(expr, argValue, wantType);
  6552. }
  6553. else if ((resolvedArg.mArgFlags & (BfArgFlag_UntypedDefault)) != 0)
  6554. {
  6555. argValue = mModule->GetDefaultTypedValue(wantType);
  6556. }
  6557. else if ((resolvedArg.mArgFlags & (BfArgFlag_VariableDeclaration | BfArgFlag_UninitializedExpr)) != 0)
  6558. {
  6559. auto variableDeclaration = BfNodeDynCast<BfVariableDeclaration>(resolvedArg.mExpression);
  6560. auto variableType = wantType;
  6561. bool isLet = (variableDeclaration != NULL) && (variableDeclaration->mTypeRef->IsExact<BfLetTypeReference>());
  6562. bool isVar = (variableDeclaration == NULL) || (variableDeclaration->mTypeRef->IsExact<BfVarTypeReference>());
  6563. if (mModule->mCurMethodState->mPendingNullConditional != NULL)
  6564. {
  6565. mModule->Fail("Variables cannot be declared in method arguments inside null conditional expressions", variableDeclaration);
  6566. }
  6567. if ((!isLet) && (!isVar))
  6568. {
  6569. if (variableType->IsVar())
  6570. {
  6571. auto resolvedType = mModule->ResolveTypeRef(variableDeclaration->mTypeRef);
  6572. if (resolvedType != NULL)
  6573. variableType = resolvedType;
  6574. }
  6575. else
  6576. {
  6577. mModule->Fail("Only 'ref' or 'var' variables can be declared in method arguments", variableDeclaration);
  6578. auto autoComplete = GetAutoComplete();
  6579. if (autoComplete != NULL)
  6580. autoComplete->CheckTypeRef(variableDeclaration->mTypeRef, true, true);
  6581. }
  6582. }
  6583. else
  6584. {
  6585. if (variableType->IsVar())
  6586. {
  6587. mModule->Fail("Variable type required for 'var' parameter types", variableDeclaration);
  6588. }
  6589. }
  6590. if (wantType->IsRef())
  6591. {
  6592. auto refType = (BfRefType*)wantType;
  6593. variableType = refType->mElementType;
  6594. }
  6595. if ((variableDeclaration != NULL) && (variableDeclaration->mInitializer != NULL))
  6596. {
  6597. mModule->Fail("Initializers cannot be used when declaring variables for 'out' parameters", variableDeclaration->mEqualsNode);
  6598. mModule->CreateValueFromExpression(variableDeclaration->mInitializer, variableType, BfEvalExprFlags_NoCast);
  6599. }
  6600. BfLocalVariable* localVar = new BfLocalVariable();
  6601. if ((variableDeclaration != NULL) && (variableDeclaration->mNameNode != NULL))
  6602. {
  6603. localVar->mName = variableDeclaration->mNameNode->ToString();
  6604. localVar->mNameNode = BfNodeDynCast<BfIdentifierNode>(variableDeclaration->mNameNode);
  6605. }
  6606. else
  6607. {
  6608. if (paramNameNode != NULL)
  6609. {
  6610. localVar->mName = "__";
  6611. paramNameNode->ToString(localVar->mName);
  6612. localVar->mName += "_";
  6613. localVar->mName += StrFormat("%d", mModule->mCurMethodState->GetRootMethodState()->mCurLocalVarId);
  6614. }
  6615. else
  6616. localVar->mName = "__" + StrFormat("%d", mModule->mCurMethodState->GetRootMethodState()->mCurLocalVarId);
  6617. }
  6618. localVar->mResolvedType = variableType;
  6619. if (!variableType->IsValuelessType())
  6620. localVar->mAddr = mModule->CreateAlloca(variableType);
  6621. localVar->mIsReadOnly = isLet;
  6622. localVar->mReadFromId = 0;
  6623. localVar->mWrittenToId = 0;
  6624. localVar->mAssignedKind = BfLocalVarAssignKind_Unconditional;
  6625. mModule->CheckVariableDef(localVar);
  6626. localVar->Init();
  6627. mModule->AddLocalVariableDef(localVar, true);
  6628. CheckVariableDeclaration(resolvedArg.mExpression, false, false, false);
  6629. argValue = BfTypedValue(localVar->mAddr, mModule->CreateRefType(variableType, BfRefType::RefKind_Out));
  6630. auto curScope = mModule->mCurMethodState->mCurScope;
  6631. if (curScope->mScopeKind == BfScopeKind_StatementTarget)
  6632. {
  6633. // Move this variable into the parent scope
  6634. curScope->mLocalVarStart = (int)mModule->mCurMethodState->mLocals.size();
  6635. }
  6636. }
  6637. return argValue;
  6638. }
  6639. BfTypedValue BfExprEvaluator::CheckEnumCreation(BfAstNode* targetSrc, BfTypeInstance* enumType, const StringImpl& caseName, BfResolvedArgs& argValues)
  6640. {
  6641. auto activeTypeDef = mModule->GetActiveTypeDef();
  6642. mModule->mBfIRBuilder->PopulateType(enumType);
  6643. auto resolvePassData = mModule->mCompiler->mResolvePassData;
  6644. // if (resolvePassData != NULL)
  6645. // {
  6646. // if (mModule->mParentNodeEntry != NULL)
  6647. // {
  6648. // if (auto invocationExpr = BfNodeDynCast<BfInvocationExpression>(mModule->mParentNodeEntry->mNode))
  6649. // {
  6650. // if (auto memberRefExpr = BfNodeDynCast<BfMemberReferenceExpression>(invocationExpr->mTarget))
  6651. // {
  6652. // BfAstNode* dotNode = memberRefExpr->mDotToken;
  6653. // BfAstNode* nameNode = targetSrc;
  6654. // String filter;
  6655. // auto autoComplete = resolvePassData->mAutoComplete;
  6656. // if ((autoComplete != NULL) && (autoComplete->InitAutocomplete(dotNode, nameNode, filter)))
  6657. // autoComplete->AddEnumTypeMembers(enumType, caseName, false, enumType == mModule->mCurTypeInstance);
  6658. // }
  6659. // }
  6660. // }
  6661. // }
  6662. for (int fieldIdx = 0; fieldIdx < (int)enumType->mFieldInstances.size(); fieldIdx++)
  6663. {
  6664. auto fieldInstance = &enumType->mFieldInstances[fieldIdx];
  6665. auto fieldDef = fieldInstance->GetFieldDef();
  6666. if (fieldDef == NULL)
  6667. continue;
  6668. if ((fieldInstance->mIsEnumPayloadCase) && (fieldDef->mName == caseName))
  6669. {
  6670. if ((!enumType->IsTypeMemberIncluded(fieldDef->mDeclaringType, activeTypeDef, mModule)) ||
  6671. (!enumType->IsTypeMemberAccessible(fieldDef->mDeclaringType, activeTypeDef)))
  6672. continue;
  6673. auto autoComplete = GetAutoComplete();
  6674. if ((autoComplete != NULL) && (autoComplete->mIsCapturingMethodMatchInfo))
  6675. {
  6676. BfAutoComplete::MethodMatchEntry methodMatchEntry;
  6677. methodMatchEntry.mPayloadEnumField = fieldInstance;
  6678. methodMatchEntry.mTypeInstance = enumType;
  6679. methodMatchEntry.mCurMethodInstance = mModule->mCurMethodInstance;
  6680. autoComplete->mMethodMatchInfo->mInstanceList.push_back(methodMatchEntry);
  6681. }
  6682. if (resolvePassData != NULL)
  6683. {
  6684. BfAstNode* nameNode = targetSrc;
  6685. if (resolvePassData->mGetSymbolReferenceKind == BfGetSymbolReferenceKind_Field)
  6686. resolvePassData->HandleFieldReference(nameNode, enumType->mTypeDef, fieldDef);
  6687. }
  6688. BfIRValue enumValue;
  6689. BfTypedValue result;
  6690. bool wantConst = IsComptimeEntry();
  6691. if (wantConst)
  6692. {
  6693. NOP;
  6694. }
  6695. else if ((mReceivingValue != NULL) && (mReceivingValue->mType == enumType) && (mReceivingValue->IsAddr()))
  6696. {
  6697. result = *mReceivingValue;
  6698. mReceivingValue = NULL;
  6699. enumValue = result.mValue;
  6700. }
  6701. else
  6702. {
  6703. mResultIsTempComposite = true;
  6704. enumValue = mModule->CreateAlloca(enumType);
  6705. result = BfTypedValue(enumValue, fieldInstance->mOwner, BfTypedValueKind_TempAddr);
  6706. }
  6707. BF_ASSERT(fieldInstance->mResolvedType->IsTuple());
  6708. auto tupleType = (BfTypeInstance*)fieldInstance->mResolvedType;
  6709. mModule->mBfIRBuilder->PopulateType(tupleType);
  6710. bool constFailed = false;
  6711. SizedArray<BfIRValue, 8> constTupleMembers;
  6712. BfIRValue fieldPtr;
  6713. BfIRValue tuplePtr;
  6714. if (wantConst)
  6715. {
  6716. constTupleMembers.Add(mModule->mBfIRBuilder->CreateConstAggZero(mModule->mBfIRBuilder->MapType(tupleType->mBaseType)));
  6717. }
  6718. else if (!tupleType->IsValuelessType())
  6719. {
  6720. fieldPtr = mModule->mBfIRBuilder->CreateInBoundsGEP(enumValue, 0, 1);
  6721. auto tuplePtrType = mModule->CreatePointerType(tupleType);
  6722. auto mappedPtrType = mModule->mBfIRBuilder->MapType(tuplePtrType);
  6723. tuplePtr = mModule->mBfIRBuilder->CreateBitCast(fieldPtr, mappedPtrType);
  6724. }
  6725. for (int tupleFieldIdx = 0; tupleFieldIdx < (int)tupleType->mFieldInstances.size(); tupleFieldIdx++)
  6726. {
  6727. auto tupleFieldInstance = &tupleType->mFieldInstances[tupleFieldIdx];
  6728. auto resolvedFieldType = tupleFieldInstance->GetResolvedType();
  6729. if (tupleFieldIdx >= argValues.mResolvedArgs.size())
  6730. {
  6731. BfAstNode* refNode = targetSrc;
  6732. BfAstNode* prevNode = NULL;
  6733. if (mModule->mParentNodeEntry != NULL)
  6734. {
  6735. if (auto invokeExpr = BfNodeDynCast<BfInvocationExpression>(mModule->mParentNodeEntry->mNode))
  6736. {
  6737. if (invokeExpr->mCloseParen != NULL)
  6738. refNode = invokeExpr->mCloseParen;
  6739. }
  6740. }
  6741. BfError* error = mModule->Fail(StrFormat("Not enough parameters specified, expected %d more.", tupleType->mFieldInstances.size() - (int)argValues.mArguments->size()), refNode);
  6742. if (error != NULL)
  6743. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("See enum declaration"), fieldDef->mFieldDeclaration);
  6744. if (wantConst)
  6745. constFailed = true;
  6746. break;
  6747. }
  6748. BfTypedValue receivingValue;
  6749. BfIRValue tupleFieldPtr;
  6750. if (tuplePtr)
  6751. {
  6752. tupleFieldPtr = mModule->mBfIRBuilder->CreateInBoundsGEP(tuplePtr, 0, tupleFieldInstance->mDataIdx);
  6753. receivingValue = BfTypedValue(tupleFieldPtr, tupleFieldInstance->mResolvedType, true);
  6754. }
  6755. auto argValue = ResolveArgValue(argValues.mResolvedArgs[tupleFieldIdx], resolvedFieldType, &receivingValue);
  6756. if (!argValue)
  6757. {
  6758. if (wantConst)
  6759. constFailed = true;
  6760. continue;
  6761. }
  6762. if (argValue.IsValuelessType())
  6763. {
  6764. continue;
  6765. }
  6766. // Used receiving value?
  6767. if (argValue.mValue == receivingValue.mValue)
  6768. continue;
  6769. argValue = mModule->AggregateSplat(argValue);
  6770. argValues.mResolvedArgs[tupleFieldIdx].mExpectedType = resolvedFieldType;
  6771. if ((argValues.mResolvedArgs[tupleFieldIdx].mArgFlags & (BfArgFlag_DelegateBindAttempt | BfArgFlag_LambdaBindAttempt | BfArgFlag_UnqualifiedDotAttempt)) != 0)
  6772. {
  6773. auto expr = BfNodeDynCast<BfExpression>(argValues.mResolvedArgs[tupleFieldIdx].mExpression);
  6774. BF_ASSERT(expr != NULL);
  6775. argValue = mModule->CreateValueFromExpression(expr, resolvedFieldType, (BfEvalExprFlags)(mBfEvalExprFlags & BfEvalExprFlags_InheritFlags));
  6776. }
  6777. if (argValue)
  6778. {
  6779. // argValue can have a value even if tuplePtr does not have a value. This can happen if we are assigning to a (void) tuple,
  6780. // but we have a value that needs to be attempted to be casted to void
  6781. argValue = mModule->Cast(argValues.mResolvedArgs[tupleFieldIdx].mExpression, argValue, resolvedFieldType);
  6782. if (wantConst)
  6783. {
  6784. if (!argValue.mValue.IsConst())
  6785. {
  6786. mModule->Fail("Field not const", argValues.mResolvedArgs[tupleFieldIdx].mExpression);
  6787. constFailed = true;
  6788. }
  6789. constTupleMembers.Add(argValue.mValue);
  6790. }
  6791. else if (tupleFieldPtr)
  6792. {
  6793. argValue = mModule->LoadValue(argValue);
  6794. if (argValue)
  6795. mModule->mBfIRBuilder->CreateAlignedStore(argValue.mValue, tupleFieldPtr, resolvedFieldType->mAlign);
  6796. }
  6797. }
  6798. else if (wantConst)
  6799. constFailed = true;
  6800. }
  6801. if ((intptr)argValues.mResolvedArgs.size() > tupleType->mFieldInstances.size())
  6802. {
  6803. BfAstNode* errorRef = argValues.mResolvedArgs[tupleType->mFieldInstances.size()].mExpression;
  6804. if (errorRef == NULL)
  6805. errorRef = targetSrc;
  6806. BfError* error = mModule->Fail(StrFormat("Too many arguments, expected %d fewer.", argValues.mResolvedArgs.size() - tupleType->mFieldInstances.size()), errorRef);
  6807. if (error != NULL)
  6808. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("See enum declaration"), fieldDef->mFieldDeclaration);
  6809. if (wantConst)
  6810. constFailed = true;
  6811. }
  6812. auto dscrType = enumType->GetDiscriminatorType();
  6813. auto dscrField = &enumType->mFieldInstances.back();
  6814. int tagIdx = -fieldInstance->mDataIdx - 1;
  6815. if ((wantConst) && (!constFailed))
  6816. {
  6817. auto unionType = enumType->GetUnionInnerType();
  6818. auto constTuple = mModule->mBfIRBuilder->CreateConstAgg(mModule->mBfIRBuilder->MapType(tupleType, BfIRPopulateType_Full), constTupleMembers);
  6819. Array<uint8> memArr;
  6820. memArr.Resize(unionType->mSize);
  6821. if (!mModule->mBfIRBuilder->WriteConstant(constTuple, memArr.mVals, tupleType))
  6822. {
  6823. constFailed = true;
  6824. }
  6825. else
  6826. {
  6827. auto unionValue = mModule->mBfIRBuilder->ReadConstant(memArr.mVals, unionType);
  6828. if (!unionValue)
  6829. {
  6830. constFailed = true;
  6831. }
  6832. else
  6833. {
  6834. SizedArray<BfIRValue, 3> constEnumMembers;
  6835. constEnumMembers.Add(mModule->mBfIRBuilder->CreateConstAggZero(mModule->mBfIRBuilder->MapType(enumType->mBaseType, BfIRPopulateType_Full)));
  6836. constEnumMembers.Add(unionValue);
  6837. constEnumMembers.Add(mModule->mBfIRBuilder->CreateConst(dscrType->mTypeDef->mTypeCode, tagIdx));
  6838. return BfTypedValue(mModule->mBfIRBuilder->CreateConstAgg(mModule->mBfIRBuilder->MapType(enumType, BfIRPopulateType_Full), constEnumMembers), enumType);
  6839. }
  6840. }
  6841. }
  6842. if (constFailed)
  6843. {
  6844. return mModule->GetDefaultTypedValue(enumType, false, BfDefaultValueKind_Addr);
  6845. }
  6846. auto dscFieldPtr = mModule->mBfIRBuilder->CreateInBoundsGEP(enumValue, 0, dscrField->mDataIdx);
  6847. mModule->mBfIRBuilder->CreateAlignedStore(mModule->mBfIRBuilder->CreateConst(dscrType->mTypeDef->mTypeCode, tagIdx), dscFieldPtr, 4);
  6848. return result;
  6849. }
  6850. }
  6851. return BfTypedValue();
  6852. }
  6853. bool BfExprEvaluator::CheckGenericCtor(BfGenericParamType* genericParamType, BfResolvedArgs& argValues, BfAstNode* targetSrc)
  6854. {
  6855. auto genericConstraint = mModule->GetGenericParamInstance(genericParamType);
  6856. bool success = true;
  6857. if ((argValues.mArguments != NULL) && (argValues.mArguments->size() != 0))
  6858. {
  6859. mModule->Fail(StrFormat("Only default parameterless constructors can be called on generic argument '%s'", genericConstraint->GetGenericParamDef()->mName.c_str()), targetSrc);
  6860. success = false;
  6861. }
  6862. else if ((genericConstraint->mGenericParamFlags & (BfGenericParamFlag_New | BfGenericParamFlag_Struct)) == 0)
  6863. {
  6864. mModule->Fail(StrFormat("Must add 'where %s : new, struct' constraint to generic parameter to instantiate type", genericConstraint->GetGenericParamDef()->mName.c_str()), targetSrc);
  6865. success = false;
  6866. }
  6867. else if ((genericConstraint->mGenericParamFlags & BfGenericParamFlag_New) == 0)
  6868. {
  6869. mModule->Fail(StrFormat("Must add 'where %s : new' constraint to generic parameter to instantiate type", genericConstraint->GetGenericParamDef()->mName.c_str()), targetSrc);
  6870. success = false;
  6871. }
  6872. else if ((genericConstraint->mGenericParamFlags & BfGenericParamFlag_Struct) == 0)
  6873. {
  6874. mModule->Fail(StrFormat("Must add 'where %s : struct' constraint to generic parameter to instantiate type without allocator", genericConstraint->GetGenericParamDef()->mName.c_str()), targetSrc);
  6875. success = false;
  6876. }
  6877. return success;
  6878. }
  6879. BfTypedValue BfExprEvaluator::MatchMethod(BfAstNode* targetSrc, BfMethodBoundExpression* methodBoundExpr, BfTypedValue target, bool allowImplicitThis, bool bypassVirtual, const StringImpl& methodName,
  6880. BfResolvedArgs& argValues, BfSizedArray<ASTREF(BfTypeReference*)>* methodGenericArguments, BfCheckedKind checkedKind)
  6881. {
  6882. BP_ZONE("MatchMethod");
  6883. if (bypassVirtual)
  6884. {
  6885. // "bypassVirtual" means that we know for sure that the target is EXACTLY the specified target type,
  6886. // not derived from (or implementing) the target type. This cannot apply to interfaces.
  6887. BF_ASSERT(!target.mType->IsInterface());
  6888. }
  6889. auto origTarget = target;
  6890. if (mFunctionBindResult != NULL)
  6891. {
  6892. BF_ASSERT(!mFunctionBindResult->mOrigTarget);
  6893. mFunctionBindResult->mOrigTarget = origTarget;
  6894. }
  6895. if (target)
  6896. {
  6897. if (target.mType->IsConcreteInterfaceType())
  6898. target.mType = target.mType->GetUnderlyingType();
  6899. // Turn T* into a T, if we can
  6900. if ((target.mType->IsPointer()) && (target.mType->GetUnderlyingType()->IsGenericParam()))
  6901. {
  6902. auto underlyingType = target.mType->GetUnderlyingType();
  6903. auto genericParam = mModule->GetGenericParamInstance((BfGenericParamType*)underlyingType);
  6904. if (((genericParam->mTypeConstraint != NULL) && (genericParam->mTypeConstraint->IsValueType())) ||
  6905. ((genericParam->mGenericParamFlags & (BfGenericParamFlag_Struct)) != 0))
  6906. {
  6907. target.mType = underlyingType;
  6908. }
  6909. }
  6910. if ((!target.mType->IsGenericParam()) && (!target.IsSplat()) && (!target.mType->IsVar()))
  6911. target = MakeCallableTarget(targetSrc, target);
  6912. }
  6913. // static int sCallIdx = 0;
  6914. // if (!mModule->mCompiler->mIsResolveOnly)
  6915. // sCallIdx++;
  6916. // int callIdx = sCallIdx;
  6917. // if (callIdx == 118)
  6918. // {
  6919. // NOP;
  6920. // }
  6921. bool prevAllowVariableDeclarations = true;
  6922. if (mModule->mCurMethodState != NULL)
  6923. {
  6924. // Don't allow variable declarations in arguments for this method call
  6925. prevAllowVariableDeclarations = mModule->mCurMethodState->mCurScope->mAllowVariableDeclarations;
  6926. mModule->mCurMethodState->mCurScope->mAllowVariableDeclarations = false;
  6927. }
  6928. defer
  6929. (
  6930. if (mModule->mCurMethodState != NULL)
  6931. mModule->mCurMethodState->mCurScope->mAllowVariableDeclarations = prevAllowVariableDeclarations;
  6932. );
  6933. // Temporarily disable so we don't capture calls in params
  6934. SetAndRestoreValue<BfFunctionBindResult*> prevBindResult(mFunctionBindResult, NULL);
  6935. sInvocationIdx++;
  6936. bool wantCtor = methodName.IsEmpty();
  6937. BfAutoComplete::MethodMatchInfo* restoreCapturingMethodMatchInfo = NULL;
  6938. auto autoComplete = GetAutoComplete();
  6939. if ((autoComplete != NULL) && (autoComplete->mIsCapturingMethodMatchInfo))
  6940. {
  6941. if ((!targetSrc->IsFromParser(mModule->mCompiler->mResolvePassData->mParser)) ||
  6942. ((autoComplete->mMethodMatchInfo->mInvocationSrcIdx != -1) && (autoComplete->mMethodMatchInfo->mInvocationSrcIdx != targetSrc->GetSrcStart())))
  6943. {
  6944. autoComplete->mIsCapturingMethodMatchInfo = false;
  6945. restoreCapturingMethodMatchInfo = autoComplete->mMethodMatchInfo;
  6946. }
  6947. }
  6948. defer(
  6949. {
  6950. if ((restoreCapturingMethodMatchInfo != NULL) && (autoComplete->mMethodMatchInfo == restoreCapturingMethodMatchInfo))
  6951. autoComplete->mIsCapturingMethodMatchInfo = true;
  6952. });
  6953. /*if ((autoComplete != NULL) && (autoComplete->mIsCapturingMethodMatchInfo) && (autoComplete->mMethodMatchInfo->mInstanceList.size() != 0))
  6954. autoComplete->mIsCapturingMethodMatchInfo = false;*/
  6955. bool isUnboundCall = false;
  6956. if (target.mType != NULL)
  6957. {
  6958. if (target.mType->IsGenericParam())
  6959. {
  6960. auto genericParamTarget = (BfGenericParamType*) target.mType;
  6961. auto genericParamInstance = mModule->GetGenericParamInstance(genericParamTarget);
  6962. isUnboundCall = (genericParamInstance->mGenericParamFlags & BfGenericParamFlag_Var) != 0;
  6963. if (isUnboundCall)
  6964. {
  6965. if (mModule->mCurMethodInstance->mIsUnspecialized)
  6966. {
  6967. auto varType = mModule->GetPrimitiveType(BfTypeCode_Var);
  6968. target.mType = varType;
  6969. }
  6970. }
  6971. }
  6972. else if (target.mType->IsVar())
  6973. isUnboundCall = true;
  6974. }
  6975. /*if (mPrefixedAttributeState != NULL)
  6976. {
  6977. auto customAttr = mPrefixedAttributeState->mCustomAttributes->Get(mModule->mCompiler->mUnboundAttributeTypeDef);
  6978. if (customAttr != NULL)
  6979. {
  6980. if (!mModule->IsInGeneric())
  6981. {
  6982. mModule->Fail("'Unbound' can only be used within generics");
  6983. }
  6984. mPrefixedAttributeState->mUsed = true;
  6985. isUnboundCall = true;
  6986. }
  6987. }*/
  6988. if ((mModule->mAttributeState != NULL) && (mModule->mAttributeState->mCustomAttributes != NULL))
  6989. {
  6990. auto customAttr = mModule->mAttributeState->mCustomAttributes->Get(mModule->mCompiler->mUnboundAttributeTypeDef);
  6991. if (customAttr != NULL)
  6992. {
  6993. if (!mModule->IsInGeneric())
  6994. {
  6995. mModule->Fail("'Unbound' can only be used within generics");
  6996. }
  6997. mModule->mAttributeState->mUsed = true;
  6998. isUnboundCall = true;
  6999. }
  7000. }
  7001. if (isUnboundCall)
  7002. {
  7003. if ((mModule->mCurMethodInstance != NULL) && (mModule->mCurMethodInstance->mIsUnspecialized))
  7004. {
  7005. auto varType = mModule->GetPrimitiveType(BfTypeCode_Var);
  7006. for (int argIdx = 0; argIdx < (int)argValues.mResolvedArgs.size(); argIdx++)
  7007. {
  7008. if ((argValues.mResolvedArgs[argIdx].mArgFlags & BfArgFlag_DeferredEval) != 0)
  7009. {
  7010. mModule->CreateValueFromExpression((*argValues.mArguments)[argIdx], varType);
  7011. }
  7012. }
  7013. return BfTypedValue(mModule->GetDefaultValue(varType), varType);
  7014. }
  7015. }
  7016. SetAndRestoreValue<bool> prevNoBind(mNoBind, mNoBind || isUnboundCall);
  7017. bool wantsExtensionCheck = target;
  7018. auto targetType = target.mType;
  7019. BfTypeDef* curTypeDef = NULL;
  7020. BfTypeInstance* targetTypeInst = NULL;
  7021. bool checkNonStatic = true;
  7022. if (target)
  7023. {
  7024. if (targetType->IsVar())
  7025. return mModule->GetDefaultTypedValue(targetType);
  7026. targetTypeInst = targetType->ToTypeInstance();
  7027. if (targetTypeInst != NULL)
  7028. curTypeDef = targetTypeInst->mTypeDef;
  7029. }
  7030. else if (targetType != NULL) // Static targeted
  7031. {
  7032. if (targetType->IsWrappableType())
  7033. {
  7034. targetTypeInst = mModule->GetWrappedStructType(targetType);
  7035. }
  7036. else if (targetType->IsGenericParam())
  7037. {
  7038. auto genericParamInstance = mModule->GetGenericParamInstance((BfGenericParamType*)targetType);
  7039. if (genericParamInstance->mTypeConstraint != NULL)
  7040. targetTypeInst = genericParamInstance->mTypeConstraint->ToTypeInstance();
  7041. if (genericParamInstance->mGenericParamFlags & BfGenericParamFlag_Var)
  7042. {
  7043. auto varType = mModule->GetPrimitiveType(BfTypeCode_Var);
  7044. return BfTypedValue(mModule->GetDefaultValue(varType), varType);
  7045. }
  7046. }
  7047. else
  7048. targetTypeInst = targetType->ToTypeInstance();
  7049. if (targetTypeInst == NULL)
  7050. {
  7051. //mModule->Fail("No static methods available", targetSrc);
  7052. //return BfTypedValue();
  7053. }
  7054. else
  7055. {
  7056. curTypeDef = targetTypeInst->mTypeDef;
  7057. checkNonStatic = false;
  7058. }
  7059. }
  7060. else // Current scopeData
  7061. {
  7062. if ((mModule->mCurMethodInstance != NULL) && (mModule->mCurMethodInstance->mIsForeignMethodDef) && (mModule->mCurMethodInstance->mMethodInfoEx->mForeignType->IsInterface()))
  7063. {
  7064. targetTypeInst = mModule->mCurMethodInstance->mMethodInfoEx->mForeignType;
  7065. curTypeDef = targetTypeInst->mTypeDef;
  7066. checkNonStatic = true;
  7067. target = mModule->GetThis();
  7068. //target.mType = targetTypeInst;
  7069. }
  7070. else
  7071. {
  7072. curTypeDef = mModule->mCurTypeInstance->mTypeDef;
  7073. targetTypeInst = mModule->mCurTypeInstance;
  7074. if (mModule->mCurMethodState == NULL)
  7075. {
  7076. checkNonStatic = false;
  7077. }
  7078. else
  7079. {
  7080. if (mModule->mCurMethodState->mMixinState != NULL)
  7081. {
  7082. targetTypeInst = mModule->mCurMethodState->mMixinState->mMixinMethodInstance->GetOwner();
  7083. curTypeDef = targetTypeInst->mTypeDef;
  7084. }
  7085. if (mModule->mCurMethodState->mTempKind != BfMethodState::TempKind_None)
  7086. {
  7087. checkNonStatic = mModule->mCurMethodState->mTempKind == BfMethodState::TempKind_NonStatic;
  7088. }
  7089. else
  7090. checkNonStatic = !mModule->mCurMethodInstance->mMethodDef->mIsStatic;
  7091. }
  7092. }
  7093. }
  7094. bool isIndirectMethodCall = false;
  7095. BfType* lookupType = targetType;
  7096. BfTypeInstance* lookupTypeInst = targetTypeInst;
  7097. if (targetType != NULL)
  7098. {
  7099. lookupType = BindGenericType(targetSrc, targetType);
  7100. if (lookupType->IsGenericParam())
  7101. lookupTypeInst = NULL;
  7102. }
  7103. BfMethodDef* methodDef = NULL;
  7104. BfTypeVector checkMethodGenericArguments;
  7105. BfTypeInstance* curTypeInst = targetTypeInst;
  7106. BfMethodMatcher methodMatcher(targetSrc, mModule, methodName, argValues.mResolvedArgs, methodGenericArguments);
  7107. methodMatcher.mOrigTarget = origTarget;
  7108. methodMatcher.mTarget = target;
  7109. methodMatcher.mCheckedKind = checkedKind;
  7110. methodMatcher.mAllowImplicitThis = allowImplicitThis;
  7111. methodMatcher.mAllowStatic = !target.mValue;
  7112. methodMatcher.mAllowNonStatic = !methodMatcher.mAllowStatic;
  7113. methodMatcher.mAutoFlushAmbiguityErrors = !wantsExtensionCheck;
  7114. if (allowImplicitThis)
  7115. {
  7116. if (mModule->mCurMethodState == NULL)
  7117. {
  7118. methodMatcher.mAllowStatic = true;
  7119. methodMatcher.mAllowNonStatic = false;
  7120. }
  7121. else if (mModule->mCurMethodState->mTempKind != BfMethodState::TempKind_None)
  7122. {
  7123. methodMatcher.mAllowNonStatic = mModule->mCurMethodState->mTempKind == BfMethodState::TempKind_NonStatic;
  7124. methodMatcher.mAllowStatic = true;
  7125. }
  7126. else
  7127. {
  7128. if (!mModule->mCurMethodInstance->mMethodDef->mIsStatic)
  7129. methodMatcher.mAllowNonStatic = true;
  7130. methodMatcher.mAllowStatic = true;
  7131. if (mModule->mCurMethodInstance->mMethodDef->mIsLocalMethod)
  7132. {
  7133. auto rootMethodState = mModule->mCurMethodState->GetRootMethodState();
  7134. methodMatcher.mAllowNonStatic = !rootMethodState->mMethodInstance->mMethodDef->mIsStatic;
  7135. }
  7136. }
  7137. }
  7138. if (methodName == BF_METHODNAME_CALCAPPEND)
  7139. methodMatcher.mMethodType = BfMethodType_CtorCalcAppend;
  7140. BF_ASSERT(methodMatcher.mBestMethodDef == NULL);
  7141. BfLocalMethod* matchedLocalMethod = NULL;
  7142. if (target.mType == NULL)
  7143. {
  7144. CheckLocalMethods(targetSrc, curTypeInst, methodName, methodMatcher, BfMethodType_Normal);
  7145. if (methodMatcher.mBestMethodDef == NULL)
  7146. methodMatcher.mBestMethodDef = methodMatcher.mBackupMethodDef;
  7147. if (methodMatcher.mBestMethodDef != NULL)
  7148. {
  7149. auto rootMethodState = mModule->mCurMethodState->GetRootMethodState();
  7150. auto methodDef = methodMatcher.mBestMethodDef;
  7151. if (mModule->mCompiler->mResolvePassData != NULL)
  7152. {
  7153. auto identifierNode = BfNodeDynCast<BfIdentifierNode>(targetSrc);
  7154. mModule->mCompiler->mResolvePassData->HandleLocalReference(identifierNode, curTypeInst->mTypeDef, rootMethodState->mMethodInstance->mMethodDef, ~methodDef->mIdx);
  7155. auto autoComplete = GetAutoComplete();
  7156. if ((autoComplete != NULL) && (autoComplete->IsAutocompleteNode(identifierNode)))
  7157. {
  7158. autoComplete->SetDefinitionLocation(methodDef->GetRefNode(), true);
  7159. if (autoComplete->mDefType == NULL)
  7160. {
  7161. autoComplete->mDefMethod = mModule->mCurMethodState->GetRootMethodState()->mMethodInstance->mMethodDef;
  7162. autoComplete->mDefType = curTypeDef;
  7163. autoComplete->mReplaceLocalId = ~methodDef->mIdx;
  7164. }
  7165. }
  7166. if ((autoComplete != NULL) && (autoComplete->mIsCapturingMethodMatchInfo))
  7167. {
  7168. BfAutoComplete::MethodMatchEntry methodMatchEntry;
  7169. methodMatchEntry.mMethodDef = methodDef;
  7170. methodMatchEntry.mTypeInstance = mModule->mCurTypeInstance;
  7171. methodMatchEntry.mCurMethodInstance = mModule->mCurMethodInstance;
  7172. autoComplete->mMethodMatchInfo->mInstanceList.push_back(methodMatchEntry);
  7173. }
  7174. }
  7175. if ((mModule->mCurMethodState->mClosureState != NULL) && (mModule->mCurMethodState->mClosureState->mCapturing))
  7176. {
  7177. auto methodInstance = mModule->GetRawMethodInstance(methodMatcher.mBestMethodTypeInstance, methodMatcher.mBestMethodDef);
  7178. if (methodInstance->mReturnType == NULL)
  7179. {
  7180. FinishDeferredEvals(argValues);
  7181. // If we are recursive then we won't even have a completed methodInstance yet to look at
  7182. return mModule->GetDefaultTypedValue(mModule->mContext->mBfObjectType);
  7183. }
  7184. }
  7185. }
  7186. }
  7187. if (methodMatcher.mBestMethodDef == NULL)
  7188. {
  7189. if (lookupTypeInst == NULL)
  7190. {
  7191. if ((lookupType != NULL) && (lookupType->IsConcreteInterfaceType()))
  7192. {
  7193. auto concreteInterfaceType = (BfConcreteInterfaceType*)lookupType;
  7194. lookupTypeInst = concreteInterfaceType->mInterface;
  7195. }
  7196. else if (isUnboundCall)
  7197. {
  7198. //auto resolvedType = mModule->ResolveGenericType(lookupType);
  7199. }
  7200. else if (lookupType->IsGenericParam())
  7201. {
  7202. auto genericParamTarget = (BfGenericParamType*)lookupType;
  7203. auto _HandleGenericParamInstance = [&](BfGenericParamInstance* genericParamInstance)
  7204. {
  7205. if (genericParamInstance->mTypeConstraint != NULL)
  7206. lookupTypeInst = genericParamInstance->mTypeConstraint->ToTypeInstance();
  7207. else
  7208. lookupTypeInst = mModule->mContext->mBfObjectType;
  7209. for (BfType* ifaceInst : genericParamInstance->mInterfaceConstraints)
  7210. {
  7211. if (ifaceInst->IsUnspecializedType())
  7212. ifaceInst = mModule->ResolveType(ifaceInst);
  7213. BfTypeInstance* typeInst = ifaceInst->ToTypeInstance();
  7214. BF_ASSERT(typeInst != NULL);
  7215. if (methodMatcher.CheckType(typeInst, target, false))
  7216. methodMatcher.mSelfType = lookupType;
  7217. }
  7218. };
  7219. auto genericParamInstance = mModule->GetGenericParamInstance(genericParamTarget);
  7220. _HandleGenericParamInstance(genericParamInstance);
  7221. // Check method generic constraints
  7222. if ((mModule->mCurMethodInstance != NULL) && (mModule->mCurMethodInstance->mIsUnspecialized) && (mModule->mCurMethodInstance->mMethodInfoEx != NULL))
  7223. {
  7224. for (int genericParamIdx = (int)mModule->mCurMethodInstance->mMethodInfoEx->mMethodGenericArguments.size();
  7225. genericParamIdx < mModule->mCurMethodInstance->mMethodInfoEx->mGenericParams.size(); genericParamIdx++)
  7226. {
  7227. auto genericParam = mModule->mCurMethodInstance->mMethodInfoEx->mGenericParams[genericParamIdx];
  7228. if (genericParam->mExternType == lookupType)
  7229. _HandleGenericParamInstance(genericParam);
  7230. }
  7231. }
  7232. }
  7233. }
  7234. if ((lookupTypeInst != NULL) && (!wantCtor))
  7235. {
  7236. methodMatcher.mBypassVirtual = bypassVirtual;
  7237. methodMatcher.CheckType(lookupTypeInst, target, false);
  7238. }
  7239. if ((lookupType != NULL) && (lookupType->IsGenericParam()))
  7240. {
  7241. //lookupType = mModule->ResolveGenericType(lookupType);
  7242. if (!lookupType->IsGenericParam())
  7243. {
  7244. target = MakeCallableTarget(targetSrc, target);
  7245. if (target)
  7246. {
  7247. lookupTypeInst = lookupType->ToTypeInstance();
  7248. }
  7249. }
  7250. }
  7251. }
  7252. bool isFailurePass = false;
  7253. if (methodMatcher.mBestMethodDef == NULL)
  7254. {
  7255. isFailurePass = true;
  7256. if (lookupTypeInst != NULL)
  7257. methodMatcher.CheckType(lookupTypeInst, target, true);
  7258. }
  7259. BfTypedValue staticResult;
  7260. methodMatcher.TryDevirtualizeCall(target, &origTarget, &staticResult);
  7261. if (staticResult)
  7262. return staticResult;
  7263. bypassVirtual |= methodMatcher.mBypassVirtual;
  7264. if (methodMatcher.mBestMethodDef != NULL)
  7265. {
  7266. curTypeInst = methodMatcher.mBestMethodTypeInstance;
  7267. methodDef = methodMatcher.mBestMethodDef;
  7268. }
  7269. if ((methodDef) && (!methodDef->mIsStatic) && (!target) && (allowImplicitThis))
  7270. {
  7271. target = mModule->GetThis();
  7272. }
  7273. // If we call "GetType" on a value type, statically determine the type rather than boxing and then dispatching
  7274. if ((methodDef) && (target) && (curTypeInst == mModule->mContext->mBfObjectType) &&
  7275. (methodDef->mName == "GetType") && (target.mType->IsValueType()) && (argValues.mArguments->IsEmpty()))
  7276. {
  7277. BfType* targetType = target.mType;
  7278. if (origTarget)
  7279. targetType = origTarget.mType;
  7280. auto typeType = mModule->ResolveTypeDef(mModule->mCompiler->mTypeTypeDef);
  7281. mModule->AddDependency(targetType, mModule->mCurTypeInstance, BfDependencyMap::DependencyFlag_ExprTypeReference);
  7282. return BfTypedValue(mModule->CreateTypeDataRef(targetType), typeType);
  7283. }
  7284. bool skipThis = false;
  7285. BfTypedValue fieldVal;
  7286. bool hasFieldVal = false;
  7287. // Fail, check for delegate field invocation
  7288. if ((methodDef == NULL) && ((methodGenericArguments == NULL) || (methodGenericArguments->size() == 0)))
  7289. {
  7290. // Check for payload enum initialization first
  7291. BfTypedValue enumResult;
  7292. BfTypeInstance* enumType = NULL;
  7293. if ((!target) && (mModule->mCurTypeInstance->IsPayloadEnum()))
  7294. {
  7295. enumType = mModule->mCurTypeInstance;
  7296. //enumResult = CheckEnumCreation(targetSrc, mModule->mCurTypeInstance, methodName, argValues);
  7297. }
  7298. else if ((!target) && (target.HasType()) && (targetType->IsPayloadEnum()))
  7299. {
  7300. enumType = targetType->ToTypeInstance();
  7301. //enumResult = CheckEnumCreation(targetSrc, enumType, methodName, argValues);
  7302. }
  7303. if (enumType != NULL)
  7304. {
  7305. enumResult = CheckEnumCreation(targetSrc, enumType, methodName, argValues);
  7306. }
  7307. if (enumResult)
  7308. {
  7309. if ((mModule->mCompiler->mResolvePassData != NULL) &&
  7310. (targetSrc->IsFromParser(mModule->mCompiler->mResolvePassData->mParser)) &&
  7311. (mModule->mCompiler->mResolvePassData->mSourceClassifier != NULL))
  7312. {
  7313. mModule->mCompiler->mResolvePassData->mSourceClassifier->SetElementType(targetSrc, BfSourceElementType_Normal);
  7314. }
  7315. return enumResult;
  7316. }
  7317. if (allowImplicitThis)
  7318. {
  7319. auto identifierNode = BfNodeDynCast<BfIdentifierNode>(targetSrc);
  7320. if (identifierNode != NULL)
  7321. fieldVal = LookupIdentifier(identifierNode);
  7322. }
  7323. else
  7324. {
  7325. SetAndRestoreValue<BfEvalExprFlags> prevFlags(mBfEvalExprFlags, (BfEvalExprFlags)(mBfEvalExprFlags & ~BfEvalExprFlags_AllowEnumId));
  7326. fieldVal = LookupField(targetSrc, target, methodName);
  7327. }
  7328. if (fieldVal)
  7329. {
  7330. hasFieldVal = true;
  7331. wantsExtensionCheck = !fieldVal.mType->IsDelegate() && !fieldVal.mType->IsFunction();
  7332. }
  7333. else if (mPropDef != NULL)
  7334. {
  7335. hasFieldVal = true;
  7336. BfMethodDef* matchedMethod = GetPropertyMethodDef(mPropDef, BfMethodType_PropertyGetter, mPropCheckedKind, mPropTarget);
  7337. if (matchedMethod != NULL)
  7338. {
  7339. auto getMethodInstance = mModule->GetRawMethodInstance(mPropTarget.mType->ToTypeInstance(), matchedMethod);
  7340. if ((getMethodInstance != NULL) &&
  7341. ((getMethodInstance->mReturnType->IsDelegate()) || (getMethodInstance->mReturnType->IsFunction())))
  7342. wantsExtensionCheck = false;
  7343. }
  7344. }
  7345. }
  7346. if ((!methodDef) && (!target.mValue))
  7347. {
  7348. // Check to see if we're constructing a struct via a call like: "Struct structVal = Struct()"
  7349. int wantNumGenericArgs = 0;
  7350. if ((methodGenericArguments != NULL) && (methodGenericArguments->size() > 0))
  7351. wantNumGenericArgs = (int)methodGenericArguments->size();
  7352. BfTypeInstance* resolvedTypeInstance = NULL;
  7353. if (wantCtor)
  7354. {
  7355. resolvedTypeInstance = targetTypeInst;
  7356. }
  7357. else if (targetType != NULL)
  7358. {
  7359. if (auto invocationExpr = BfNodeDynCast<BfInvocationExpression>(methodBoundExpr))
  7360. {
  7361. auto resolvedType = mModule->ResolveTypeRef(invocationExpr->mTarget, methodGenericArguments);
  7362. if (resolvedType != NULL)
  7363. resolvedTypeInstance = resolvedType->ToTypeInstance();
  7364. }
  7365. }
  7366. else
  7367. {
  7368. BfIdentifierNode* identifierNode = BfNodeDynCast<BfIdentifierNode>(targetSrc);
  7369. if (identifierNode != NULL)
  7370. {
  7371. SetAndRestoreValue<bool> prevIgnoreErrors(mModule->mIgnoreErrors, true);
  7372. BfType* refType;
  7373. if (methodGenericArguments != NULL)
  7374. {
  7375. refType = mModule->ResolveTypeRef(identifierNode, methodGenericArguments);
  7376. }
  7377. else
  7378. refType = mModule->ResolveTypeRef(identifierNode, NULL);
  7379. prevIgnoreErrors.Restore();
  7380. if ((refType != NULL) && (refType->IsPrimitiveType()))
  7381. {
  7382. FinishDeferredEvals(argValues);
  7383. if (argValues.mResolvedArgs.size() != 1)
  7384. {
  7385. mModule->Fail("Cast requires one parameter", targetSrc);
  7386. return BfTypedValue();
  7387. }
  7388. // This is just a primitive cast
  7389. auto& resolvedArg = argValues.mResolvedArgs[0];
  7390. BfTypedValue castedValue;
  7391. BfTypedValue castTarget = resolvedArg.mTypedValue;
  7392. if (resolvedArg.mTypedValue)
  7393. {
  7394. castTarget = mModule->LoadValue(castTarget);
  7395. castedValue = mModule->Cast(targetSrc, castTarget, refType, BfCastFlags_Explicit);
  7396. }
  7397. if (!castedValue)
  7398. castedValue = mModule->GetDefaultTypedValue(refType);
  7399. return castedValue;
  7400. }
  7401. if (refType != NULL)
  7402. {
  7403. resolvedTypeInstance = refType->ToTypeInstance();
  7404. if (refType->IsGenericParam())
  7405. {
  7406. CheckGenericCtor((BfGenericParamType*)refType, argValues, targetSrc);
  7407. return mModule->GetDefaultTypedValue(refType);
  7408. }
  7409. }
  7410. }
  7411. }
  7412. if (resolvedTypeInstance != NULL)
  7413. {
  7414. if ((!resolvedTypeInstance->IsStruct()) && (!resolvedTypeInstance->IsTypedPrimitive()))
  7415. {
  7416. mModule->Fail("Objects must be allocated through 'new' or 'scope'", targetSrc);
  7417. return BfTypedValue();
  7418. }
  7419. if (auto identifier = BfNodeDynCastExact<BfIdentifierNode>(targetSrc))
  7420. mModule->SetElementType(identifier, BfSourceElementType_Type);
  7421. if (mModule->mCompiler->mResolvePassData != NULL)
  7422. mModule->mCompiler->mResolvePassData->HandleTypeReference(targetSrc, resolvedTypeInstance->mTypeDef);
  7423. BfTypedValue structInst;
  7424. mModule->PopulateType(resolvedTypeInstance);
  7425. if (!resolvedTypeInstance->IsValuelessType())
  7426. {
  7427. if ((mReceivingValue != NULL) && (mReceivingValue->mType == resolvedTypeInstance) && (mReceivingValue->IsAddr()))
  7428. {
  7429. structInst = *mReceivingValue;
  7430. mReceivingValue = NULL;
  7431. }
  7432. else
  7433. {
  7434. auto allocaInst = mModule->CreateAlloca(resolvedTypeInstance);
  7435. structInst = BfTypedValue(allocaInst, resolvedTypeInstance, true);
  7436. }
  7437. mResultIsTempComposite = true;
  7438. }
  7439. else
  7440. {
  7441. structInst = BfTypedValue(mModule->mBfIRBuilder->GetFakeVal(), resolvedTypeInstance, true);
  7442. }
  7443. mResultLocalVar = NULL;
  7444. mResultFieldInstance = NULL;
  7445. mResultLocalVarRefNode = NULL;
  7446. auto result = MatchConstructor(targetSrc, methodBoundExpr, structInst, resolvedTypeInstance, argValues, false, false);
  7447. if ((result) && (!result.mType->IsVoid()))
  7448. return result;
  7449. mModule->ValidateAllocation(resolvedTypeInstance, targetSrc);
  7450. mModule->AddDependency(resolvedTypeInstance, mModule->mCurTypeInstance, BfDependencyMap::DependencyFlag_LocalUsage);
  7451. if (mUsedAsStatement)
  7452. {
  7453. mModule->Warn(0, "Struct constructor being used as a statement", targetSrc);
  7454. }
  7455. return structInst;
  7456. }
  7457. }
  7458. // For for extensions in current type
  7459. if (wantsExtensionCheck)
  7460. {
  7461. auto checkTypeInst = mModule->mCurTypeInstance;
  7462. methodMatcher.mMethodType = BfMethodType_Extension;
  7463. if (methodMatcher.CheckType(checkTypeInst, BfTypedValue(), false, true))
  7464. {
  7465. isFailurePass = false;
  7466. curTypeInst = methodMatcher.mBestMethodTypeInstance;
  7467. methodDef = methodMatcher.mBestMethodDef;
  7468. }
  7469. }
  7470. // Look in globals. Always check for extension methods.
  7471. if ((methodDef == NULL) || (wantsExtensionCheck))
  7472. {
  7473. if (mModule->mContext->mCurTypeState != NULL)
  7474. {
  7475. BfGlobalLookup globalLookup;
  7476. globalLookup.mKind = BfGlobalLookup::Kind_Method;
  7477. globalLookup.mName = methodName;
  7478. mModule->PopulateGlobalContainersList(globalLookup);
  7479. for (auto& globalContainer : mModule->mContext->mCurTypeState->mGlobalContainers)
  7480. {
  7481. if (globalContainer.mTypeInst == NULL)
  7482. continue;
  7483. methodMatcher.mMethodType = wantsExtensionCheck ? BfMethodType_Extension : BfMethodType_Normal;
  7484. if (methodMatcher.CheckType(globalContainer.mTypeInst, BfTypedValue(), false))
  7485. {
  7486. isFailurePass = false;
  7487. curTypeInst = methodMatcher.mBestMethodTypeInstance;
  7488. methodDef = methodMatcher.mBestMethodDef;
  7489. }
  7490. }
  7491. }
  7492. }
  7493. // Look in static search. Always check for extension methods.
  7494. if ((methodDef == NULL) || (wantsExtensionCheck))
  7495. {
  7496. BfStaticSearch* staticSearch = mModule->GetStaticSearch();
  7497. if (staticSearch != NULL)
  7498. {
  7499. for (auto typeInst : staticSearch->mStaticTypes)
  7500. {
  7501. methodMatcher.mMethodType = wantsExtensionCheck ? BfMethodType_Extension : BfMethodType_Normal;
  7502. if (methodMatcher.CheckType(typeInst, BfTypedValue(), false))
  7503. {
  7504. isFailurePass = false;
  7505. curTypeInst = methodMatcher.mBestMethodTypeInstance;
  7506. methodDef = methodMatcher.mBestMethodDef;
  7507. }
  7508. }
  7509. }
  7510. }
  7511. if ((methodDef == NULL) && (hasFieldVal))
  7512. {
  7513. if (mPropDef != NULL)
  7514. fieldVal = GetResult();
  7515. if (fieldVal)
  7516. {
  7517. if (fieldVal.mType->IsGenericParam())
  7518. {
  7519. bool delegateFailed = true;
  7520. auto genericParamInstance = mModule->GetGenericParamInstance((BfGenericParamType*)fieldVal.mType);
  7521. BfTypeInstance* typeInstConstraint = NULL;
  7522. if (genericParamInstance->mTypeConstraint != NULL)
  7523. typeInstConstraint = genericParamInstance->mTypeConstraint->ToTypeInstance();
  7524. if ((typeInstConstraint != NULL) &&
  7525. ((typeInstConstraint->mTypeDef == mModule->mCompiler->mDelegateTypeDef) || (typeInstConstraint->mTypeDef == mModule->mCompiler->mFunctionTypeDef)))
  7526. {
  7527. MarkResultUsed();
  7528. if (argValues.mArguments->size() == 1)
  7529. {
  7530. BfExprEvaluator exprEvaluator(mModule);
  7531. exprEvaluator.mBfEvalExprFlags = BfEvalExprFlags_AllowParamsExpr;
  7532. exprEvaluator.Evaluate((*argValues.mArguments)[0]);
  7533. if ((mModule->mCurMethodState != NULL) && (exprEvaluator.mResultLocalVar != NULL) && (exprEvaluator.mResultLocalVarRefNode != NULL))
  7534. {
  7535. auto localVar = exprEvaluator.mResultLocalVar;
  7536. if ((localVar->mCompositeCount >= 0) && (localVar->mResolvedType == fieldVal.mType))
  7537. {
  7538. delegateFailed = false;
  7539. if (mModule->mCurMethodInstance->mIsUnspecialized)
  7540. {
  7541. auto retTypeType = mModule->CreateModifiedTypeType(fieldVal.mType, BfToken_RetType);
  7542. return mModule->GetFakeTypedValue(retTypeType);
  7543. }
  7544. }
  7545. }
  7546. }
  7547. if (delegateFailed)
  7548. {
  7549. mModule->Fail(StrFormat("Generic delegates can only be invoked with 'params %s' composite parameters", mModule->TypeToString(fieldVal.mType).c_str()), targetSrc);
  7550. return BfTypedValue();
  7551. }
  7552. }
  7553. }
  7554. if (fieldVal.mType->IsTypeInstance())
  7555. {
  7556. prevBindResult.Restore();
  7557. auto fieldTypeInst = fieldVal.mType->ToTypeInstance();
  7558. MarkResultUsed();
  7559. return MatchMethod(targetSrc, NULL, fieldVal, false, false, "Invoke", argValues, methodGenericArguments, checkedKind);
  7560. }
  7561. if (fieldVal.mType->IsVar())
  7562. {
  7563. FinishDeferredEvals(argValues);
  7564. return BfTypedValue(mModule->GetDefaultValue(fieldVal.mType), fieldVal.mType);
  7565. }
  7566. if (fieldVal.mType->IsGenericParam())
  7567. {
  7568. auto genericParam = mModule->GetGenericParamInstance((BfGenericParamType*)fieldVal.mType);
  7569. BfType* typeConstraint = genericParam->mTypeConstraint;
  7570. if ((mModule->mCurMethodInstance != NULL) && (mModule->mCurMethodInstance->mIsUnspecialized) && (mModule->mCurMethodInstance->mMethodInfoEx != NULL))
  7571. {
  7572. for (int genericParamIdx = (int)mModule->mCurMethodInstance->mMethodInfoEx->mMethodGenericArguments.size();
  7573. genericParamIdx < mModule->mCurMethodInstance->mMethodInfoEx->mGenericParams.size(); genericParamIdx++)
  7574. {
  7575. auto genericParam = mModule->mCurMethodInstance->mMethodInfoEx->mGenericParams[genericParamIdx];
  7576. if ((genericParam->mExternType == fieldVal.mType) && (genericParam->mTypeConstraint != NULL))
  7577. typeConstraint = genericParam->mTypeConstraint;
  7578. }
  7579. }
  7580. if ((typeConstraint != NULL) &&
  7581. ((typeConstraint->IsDelegate()) || (typeConstraint->IsFunction())))
  7582. {
  7583. BfMethodInstance* invokeMethodInstance = mModule->GetRawMethodInstanceAtIdx(typeConstraint->ToTypeInstance(), 0, "Invoke");
  7584. methodDef = invokeMethodInstance->mMethodDef;
  7585. methodMatcher.mBestMethodInstance = invokeMethodInstance;
  7586. methodMatcher.mBestMethodTypeInstance = invokeMethodInstance->GetOwner();
  7587. methodMatcher.mBestMethodDef = invokeMethodInstance->mMethodDef;
  7588. target = mModule->GetDefaultTypedValue(methodMatcher.mBestMethodTypeInstance);
  7589. isFailurePass = false;
  7590. isIndirectMethodCall = true;
  7591. }
  7592. }
  7593. else if (fieldVal.mType->IsMethodRef())
  7594. {
  7595. auto functionBindResults = prevBindResult.mPrevVal;
  7596. if (functionBindResults != NULL)
  7597. {
  7598. functionBindResults->mOrigTarget = fieldVal;
  7599. }
  7600. origTarget = fieldVal;
  7601. auto methodRefType = (BfMethodRefType*)fieldVal.mType;
  7602. BfMethodInstance* methodInstance = methodRefType->mMethodRef;
  7603. methodDef = methodInstance->mMethodDef;
  7604. if (methodDef->mIsLocalMethod)
  7605. {
  7606. methodMatcher.mBestMethodInstance = mModule->ReferenceExternalMethodInstance(methodInstance);
  7607. }
  7608. else
  7609. {
  7610. BfTypeVector methodGenericArguments;
  7611. if (methodInstance->mMethodInfoEx != NULL)
  7612. methodGenericArguments = methodInstance->mMethodInfoEx->mMethodGenericArguments;
  7613. methodMatcher.mBestMethodInstance = mModule->GetMethodInstance(methodInstance->GetOwner(), methodInstance->mMethodDef, methodGenericArguments);
  7614. }
  7615. methodMatcher.mBestMethodTypeInstance = methodInstance->GetOwner();
  7616. if (methodInstance->HasThis())
  7617. {
  7618. bool failed = false;
  7619. target = DoImplicitArgCapture(targetSrc, methodInstance, -1, failed, BfImplicitParamKind_General, origTarget);
  7620. }
  7621. else if (!methodDef->mIsStatic)
  7622. {
  7623. auto thisType = methodInstance->GetParamType(-1);
  7624. BF_ASSERT(thisType->IsValuelessType());
  7625. target = BfTypedValue(mModule->mBfIRBuilder->GetFakeVal(), methodMatcher.mBestMethodTypeInstance);
  7626. }
  7627. else
  7628. target = BfTypedValue(methodMatcher.mBestMethodTypeInstance);
  7629. methodMatcher.mBypassVirtual = true;
  7630. bypassVirtual = true;
  7631. isFailurePass = false;
  7632. isIndirectMethodCall = true;
  7633. }
  7634. if (methodDef == NULL)
  7635. {
  7636. mModule->Fail(StrFormat("Cannot perform invocation on type '%s'", mModule->TypeToString(fieldVal.mType).c_str()), targetSrc);
  7637. return BfTypedValue();
  7638. }
  7639. }
  7640. }
  7641. // This will flush out any new ambiguity errors from extension methods
  7642. methodMatcher.FlushAmbiguityError();
  7643. if (methodDef == NULL)
  7644. {
  7645. FinishDeferredEvals(argValues);
  7646. auto compiler = mModule->mCompiler;
  7647. if ((compiler->IsAutocomplete()) && (compiler->mResolvePassData->mAutoComplete->CheckFixit(targetSrc)))
  7648. {
  7649. mModule->CheckTypeRefFixit(targetSrc);
  7650. bool wantStatic = !target.mValue;
  7651. if ((targetType == NULL) && (allowImplicitThis))
  7652. {
  7653. targetType = mModule->mCurTypeInstance;
  7654. if (mModule->mCurMethodInstance != NULL)
  7655. wantStatic = mModule->mCurMethodInstance->mMethodDef->mIsStatic;
  7656. }
  7657. if (targetType != NULL)
  7658. {
  7659. auto typeInst = targetType->ToTypeInstance();
  7660. if ((targetType != NULL) && (!methodName.IsEmpty()))
  7661. {
  7662. BfTypeVector paramTypes;
  7663. for (int argIdx = 0; argIdx < (int)argValues.mResolvedArgs.size(); argIdx++)
  7664. {
  7665. auto& resolvedArg = argValues.mResolvedArgs[argIdx];
  7666. paramTypes.Add(resolvedArg.mTypedValue.mType);
  7667. }
  7668. autoComplete->FixitAddMethod(typeInst, methodName, mExpectingType, paramTypes, wantStatic);
  7669. }
  7670. }
  7671. }
  7672. if (methodName.IsEmpty())
  7673. {
  7674. // Would have caused a parsing error
  7675. }
  7676. else if (target.mType != NULL)
  7677. mModule->Fail(StrFormat("Method '%s' does not exist in type '%s'", methodName.c_str(), mModule->TypeToString(target.mType).c_str()), targetSrc);
  7678. else
  7679. mModule->Fail(StrFormat("Method '%s' does not exist", methodName.c_str()), targetSrc);
  7680. return BfTypedValue();
  7681. }
  7682. if ((prevBindResult.mPrevVal != NULL) && (methodMatcher.mMethodCheckCount > 1))
  7683. prevBindResult.mPrevVal->mCheckedMultipleMethods = true;
  7684. BfType* overrideReturnType = NULL;
  7685. BfModuleMethodInstance moduleMethodInstance = GetSelectedMethod(targetSrc, curTypeInst, methodDef, methodMatcher, &overrideReturnType);
  7686. if ((mModule->mAttributeState != NULL) && ((mModule->mAttributeState->mFlags & (BfAttributeState::Flag_StopOnError | BfAttributeState::Flag_HadError)) ==
  7687. (BfAttributeState::Flag_StopOnError | BfAttributeState::Flag_HadError)))
  7688. {
  7689. FinishDeferredEvals(argValues);
  7690. return BfTypedValue();
  7691. }
  7692. if ((moduleMethodInstance.mMethodInstance != NULL) && (!mModule->CheckUseMethodInstance(moduleMethodInstance.mMethodInstance, targetSrc)))
  7693. {
  7694. FinishDeferredEvals(argValues);
  7695. return BfTypedValue();
  7696. }
  7697. if ((mModule->mCurMethodInstance != NULL) && (mModule->mCurMethodInstance->mIsUnspecialized))
  7698. {
  7699. if (methodMatcher.mHasVarArguments)
  7700. {
  7701. BfType* retType = mModule->GetPrimitiveType(BfTypeCode_Var);
  7702. if ((!methodMatcher.mHadVarConflictingReturnType) && (methodMatcher.mBestRawMethodInstance != NULL) && (!methodMatcher.mBestRawMethodInstance->mReturnType->IsUnspecializedTypeVariation()))
  7703. {
  7704. if ((!methodMatcher.mBestRawMethodInstance->mReturnType->IsGenericParam()) ||
  7705. (((BfGenericParamType*)methodMatcher.mBestRawMethodInstance->mReturnType)->mGenericParamKind != BfGenericParamKind_Method))
  7706. retType = methodMatcher.mBestRawMethodInstance->mReturnType;
  7707. }
  7708. return mModule->GetDefaultTypedValue(retType, true, BfDefaultValueKind_Addr);
  7709. }
  7710. }
  7711. if ((bypassVirtual) && (!target.mValue) && (target.mType->IsInterface()))
  7712. {
  7713. target = mModule->GetThis();
  7714. }
  7715. if (!moduleMethodInstance)
  7716. {
  7717. FinishDeferredEvals(argValues);
  7718. return BfTypedValue();
  7719. }
  7720. bool isSkipCall = moduleMethodInstance.mMethodInstance->IsSkipCall(bypassVirtual);
  7721. if ((moduleMethodInstance.mMethodInstance->IsOrInUnspecializedVariation()) && (!mModule->mBfIRBuilder->mIgnoreWrites))
  7722. {
  7723. // Invalid methods such as types with a HasVar tuple generic arg will be marked as mIsUnspecializedVariation and shouldn't actually be called
  7724. FinishDeferredEvals(argValues);
  7725. return mModule->GetDefaultTypedValue(moduleMethodInstance.mMethodInstance->mReturnType, true, BfDefaultValueKind_Addr);
  7726. }
  7727. if (methodDef->IsEmptyPartial())
  7728. {
  7729. // Ignore call
  7730. return mModule->GetDefaultTypedValue(moduleMethodInstance.mMethodInstance->mReturnType, true, BfDefaultValueKind_Addr);
  7731. }
  7732. if ((moduleMethodInstance.mMethodInstance->mMethodDef->mIsStatic) && (moduleMethodInstance.mMethodInstance->GetOwner()->IsInterface()))
  7733. {
  7734. bool isConstrained = false;
  7735. if (target.mType != NULL)
  7736. isConstrained = target.mType->IsGenericParam();
  7737. if ((target.mType == NULL) && ((mModule->mCurMethodInstance->mIsForeignMethodDef) || (mModule->mCurTypeInstance->IsInterface())))
  7738. isConstrained = true;
  7739. // If mIgnoreWrites is off then we skip devirtualization, so allow this
  7740. if ((target.mType != NULL) && (!target.mType->IsInterface()) && (mModule->mBfIRBuilder->mIgnoreWrites))
  7741. isConstrained = true;
  7742. if (!isConstrained)
  7743. {
  7744. if (mModule->mCurTypeInstance->IsInterface())
  7745. {
  7746. if (methodDef->mBody == NULL)
  7747. mModule->Fail(StrFormat("Interface method '%s' must provide a body to be explicitly invoked", mModule->MethodToString(moduleMethodInstance.mMethodInstance).c_str()), targetSrc);
  7748. }
  7749. else
  7750. 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);
  7751. FinishDeferredEvals(argValues);
  7752. return mModule->GetDefaultTypedValue(moduleMethodInstance.mMethodInstance->mReturnType, true, BfDefaultValueKind_Addr);
  7753. }
  7754. }
  7755. // 'base' could really mean 'this' if we're in an extension
  7756. if ((target.IsBase()) && (targetTypeInst == mModule->mCurTypeInstance))
  7757. target.ToThis();
  7758. else
  7759. MakeBaseConcrete(target);
  7760. BfType* callTargetType = curTypeInst;
  7761. if (methodDef->mMethodType == BfMethodType_Extension)
  7762. {
  7763. callTargetType = moduleMethodInstance.mMethodInstance->GetParamType(0);
  7764. if ((callTargetType->IsRef()) && (target.IsAddr()) && (!target.IsReadOnly()) && (target.mType->IsValueType()))
  7765. {
  7766. target = BfTypedValue(target.mValue, mModule->CreateRefType(target.mType));
  7767. }
  7768. }
  7769. BfTypedValue callTarget;
  7770. if (isSkipCall)
  7771. {
  7772. // Just a fake value so we can continue on without generating any code (boxing, conversion, etc)
  7773. if (target)
  7774. {
  7775. if (((target.mType->IsComposite()) || (target.mType->IsTypedPrimitive())))
  7776. {
  7777. if ((moduleMethodInstance.mMethodInstance->mMethodDef->mIsMutating) &&
  7778. ((target.IsReadOnly()) || (!target.IsAddr())))
  7779. {
  7780. String err = StrFormat("call mutating method '%s' on", mModule->MethodToString(moduleMethodInstance.mMethodInstance).c_str());
  7781. CheckModifyResult(target, targetSrc, err.c_str());
  7782. }
  7783. }
  7784. callTarget = BfTypedValue(mModule->mBfIRBuilder->GetFakeVal(), targetTypeInst);
  7785. }
  7786. }
  7787. else if (targetTypeInst == callTargetType)
  7788. {
  7789. if ((target) && (methodDef->HasNoThisSplat()))
  7790. {
  7791. callTarget = mModule->MakeAddressable(target);
  7792. }
  7793. else
  7794. callTarget = target;
  7795. if ((callTarget) && (moduleMethodInstance.mMethodInstance->GetOwner()->IsInterface()))
  7796. {
  7797. auto wantThis = moduleMethodInstance.mMethodInstance->GetParamType(-1);
  7798. if ((callTarget.mType != wantThis) && (wantThis->IsInterface()))
  7799. callTarget = mModule->Cast(targetSrc, callTarget, wantThis, BfCastFlags_Explicit);
  7800. }
  7801. }
  7802. else if (target)
  7803. {
  7804. if (methodMatcher.mFakeConcreteTarget)
  7805. {
  7806. BF_ASSERT(callTargetType->IsInterface());
  7807. callTarget = mModule->GetDefaultTypedValue(mModule->CreateConcreteInterfaceType(callTargetType->ToTypeInstance()));
  7808. }
  7809. else if (((target.mType->IsGenericParam()) || (target.mType->IsConcreteInterfaceType())) && (callTargetType->IsInterface()))
  7810. {
  7811. // Leave as generic
  7812. callTarget = target;
  7813. }
  7814. else
  7815. {
  7816. bool handled = false;
  7817. if ((target.mType->IsTypedPrimitive()) && (callTargetType->IsTypedPrimitive()))
  7818. {
  7819. handled = true;
  7820. callTarget = target;
  7821. }
  7822. else if ((target.mType->IsStructOrStructPtr()) || (target.mType->IsTypedPrimitive()))
  7823. {
  7824. //BF_ASSERT(target.IsAddr());
  7825. if (callTargetType->IsObjectOrInterface())
  7826. {
  7827. // Box it
  7828. callTarget = mModule->Cast(targetSrc, target, callTargetType, BfCastFlags_Explicit);
  7829. handled = true;
  7830. }
  7831. else
  7832. {
  7833. //BF_ASSERT(target.IsAddr() || target.IsSplat() || target.mType->IsPointer());
  7834. }
  7835. }
  7836. else
  7837. target = mModule->LoadValue(target);
  7838. if (!handled)
  7839. {
  7840. // Could we have just unconditionally done this?
  7841. callTarget = mModule->Cast(targetSrc, target, callTargetType, BfCastFlags_Explicit);
  7842. }
  7843. }
  7844. }
  7845. if (isFailurePass)
  7846. {
  7847. BfError* error;
  7848. if (methodMatcher.mMatchFailKind == BfMethodMatcher::MatchFailKind_CheckedMismatch)
  7849. 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);
  7850. else
  7851. error = mModule->Fail(StrFormat("'%s' is inaccessible due to its protection level", mModule->MethodToString(moduleMethodInstance.mMethodInstance).c_str()), targetSrc);
  7852. if (error != NULL)
  7853. {
  7854. if ((error != NULL) && (moduleMethodInstance.mMethodInstance->mMethodDef->mMethodDeclaration != NULL))
  7855. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("See method declaration"), moduleMethodInstance.mMethodInstance->mMethodDef->GetRefNode());
  7856. }
  7857. }
  7858. if ((mModule->mCompiler->mResolvePassData != NULL) && (methodDef != NULL))
  7859. {
  7860. auto identifierNode = BfNodeDynCast<BfIdentifierNode>(targetSrc);
  7861. while (auto qualifiedNameNode = BfNodeDynCast<BfQualifiedNameNode>(identifierNode))
  7862. identifierNode = qualifiedNameNode->mRight;
  7863. if ((identifierNode != NULL) && (methodDef->mIdx >= 0) && (!isIndirectMethodCall))
  7864. {
  7865. mModule->mCompiler->mResolvePassData->HandleMethodReference(identifierNode, moduleMethodInstance.mMethodInstance->GetOwner()->mTypeDef, methodDef);
  7866. auto autoComplete = GetAutoComplete();
  7867. if ((autoComplete != NULL) && (autoComplete->IsAutocompleteNode(identifierNode)))
  7868. {
  7869. autoComplete->SetDefinitionLocation(methodDef->GetRefNode(), true);
  7870. int virtualIdx = moduleMethodInstance.mMethodInstance->mVirtualTableIdx;
  7871. if ((autoComplete->mResolveType == BfResolveType_GoToDefinition) &&
  7872. (virtualIdx != -1) && (targetTypeInst != NULL) && (!targetTypeInst->IsStruct()) && (!targetTypeInst->IsTypedPrimitive()) && (!targetTypeInst->IsInterface()) &&
  7873. // 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
  7874. (targetTypeInst->mVirtualMethodTable.size() != 0))
  7875. {
  7876. auto methodEntry = targetTypeInst->mVirtualMethodTable[virtualIdx];
  7877. if (methodEntry.mImplementingMethod.mMethodNum != -1)
  7878. {
  7879. BfMethodInstance* callingMethodInstance = methodEntry.mImplementingMethod;
  7880. if (callingMethodInstance != NULL)
  7881. {
  7882. auto callingMethodDef = callingMethodInstance->mMethodDef;
  7883. auto callingMethodDeclaration = callingMethodDef->GetMethodDeclaration();
  7884. if ((callingMethodDeclaration != NULL) && (callingMethodDeclaration->mNameNode != NULL))
  7885. autoComplete->SetDefinitionLocation(callingMethodDeclaration->mNameNode, true);
  7886. }
  7887. }
  7888. }
  7889. if (autoComplete->mDefType == NULL)
  7890. {
  7891. autoComplete->mDefMethod = methodDef;
  7892. autoComplete->mDefType = moduleMethodInstance.mMethodInstance->GetOwner()->mTypeDef;
  7893. }
  7894. if (autoComplete->mResolveType == BfResolveType_GetResultString)
  7895. {
  7896. autoComplete->mResultString = ":";
  7897. autoComplete->mResultString += mModule->MethodToString(moduleMethodInstance.mMethodInstance);
  7898. auto methodDecl = moduleMethodInstance.mMethodInstance->mMethodDef->GetMethodDeclaration();
  7899. if ((methodDecl != NULL) && (methodDecl->mDocumentation != NULL))
  7900. {
  7901. autoComplete->mResultString += "\x03";
  7902. methodDecl->mDocumentation->GetDocString(autoComplete->mResultString);
  7903. }
  7904. }
  7905. }
  7906. }
  7907. }
  7908. // This was causing forward-backward-forward steps when we just used 'targetSrc'. Using closeParen is undesirable because most of the time
  7909. // we DO just want it to just go to the targetSrc... do we even need this?
  7910. /*if (auto invokeExpr = BfNodeDynCast<BfInvocationExpression>(targetSrc->mParent))
  7911. {
  7912. // We set the srcPos to the close paren right before the call so we keep a forward progression of src positions in the case
  7913. // where some of the params are method calls and such
  7914. if (invokeExpr->mCloseParen != NULL)
  7915. mModule->UpdateExprSrcPos(invokeExpr->mCloseParen);
  7916. else
  7917. mModule->UpdateExprSrcPos(targetSrc);
  7918. }
  7919. else
  7920. mModule->UpdateExprSrcPos(targetSrc);*/
  7921. if (!mModule->mBfIRBuilder->mIgnoreWrites)
  7922. {
  7923. //BF_ASSERT(!callTarget.mValue.IsFake());
  7924. }
  7925. prevBindResult.Restore();
  7926. // Check mut
  7927. if ((callTarget.mType != NULL) &&
  7928. (callTarget.mType->IsGenericParam()) &&
  7929. ((!callTarget.IsAddr()) || (callTarget.IsReadOnly())) &&
  7930. (callTarget.mKind != BfTypedValueKind_MutableValue) &&
  7931. (moduleMethodInstance.mMethodInstance->mMethodDef->mIsMutating))
  7932. {
  7933. auto genericParamInstance = mModule->GetGenericParamInstance((BfGenericParamType*)callTarget.mType);
  7934. bool needsMut = true;
  7935. if ((genericParamInstance->mGenericParamFlags & (BfGenericParamFlag_StructPtr | BfGenericParamFlag_Class | BfGenericParamFlag_Var)) != 0)
  7936. needsMut = false;
  7937. if (genericParamInstance->mTypeConstraint != NULL)
  7938. {
  7939. auto typeConstaintTypeInstance = genericParamInstance->mTypeConstraint->ToTypeInstance();
  7940. if ((typeConstaintTypeInstance != NULL) && (!typeConstaintTypeInstance->IsComposite()))
  7941. needsMut = false;
  7942. }
  7943. if ((mFunctionBindResult != NULL) && (mFunctionBindResult->mSkipMutCheck))
  7944. needsMut = false;
  7945. if (needsMut)
  7946. {
  7947. String err = StrFormat("call mutating method '%s' on", mModule->MethodToString(moduleMethodInstance.mMethodInstance).c_str());
  7948. CheckModifyResult(callTarget, targetSrc, err.c_str(), true);
  7949. }
  7950. }
  7951. // Check mut on interface
  7952. if ((callTarget.mType != NULL) &&
  7953. (callTarget.mType->IsInterface()) &&
  7954. (target.IsThis()) &&
  7955. (mModule->mCurTypeInstance) &&
  7956. (!mModule->mCurMethodInstance->mMethodDef->mIsMutating) &&
  7957. (methodDef->mIsMutating))
  7958. {
  7959. mModule->Fail(StrFormat("Cannot call mutating method '%s' within default interface method '%s'. Consider adding 'mut' specifier to this method.",
  7960. mModule->MethodToString(moduleMethodInstance.mMethodInstance).c_str(), mModule->MethodToString(mModule->mCurMethodInstance).c_str()), targetSrc);
  7961. }
  7962. BfTypedValue result;
  7963. BfTypedValue argCascade;
  7964. //
  7965. {
  7966. SetAndRestoreValue<BfEvalExprFlags> prevEvalExprFlag(mBfEvalExprFlags);
  7967. if ((mModule->mAttributeState != NULL) && (mModule->mAttributeState->mCustomAttributes != NULL) && (mModule->mAttributeState->mCustomAttributes->Contains(mModule->mCompiler->mConstEvalAttributeTypeDef)))
  7968. {
  7969. mModule->mAttributeState->mUsed = true;
  7970. mBfEvalExprFlags = (BfEvalExprFlags)(mBfEvalExprFlags | BfEvalExprFlags_Comptime);
  7971. }
  7972. else if ((moduleMethodInstance.mMethodInstance->mComptimeFlags & BfComptimeFlag_ConstEval) != 0)
  7973. {
  7974. mBfEvalExprFlags = (BfEvalExprFlags)(mBfEvalExprFlags | BfEvalExprFlags_Comptime);
  7975. }
  7976. else if (((moduleMethodInstance.mMethodInstance->mComptimeFlags & BfComptimeFlag_Comptime) != 0) && (!mModule->mIsComptimeModule))
  7977. {
  7978. if ((mModule->mCurMethodInstance == NULL) || (mModule->mCurMethodInstance->mComptimeFlags == BfComptimeFlag_None))
  7979. mBfEvalExprFlags = (BfEvalExprFlags)(mBfEvalExprFlags | BfEvalExprFlags_Comptime);
  7980. }
  7981. if (((moduleMethodInstance.mMethodInstance->mComptimeFlags & BfComptimeFlag_OnlyFromComptime) != 0) &&
  7982. ((mBfEvalExprFlags & BfEvalExprFlags_Comptime) != 0) &&
  7983. ((mModule->mCurMethodInstance == NULL) || (mModule->mCurMethodInstance->mComptimeFlags == BfComptimeFlag_None)) &&
  7984. (!mModule->mIsComptimeModule))
  7985. {
  7986. 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);
  7987. }
  7988. BfCreateFallFlags subCallFlags = BfCreateFallFlags_None;
  7989. if (bypassVirtual)
  7990. subCallFlags = (BfCreateFallFlags)(subCallFlags | BfCreateFallFlags_BypassVirtual);
  7991. if (skipThis)
  7992. subCallFlags = (BfCreateFallFlags)(subCallFlags | BfCreateFallFlags_SkipThis);
  7993. result = CreateCall(targetSrc, callTarget, origTarget, methodDef, moduleMethodInstance, subCallFlags, argValues.mResolvedArgs, &argCascade);
  7994. }
  7995. if (overrideReturnType != NULL)
  7996. {
  7997. BF_ASSERT(moduleMethodInstance.mMethodInstance->mIsUnspecializedVariation);
  7998. result = mModule->GetDefaultTypedValue(overrideReturnType, false, BfDefaultValueKind_Addr);
  7999. }
  8000. if (result)
  8001. {
  8002. if (result.mType->IsRef())
  8003. result = mModule->RemoveRef(result);
  8004. }
  8005. PerformCallChecks(moduleMethodInstance.mMethodInstance, targetSrc);
  8006. if (result)
  8007. {
  8008. bool discardedReturnValue = mUsedAsStatement;
  8009. if (discardedReturnValue)
  8010. {
  8011. auto _ShowDiscardWaring = [&](const String& text, BfCustomAttributes* customAttributes, BfIRConstHolder* constHolder, BfAstNode* refNode)
  8012. {
  8013. if (customAttributes != NULL)
  8014. {
  8015. auto customAttribute = customAttributes->Get(mModule->mCompiler->mNoDiscardAttributeTypeDef);
  8016. if (!customAttribute->mCtorArgs.IsEmpty())
  8017. {
  8018. String* str = mModule->GetStringPoolString(customAttribute->mCtorArgs[0], constHolder);
  8019. if ((str != NULL) && (!str->IsEmpty()))
  8020. {
  8021. mModule->Warn(0, text + ": " + *str, targetSrc);
  8022. return;
  8023. }
  8024. }
  8025. }
  8026. mModule->Warn(0, text, targetSrc);
  8027. };
  8028. bool showedWarning = false;
  8029. if (moduleMethodInstance.mMethodInstance->mMethodDef->mIsNoDiscard)
  8030. {
  8031. _ShowDiscardWaring("Discarding return value of method with [NoDiscard] attribute", moduleMethodInstance.mMethodInstance->GetCustomAttributes(),
  8032. moduleMethodInstance.mMethodInstance->GetOwner()->mConstHolder, targetSrc);
  8033. showedWarning = true;
  8034. }
  8035. auto typeInst = result.mType->ToTypeInstance();
  8036. if (typeInst != NULL)
  8037. {
  8038. if ((typeInst->mTypeDef->mIsNoDiscard) && (!showedWarning))
  8039. {
  8040. _ShowDiscardWaring("Discarding return value whose type has [NoDiscard] attribute", typeInst->mCustomAttributes, typeInst->mConstHolder, targetSrc);
  8041. }
  8042. BfModuleMethodInstance moduleMethodInstance = mModule->GetMethodByName(typeInst, "ReturnValueDiscarded", 0, true);
  8043. if (moduleMethodInstance)
  8044. {
  8045. auto wasGetDefinition = (autoComplete != NULL) && (autoComplete->mIsGetDefinition);
  8046. if (wasGetDefinition)
  8047. autoComplete->mIsGetDefinition = false;
  8048. result = mModule->MakeAddressable(result);
  8049. BfResolvedArgs resolvedArgs;
  8050. MatchMethod(targetSrc, NULL, result, false, false, "ReturnValueDiscarded", resolvedArgs, NULL);
  8051. if (wasGetDefinition)
  8052. autoComplete->mIsGetDefinition = true;
  8053. }
  8054. }
  8055. }
  8056. }
  8057. if (argCascade)
  8058. {
  8059. if (argCascade.mType->IsRef())
  8060. argCascade = mModule->RemoveRef(argCascade);
  8061. result = argCascade;
  8062. }
  8063. if (result)
  8064. {
  8065. if (result.mType->IsSelf())
  8066. {
  8067. if (methodMatcher.mSelfType != NULL)
  8068. {
  8069. BF_ASSERT(mModule->IsInGeneric());
  8070. result = mModule->GetDefaultTypedValue(methodMatcher.mSelfType);
  8071. }
  8072. else
  8073. {
  8074. // Will be an error
  8075. result = mModule->GetDefaultTypedValue(methodMatcher.mBestMethodTypeInstance);
  8076. }
  8077. }
  8078. }
  8079. return result;
  8080. }
  8081. void BfExprEvaluator::LookupQualifiedName(BfQualifiedNameNode* nameNode, bool ignoreInitialError, bool* hadError)
  8082. {
  8083. BfIdentifierNode* nameLeft = nameNode->mLeft;
  8084. BfIdentifierNode* nameRight = nameNode->mRight;
  8085. StringT<64> fieldName;
  8086. if (nameNode->mRight != NULL)
  8087. nameNode->mRight->ToString(fieldName);
  8088. bool wasBaseLookup = false;
  8089. if (auto qualifiedLeftName = BfNodeDynCast<BfQualifiedNameNode>(nameNode->mLeft))
  8090. {
  8091. if (CheckIsBase(qualifiedLeftName->mRight))
  8092. {
  8093. wasBaseLookup = true;
  8094. auto type = mModule->ResolveTypeRef(qualifiedLeftName->mLeft, NULL);
  8095. if (type == NULL)
  8096. return;
  8097. auto fieldName = nameNode->mRight->ToString();
  8098. auto target = mModule->GetThis();
  8099. target.mType = type;
  8100. mResult = LookupField(nameNode->mRight, target, fieldName);
  8101. if ((mPropDef != NULL) && (mPropDef->IsVirtual()))
  8102. mPropDefBypassVirtual = true;
  8103. return;
  8104. }
  8105. }
  8106. if (!wasBaseLookup)
  8107. mResult = LookupIdentifier(nameNode->mLeft, ignoreInitialError, hadError);
  8108. GetResult();
  8109. if (!mResult)
  8110. {
  8111. if (!ignoreInitialError)
  8112. mModule->Fail("Identifier not found", nameNode->mLeft);
  8113. return;
  8114. }
  8115. if (mResult.mType->IsObject())
  8116. {
  8117. mResult = mModule->LoadValue(mResult, 0, mIsVolatileReference);
  8118. }
  8119. else if ((mResult.mType->IsPointer()) && mResult.mType->IsStructOrStructPtr())
  8120. {
  8121. BfPointerType* structPtrType = (BfPointerType*)mResult.mType;
  8122. mResult = mModule->LoadValue(mResult, 0, mIsVolatileReference);
  8123. mResult.mType = structPtrType->mElementType;
  8124. if (mResult.mKind == BfTypedValueKind_ThisValue)
  8125. mResult.mKind = BfTypedValueKind_ThisAddr;
  8126. else
  8127. mResult.mKind = BfTypedValueKind_Addr;
  8128. }
  8129. mIsVolatileReference = false;
  8130. mIsHeapReference = false;
  8131. if (!mResult)
  8132. return;
  8133. auto origResult = mResult;
  8134. auto lookupType = BindGenericType(nameNode, mResult.mType);
  8135. if (mResult.mType->IsVar())
  8136. {
  8137. mResult = BfTypedValue(mModule->GetDefaultValue(mResult.mType), mResult.mType, true);
  8138. return;
  8139. }
  8140. if ((!mResult.mType->IsTypeInstance()) && (!mResult.mType->IsGenericParam()))
  8141. {
  8142. if (hadError != NULL)
  8143. *hadError = true;
  8144. mModule->Fail(StrFormat("Type '%s' has no fields", mModule->TypeToString(mResult.mType).c_str()), nameNode->mLeft);
  8145. mResult = BfTypedValue();
  8146. return;
  8147. }
  8148. BfTypedValue lookupVal = mResult;
  8149. mResult = LookupField(nameNode->mRight, lookupVal, fieldName);
  8150. if ((!mResult) && (mPropDef == NULL) && (lookupType->IsGenericParam()))
  8151. {
  8152. auto genericParamInst = mModule->GetGenericParamInstance((BfGenericParamType*)lookupType);
  8153. SizedArray<BfTypeInstance*, 8> searchConstraints;
  8154. for (auto ifaceConstraint : genericParamInst->mInterfaceConstraints)
  8155. {
  8156. if (!searchConstraints.Contains(ifaceConstraint))
  8157. {
  8158. searchConstraints.push_back(ifaceConstraint);
  8159. for (auto& innerIFaceEntry : ifaceConstraint->mInterfaces)
  8160. {
  8161. auto innerIFace = innerIFaceEntry.mInterfaceType;
  8162. if (!searchConstraints.Contains(innerIFace))
  8163. {
  8164. searchConstraints.push_back(innerIFace);
  8165. }
  8166. }
  8167. }
  8168. }
  8169. BfTypedValue prevTarget;
  8170. BfPropertyDef* prevDef = NULL;
  8171. for (auto ifaceConstraint : searchConstraints)
  8172. {
  8173. BfTypedValue lookupVal = BfTypedValue(mModule->mBfIRBuilder->GetFakeVal(), ifaceConstraint);
  8174. mResult = LookupField(nameNode->mRight, lookupVal, fieldName);
  8175. if (mPropDef != NULL)
  8176. {
  8177. if (prevDef != NULL)
  8178. {
  8179. bool isBetter = mModule->TypeIsSubTypeOf(mPropTarget.mType->ToTypeInstance(), prevTarget.mType->ToTypeInstance());
  8180. bool isWorse = mModule->TypeIsSubTypeOf(prevTarget.mType->ToTypeInstance(), mPropTarget.mType->ToTypeInstance());
  8181. if ((isWorse) && (!isBetter))
  8182. continue;
  8183. if (isBetter == isWorse)
  8184. {
  8185. auto error = mModule->Fail("Ambiguous property reference", nameNode->mRight);
  8186. if (error != NULL)
  8187. {
  8188. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("'%s' has a candidate", mModule->TypeToString(prevTarget.mType).c_str()), prevDef->GetRefNode());
  8189. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("'%s' has a candidate", mModule->TypeToString(mPropTarget.mType).c_str()), mPropDef->GetRefNode());
  8190. }
  8191. }
  8192. }
  8193. prevDef = mPropDef;
  8194. prevTarget = mPropTarget;
  8195. }
  8196. }
  8197. /*if ((mResult) || (mPropDef != NULL))
  8198. break;*/
  8199. }
  8200. if (mPropDef != NULL)
  8201. {
  8202. mOrigPropTarget = origResult;
  8203. if (((CheckIsBase(nameNode->mLeft)) || (wasBaseLookup)) && (mPropDef->IsVirtual()))
  8204. mPropDefBypassVirtual = true;
  8205. }
  8206. if ((mResult) || (mPropDef != NULL))
  8207. return;
  8208. if (hadError != NULL)
  8209. *hadError = true;
  8210. BfTypeInstance* typeInst = lookupType->ToTypeInstance();
  8211. auto compiler = mModule->mCompiler;
  8212. if ((typeInst != NULL) && (compiler->IsAutocomplete()) && (compiler->mResolvePassData->mAutoComplete->CheckFixit(nameNode->mRight)))
  8213. {
  8214. FixitAddMember(typeInst, mExpectingType, nameNode->mRight->ToString(), false);
  8215. }
  8216. mModule->Fail("Unable to find member", nameNode->mRight);
  8217. }
  8218. void BfExprEvaluator::LookupQualifiedName(BfAstNode* nameNode, BfIdentifierNode* nameLeft, BfIdentifierNode* nameRight, bool ignoreInitialError, bool* hadError)
  8219. {
  8220. String fieldName;
  8221. if (nameRight != NULL)
  8222. fieldName = nameRight->ToString();
  8223. bool wasBaseLookup = false;
  8224. if (auto qualifiedLeftName = BfNodeDynCast<BfQualifiedNameNode>(nameLeft))
  8225. {
  8226. if (CheckIsBase(qualifiedLeftName->mRight))
  8227. {
  8228. wasBaseLookup = true;
  8229. auto type = mModule->ResolveTypeRef(qualifiedLeftName->mLeft, NULL);
  8230. if (type == NULL)
  8231. return;
  8232. auto fieldName = nameRight->ToString();
  8233. auto target = mModule->GetThis();
  8234. target.mType = type;
  8235. mResult = LookupField(nameRight, target, fieldName);
  8236. if ((mPropDef != NULL) && (mPropDef->IsVirtual()))
  8237. mPropDefBypassVirtual = true;
  8238. return;
  8239. }
  8240. }
  8241. if (!wasBaseLookup)
  8242. {
  8243. mResult = LookupIdentifier(nameLeft, ignoreInitialError, hadError);
  8244. if ((mResult) && (!mResult.mType->IsComposite()))
  8245. CheckResultForReading(mResult);
  8246. }
  8247. GetResult();
  8248. if (!mResult)
  8249. {
  8250. if (!ignoreInitialError)
  8251. mModule->Fail("Identifier not found", nameLeft);
  8252. return;
  8253. }
  8254. if (mResult.mType->IsObject())
  8255. {
  8256. mResult = mModule->LoadValue(mResult, 0, mIsVolatileReference);
  8257. }
  8258. else if ((mResult.mType->IsPointer()) && mResult.mType->IsStructOrStructPtr())
  8259. {
  8260. BfPointerType* structPtrType = (BfPointerType*)mResult.mType;
  8261. mResult = mModule->LoadValue(mResult, 0, mIsVolatileReference);
  8262. mResult.mType = structPtrType->mElementType;
  8263. if (mResult.mKind == BfTypedValueKind_ThisValue)
  8264. mResult.mKind = BfTypedValueKind_ThisAddr;
  8265. else
  8266. mResult.mKind = BfTypedValueKind_Addr;
  8267. }
  8268. mIsVolatileReference = false;
  8269. mIsHeapReference = false;
  8270. if (!mResult)
  8271. return;
  8272. if (mResult.mType->IsAllocType())
  8273. mResult.mType = mResult.mType->GetUnderlyingType();
  8274. auto origResult = mResult;
  8275. if (mResult.mType->IsVar())
  8276. {
  8277. mResult = BfTypedValue(mModule->GetDefaultValue(mResult.mType), mResult.mType, true);
  8278. return;
  8279. }
  8280. if ((!mResult.mType->IsTypeInstance()) && (!mResult.mType->IsGenericParam()))
  8281. {
  8282. if (mResult.mType->IsSizedArray())
  8283. {
  8284. if (mResult.mType->IsValuelessType())
  8285. {
  8286. mResult.mType = mModule->GetWrappedStructType(mResult.mType);
  8287. mResult.mValue = mModule->mBfIRBuilder->GetFakeVal();
  8288. }
  8289. else
  8290. {
  8291. mResult = mModule->MakeAddressable(mResult);
  8292. mResult.mType = mModule->GetWrappedStructType(mResult.mType);
  8293. mResult.mValue = mModule->mBfIRBuilder->CreateBitCast(mResult.mValue, mModule->mBfIRBuilder->MapTypeInstPtr(mResult.mType->ToTypeInstance()));
  8294. }
  8295. }
  8296. else if (mResult.mType->IsWrappableType())
  8297. {
  8298. mResult.mType = mModule->GetWrappedStructType(mResult.mType);
  8299. }
  8300. else
  8301. {
  8302. if (hadError != NULL)
  8303. *hadError = true;
  8304. mModule->Fail(StrFormat("Type '%s' has no fields", mModule->TypeToString(mResult.mType).c_str()), nameLeft);
  8305. mResult = BfTypedValue();
  8306. return;
  8307. }
  8308. }
  8309. BfTypedValue lookupVal = mResult;
  8310. auto lookupType = BindGenericType(nameNode, mResult.mType);
  8311. if ((lookupType->IsGenericParam()) && (!mResult.mType->IsGenericParam()))
  8312. {
  8313. // Try to lookup from generic binding
  8314. mResult = LookupField(nameRight, BfTypedValue(mModule->mBfIRBuilder->GetFakeVal(), lookupType), fieldName, BfLookupFieldFlag_BindOnly);
  8315. if (mPropDef != NULL)
  8316. {
  8317. mOrigPropTarget = lookupVal;
  8318. return;
  8319. }
  8320. }
  8321. if (mPropDef == NULL)
  8322. mResult = LookupField(nameRight, lookupVal, fieldName, CheckIsBase(nameLeft) ? BfLookupFieldFlag_BaseLookup : BfLookupFieldFlag_None);
  8323. if ((!mResult) && (mPropDef == NULL) && (lookupType->IsGenericParam()))
  8324. {
  8325. auto genericParamInst = mModule->GetGenericParamInstance((BfGenericParamType*)lookupType);
  8326. SizedArray<BfTypeInstance*, 8> searchConstraints;
  8327. for (auto ifaceConstraint : genericParamInst->mInterfaceConstraints)
  8328. {
  8329. if (!searchConstraints.Contains(ifaceConstraint))
  8330. {
  8331. searchConstraints.push_back(ifaceConstraint);
  8332. for (auto& innerIFaceEntry : ifaceConstraint->mInterfaces)
  8333. {
  8334. auto innerIFace = innerIFaceEntry.mInterfaceType;
  8335. if (!searchConstraints.Contains(innerIFace))
  8336. {
  8337. searchConstraints.push_back(innerIFace);
  8338. }
  8339. }
  8340. }
  8341. }
  8342. BfTypedValue prevTarget;
  8343. BfPropertyDef* prevDef = NULL;
  8344. for (auto ifaceConstraint : searchConstraints)
  8345. {
  8346. BfTypedValue lookupVal = BfTypedValue(mModule->mBfIRBuilder->GetFakeVal(), ifaceConstraint);
  8347. mResult = LookupField(nameRight, lookupVal, fieldName);
  8348. if (mPropDef != NULL)
  8349. {
  8350. if (prevDef != NULL)
  8351. {
  8352. bool isBetter = mModule->TypeIsSubTypeOf(mPropTarget.mType->ToTypeInstance(), prevTarget.mType->ToTypeInstance());
  8353. bool isWorse = mModule->TypeIsSubTypeOf(prevTarget.mType->ToTypeInstance(), mPropTarget.mType->ToTypeInstance());
  8354. if ((isWorse) && (!isBetter))
  8355. continue;
  8356. if (isBetter == isWorse)
  8357. {
  8358. auto error = mModule->Fail("Ambiguous property reference", nameRight);
  8359. if (error != NULL)
  8360. {
  8361. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("'%s' has a candidate", mModule->TypeToString(prevTarget.mType).c_str()), prevDef->GetRefNode());
  8362. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("'%s' has a candidate", mModule->TypeToString(mPropTarget.mType).c_str()), mPropDef->GetRefNode());
  8363. }
  8364. }
  8365. }
  8366. prevDef = mPropDef;
  8367. prevTarget = mPropTarget;
  8368. }
  8369. }
  8370. }
  8371. if (mPropDef != NULL)
  8372. {
  8373. mOrigPropTarget = origResult;
  8374. if ((CheckIsBase(nameLeft)) || (wasBaseLookup))
  8375. {
  8376. if (mPropDef->IsVirtual())
  8377. mPropDefBypassVirtual = true;
  8378. }
  8379. }
  8380. if ((mResult) || (mPropDef != NULL))
  8381. return;
  8382. if (hadError != NULL)
  8383. *hadError = true;
  8384. BfTypeInstance* typeInst = lookupType->ToTypeInstance();
  8385. auto compiler = mModule->mCompiler;
  8386. if ((typeInst != NULL) && (compiler->IsAutocomplete()) && (compiler->mResolvePassData->mAutoComplete->CheckFixit(nameRight)))
  8387. {
  8388. FixitAddMember(typeInst, mExpectingType, nameRight->ToString(), false);
  8389. }
  8390. mModule->Fail("Unable to find member", nameRight);
  8391. }
  8392. void BfExprEvaluator::LookupQualifiedStaticField(BfQualifiedNameNode* nameNode, bool ignoreIdentifierNotFoundError)
  8393. {
  8394. // Lookup left side as a type
  8395. {
  8396. BfType* type = NULL;
  8397. {
  8398. type = mModule->ResolveTypeRef(nameNode->mLeft, NULL, BfPopulateType_Data, BfResolveTypeRefFlag_AllowRef);
  8399. mModule->CheckTypeRefFixit(nameNode->mLeft);
  8400. }
  8401. if (type != NULL)
  8402. {
  8403. BfTypedValue lookupType;
  8404. if (type->IsWrappableType())
  8405. lookupType = BfTypedValue(mModule->GetWrappedStructType(type));
  8406. else
  8407. lookupType = BfTypedValue(type);
  8408. auto findName = nameNode->mRight->ToString();
  8409. /*if (findName == "base")
  8410. {
  8411. mResult = BfTypedValue(lookupType);
  8412. return;
  8413. }*/
  8414. mResult = LookupField(nameNode->mRight, lookupType, findName);
  8415. if ((mResult) || (mPropDef != NULL))
  8416. return;
  8417. if (lookupType.mType != NULL)
  8418. {
  8419. BfTypeInstance* typeInst = lookupType.mType->ToTypeInstance();
  8420. auto compiler = mModule->mCompiler;
  8421. if ((typeInst != NULL) && (compiler->IsAutocomplete()) && (compiler->mResolvePassData->mAutoComplete->CheckFixit(nameNode->mRight)))
  8422. {
  8423. FixitAddMember(typeInst, mExpectingType, nameNode->mRight->ToString(), true);
  8424. }
  8425. }
  8426. if ((mBfEvalExprFlags & BfEvalExprFlags_NoLookupError) == 0)
  8427. mModule->Fail("Field not found", nameNode->mRight);
  8428. return;
  8429. }
  8430. }
  8431. String fieldName = nameNode->mRight->ToString();
  8432. if (auto qualifiedLeftName = BfNodeDynCast<BfQualifiedNameNode>(nameNode->mLeft))
  8433. LookupQualifiedStaticField(qualifiedLeftName, true);
  8434. else if (auto leftName = BfNodeDynCast<BfIdentifierNode>(nameNode->mLeft))
  8435. {
  8436. mResult = LookupIdentifier(leftName);
  8437. }
  8438. GetResult();
  8439. if (!mResult)
  8440. {
  8441. if (!ignoreIdentifierNotFoundError)
  8442. mModule->Fail("Identifier not found", nameNode->mLeft);
  8443. return;
  8444. }
  8445. if (mResult.mType->IsObject())
  8446. {
  8447. mResult = mModule->LoadValue(mResult);
  8448. }
  8449. else if ((mResult.mType->IsPointer()) && mResult.mType->IsStructOrStructPtr())
  8450. {
  8451. BfPointerType* structPtrType = (BfPointerType*) mResult.mType;
  8452. mResult = mModule->LoadValue(mResult);
  8453. mResult.mType = structPtrType->mElementType;
  8454. }
  8455. if (!mResult)
  8456. return;
  8457. if (!mResult.mType->IsTypeInstance())
  8458. {
  8459. mModule->Fail(StrFormat("Type '%s' has no fields", mModule->TypeToString(mResult.mType).c_str()), nameNode->mLeft);
  8460. return;
  8461. }
  8462. mResult = LookupField(nameNode->mRight, mResult, fieldName);
  8463. if ((mResult) || (mPropDef != NULL))
  8464. return;
  8465. mModule->Fail("Unable to find member", nameNode->mRight);
  8466. }
  8467. void BfExprEvaluator::LookupQualifiedStaticField(BfAstNode* nameNode, BfIdentifierNode* nameLeft, BfIdentifierNode* nameRight, bool ignoreIdentifierNotFoundError)
  8468. {
  8469. // Lookup left side as a type
  8470. {
  8471. BfType* type = mModule->ResolveTypeRef(nameLeft, NULL, BfPopulateType_Declaration, BfResolveTypeRefFlag_IgnoreLookupError);
  8472. if (type != NULL)
  8473. {
  8474. BfTypedValue lookupType;
  8475. if (type->IsWrappableType())
  8476. lookupType = BfTypedValue(mModule->GetWrappedStructType(type));
  8477. else
  8478. lookupType = BfTypedValue(type);
  8479. auto findName = nameRight->ToString();
  8480. if ((lookupType.mType != NULL) && (lookupType.mType->IsGenericParam()))
  8481. {
  8482. auto genericParamInstance = mModule->GetGenericParamInstance((BfGenericParamType*)lookupType.mType);
  8483. if (genericParamInstance->mTypeConstraint != NULL)
  8484. {
  8485. mResult = LookupField(nameRight, BfTypedValue(genericParamInstance->mTypeConstraint), findName);
  8486. if ((mResult) || (mPropDef != NULL))
  8487. return;
  8488. }
  8489. for (auto constraint : genericParamInstance->mInterfaceConstraints)
  8490. {
  8491. mResult = LookupField(nameRight, BfTypedValue(constraint), findName);
  8492. if ((mResult) || (mPropDef != NULL))
  8493. return;
  8494. }
  8495. }
  8496. /*if (findName == "base")
  8497. {
  8498. mResult = BfTypedValue(lookupType);
  8499. return;
  8500. }*/
  8501. mResult = LookupField(nameRight, lookupType, findName);
  8502. if ((mResult) || (mPropDef != NULL))
  8503. return;
  8504. if (lookupType.mType != NULL)
  8505. {
  8506. BfTypeInstance* typeInst = lookupType.mType->ToTypeInstance();
  8507. auto compiler = mModule->mCompiler;
  8508. if ((typeInst != NULL) && (compiler->IsAutocomplete()) && (compiler->mResolvePassData->mAutoComplete->CheckFixit(nameRight)))
  8509. {
  8510. FixitAddMember(typeInst, mExpectingType, nameRight->ToString(), true);
  8511. }
  8512. }
  8513. if ((mBfEvalExprFlags & BfEvalExprFlags_NoLookupError) == 0)
  8514. mModule->Fail("Field not found", nameRight);
  8515. return;
  8516. }
  8517. }
  8518. String fieldName = nameRight->ToString();
  8519. if (auto qualifiedLeftName = BfNodeDynCast<BfQualifiedNameNode>(nameLeft))
  8520. LookupQualifiedStaticField(qualifiedLeftName, qualifiedLeftName->mLeft, qualifiedLeftName->mRight, true);
  8521. else if (auto leftName = BfNodeDynCast<BfIdentifierNode>(nameLeft))
  8522. {
  8523. mResult = LookupIdentifier(leftName);
  8524. }
  8525. GetResult();
  8526. if (!mResult)
  8527. {
  8528. if (!ignoreIdentifierNotFoundError)
  8529. mModule->Fail("Identifier not found", nameLeft);
  8530. return;
  8531. }
  8532. if (mResult.mType->IsObject())
  8533. {
  8534. mResult = mModule->LoadValue(mResult);
  8535. }
  8536. else if ((mResult.mType->IsPointer()) && mResult.mType->IsStructOrStructPtr())
  8537. {
  8538. BfPointerType* structPtrType = (BfPointerType*)mResult.mType;
  8539. mResult = mModule->LoadValue(mResult);
  8540. mResult = BfTypedValue(mResult.mValue, structPtrType->mElementType, true);
  8541. }
  8542. if (!mResult)
  8543. return;
  8544. if (!mResult.mType->IsTypeInstance())
  8545. {
  8546. if (mResult.mType->IsSizedArray())
  8547. {
  8548. mResult.mType = mModule->GetWrappedStructType(mResult.mType);
  8549. mResult.mValue = mModule->mBfIRBuilder->CreateBitCast(mResult.mValue, mModule->mBfIRBuilder->MapTypeInstPtr(mResult.mType->ToTypeInstance()));
  8550. }
  8551. else if (mResult.mType->IsWrappableType())
  8552. {
  8553. mResult.mType = mModule->GetWrappedStructType(mResult.mType);
  8554. }
  8555. else
  8556. {
  8557. mModule->Fail(StrFormat("Type '%s' has no fields", mModule->TypeToString(mResult.mType).c_str()), nameLeft);
  8558. return;
  8559. }
  8560. }
  8561. mResult = LookupField(nameRight, mResult, fieldName);
  8562. if ((mResult) || (mPropDef != NULL))
  8563. return;
  8564. mModule->CheckTypeRefFixit(nameLeft);
  8565. mModule->Fail("Unable to find member", nameRight);
  8566. }
  8567. void BfExprEvaluator::Visit(BfQualifiedNameNode* nameNode)
  8568. {
  8569. auto autoComplete = GetAutoComplete();
  8570. if (autoComplete != NULL)
  8571. {
  8572. autoComplete->CheckMemberReference(nameNode->mLeft, nameNode->mDot, nameNode->mRight);
  8573. }
  8574. bool hadError = false;
  8575. LookupQualifiedName(nameNode, nameNode->mLeft, nameNode->mRight, true, &hadError);
  8576. if ((mResult) || (mPropDef != NULL))
  8577. return;
  8578. if (hadError)
  8579. return;
  8580. LookupQualifiedStaticField(nameNode, nameNode->mLeft, nameNode->mRight, false);
  8581. }
  8582. void BfExprEvaluator::Visit(BfThisExpression* thisExpr)
  8583. {
  8584. mResult = mModule->GetThis();
  8585. if (!mResult)
  8586. {
  8587. mModule->Fail("Static methods don't have 'this'", thisExpr);
  8588. return;
  8589. }
  8590. auto autoComplete = GetAutoComplete();
  8591. if ((autoComplete != NULL) && (autoComplete->IsAutocompleteNode(thisExpr)))
  8592. autoComplete->SetDefinitionLocation(mModule->mCurTypeInstance->mTypeDef->GetRefNode());
  8593. mResultLocalVar = mModule->GetThisVariable();
  8594. mResultFieldInstance = NULL;
  8595. }
  8596. void BfExprEvaluator::Visit(BfBaseExpression* baseExpr)
  8597. {
  8598. mResult = mModule->GetThis();
  8599. if (!mResult)
  8600. {
  8601. mModule->Fail("Static methods don't have 'base'", baseExpr);
  8602. return;
  8603. }
  8604. auto baseType = mModule->mCurTypeInstance->mBaseType;
  8605. if (baseType == NULL)
  8606. baseType = mModule->mContext->mBfObjectType;
  8607. auto autoComplete = GetAutoComplete();
  8608. if ((autoComplete != NULL) && (autoComplete->IsAutocompleteNode(baseExpr)))
  8609. autoComplete->SetDefinitionLocation(baseType->mTypeDef->GetRefNode());
  8610. mModule->PopulateType(baseType, BfPopulateType_Data);
  8611. mResult = mModule->Cast(baseExpr, mResult, baseType, BfCastFlags_Explicit);
  8612. }
  8613. void BfExprEvaluator::Visit(BfMixinExpression* mixinExpr)
  8614. {
  8615. if (mModule->mCurMethodInstance->mMethodDef->mMethodType == BfMethodType_Mixin)
  8616. {
  8617. auto varType = mModule->GetPrimitiveType(BfTypeCode_Var);
  8618. auto newVar = mModule->AllocFromType(varType, mModule->mCurMethodState->mCurScope);
  8619. mResult = BfTypedValue(newVar, varType, true);
  8620. return;
  8621. }
  8622. auto curMethodState = mModule->mCurMethodState;
  8623. if (curMethodState->mMixinState == NULL)
  8624. {
  8625. mModule->Fail("Mixin references can only be used within mixins", mixinExpr);
  8626. return;
  8627. }
  8628. int localIdx = GetMixinVariable();
  8629. if (localIdx != -1)
  8630. {
  8631. auto varDecl = curMethodState->mLocals[localIdx];
  8632. if (varDecl != NULL)
  8633. {
  8634. BfTypedValue localResult = LoadLocal(varDecl);
  8635. mResult = localResult;
  8636. mResultLocalVar = varDecl;
  8637. mResultFieldInstance = NULL;
  8638. mResultLocalVarRefNode = mixinExpr;
  8639. return;
  8640. }
  8641. }
  8642. if (mModule->mCurMethodInstance->mIsUnspecialized)
  8643. {
  8644. mResult = mModule->GetDefaultTypedValue(mModule->GetPrimitiveType(BfTypeCode_Var));
  8645. return;
  8646. }
  8647. mModule->Fail("Mixin value cannot be inferred", mixinExpr);
  8648. }
  8649. void BfExprEvaluator::Visit(BfSizedArrayCreateExpression* createExpr)
  8650. {
  8651. auto type = mModule->ResolveTypeRef(createExpr->mTypeRef);
  8652. if (type == NULL)
  8653. return;
  8654. if (type->IsArray())
  8655. {
  8656. // If we have a case like 'int[] (1, 2)' then we infer the sized array size from the initializer
  8657. auto arrayType = (BfArrayType*)type;
  8658. if (arrayType->mDimensions == 1)
  8659. {
  8660. int arraySize = 0;
  8661. if (auto arrayInitExpr = BfNodeDynCast<BfCollectionInitializerExpression>(createExpr->mInitializer))
  8662. {
  8663. arraySize = (int)arrayInitExpr->mValues.size();
  8664. }
  8665. type = mModule->CreateSizedArrayType(arrayType->GetUnderlyingType(), arraySize);
  8666. }
  8667. }
  8668. if (!type->IsSizedArray())
  8669. {
  8670. mModule->Fail("Sized array expected", createExpr->mTypeRef);
  8671. return;
  8672. }
  8673. BfSizedArrayType* arrayType = (BfSizedArrayType*)type;
  8674. if (createExpr->mInitializer == NULL)
  8675. {
  8676. mModule->AssertErrorState();
  8677. mResult = mModule->GetDefaultTypedValue(arrayType);
  8678. return;
  8679. }
  8680. InitializedSizedArray(arrayType, createExpr->mInitializer->mOpenBrace, createExpr->mInitializer->mValues, createExpr->mInitializer->mCommas, createExpr->mInitializer->mCloseBrace);
  8681. }
  8682. void BfExprEvaluator::Visit(BfInitializerExpression* initExpr)
  8683. {
  8684. uint64 unassignedFieldFlags = 0;
  8685. if (auto typeRef = BfNodeDynCast<BfTypeReference>(initExpr->mTarget))
  8686. {
  8687. BfType* type = NULL;
  8688. if (auto typeRef = BfNodeDynCast<BfDotTypeReference>(initExpr->mTarget))
  8689. {
  8690. type = mExpectingType;
  8691. }
  8692. if (type == NULL)
  8693. type = mModule->ResolveTypeRef(typeRef);
  8694. if (type != NULL)
  8695. {
  8696. if (type->IsValueType())
  8697. {
  8698. if (mReceivingValue != NULL)
  8699. {
  8700. mResult = *mReceivingValue;
  8701. mReceivingValue = NULL;
  8702. }
  8703. else
  8704. {
  8705. mResult = BfTypedValue(mModule->CreateAlloca(type), type, true);
  8706. }
  8707. auto typeInstance = type->ToTypeInstance();
  8708. if (typeInstance != NULL)
  8709. unassignedFieldFlags = (1 << typeInstance->mMergedFieldDataCount) - 1;
  8710. }
  8711. else
  8712. {
  8713. mModule->Fail("Initializer expressions can only be used on value types or allocated values", initExpr->mTarget);
  8714. }
  8715. }
  8716. }
  8717. else
  8718. VisitChild(initExpr->mTarget);
  8719. if (!mResult)
  8720. mResult = mModule->GetDefaultTypedValue(mModule->mContext->mBfObjectType);
  8721. BfIRBlock initBlock = BfIRBlock();
  8722. if (unassignedFieldFlags != 0)
  8723. {
  8724. initBlock = mModule->mBfIRBuilder->CreateBlock("initStart", true);
  8725. mModule->mBfIRBuilder->CreateBr(initBlock);
  8726. mModule->mBfIRBuilder->SetInsertPoint(initBlock);
  8727. }
  8728. BfTypedValue initValue = GetResult(true);
  8729. bool isFirstAdd = true;
  8730. BfFunctionBindResult addFunctionBindResult;
  8731. addFunctionBindResult.mWantsArgs = true;
  8732. for (auto elementExpr : initExpr->mValues)
  8733. {
  8734. bool wasValidInitKind = false;
  8735. if (auto assignExpr = BfNodeDynCast<BfAssignmentExpression>(elementExpr))
  8736. {
  8737. BfTypedValue fieldResult;
  8738. if (auto identifierNode = BfNodeDynCast<BfIdentifierNode>(assignExpr->mLeft))
  8739. {
  8740. StringT<128> findName;
  8741. identifierNode->ToString(findName);
  8742. mResultFieldInstance = NULL;
  8743. fieldResult = LookupField(identifierNode, initValue, findName, BfLookupFieldFlag_IsImplicitThis);
  8744. if ((fieldResult.mKind == BfTypedValueKind_TempAddr) || (fieldResult.mKind == BfTypedValueKind_RestrictedTempAddr))
  8745. fieldResult.mKind = BfTypedValueKind_Addr;
  8746. if ((mResultFieldInstance != NULL) && (mResultFieldInstance->mMergedDataIdx != -1))
  8747. {
  8748. int resultLocalVarField = 0;
  8749. int resultLocalVarFieldCount = 0;
  8750. mResultFieldInstance->GetDataRange(resultLocalVarField, resultLocalVarFieldCount);
  8751. for (int i = 0; i < resultLocalVarFieldCount; i++)
  8752. unassignedFieldFlags &= ~((int64)1 << (resultLocalVarField - 1 + i));
  8753. }
  8754. wasValidInitKind = true;
  8755. if ((fieldResult) || (mPropDef != NULL))
  8756. {
  8757. mResult = fieldResult;
  8758. PerformAssignment(assignExpr, true, BfTypedValue());
  8759. mResult = BfTypedValue();
  8760. }
  8761. else
  8762. {
  8763. mModule->Fail(StrFormat("'%s' does not contain a definition for '%s'", mModule->TypeToString(initValue.mType).c_str(),
  8764. findName.c_str()), identifierNode);
  8765. }
  8766. }
  8767. }
  8768. else
  8769. {
  8770. auto autoComplete = GetAutoComplete();
  8771. if ((autoComplete != NULL) && (autoComplete->IsAutocompleteNode(elementExpr)))
  8772. {
  8773. if (auto identiferNode = BfNodeDynCast<BfIdentifierNode>(elementExpr))
  8774. {
  8775. auto typeInstance = initValue.mType->ToTypeInstance();
  8776. if (typeInstance != NULL)
  8777. {
  8778. String filter;
  8779. identiferNode->ToString(filter);
  8780. autoComplete->AddTypeMembers(typeInstance, false, true, filter, typeInstance, false, true, false);
  8781. }
  8782. }
  8783. }
  8784. bool wasFirstAdd = isFirstAdd;
  8785. if (isFirstAdd)
  8786. {
  8787. BfExprEvaluator exprEvaluator(mModule);
  8788. exprEvaluator.mFunctionBindResult = &addFunctionBindResult;
  8789. SizedArray<BfExpression*, 2> argExprs;
  8790. argExprs.push_back(elementExpr);
  8791. BfSizedArray<BfExpression*> sizedArgExprs(argExprs);
  8792. BfResolvedArgs argValues(&sizedArgExprs);
  8793. exprEvaluator.ResolveArgValues(argValues);
  8794. exprEvaluator.MatchMethod(elementExpr, NULL, initValue, false, false, "Add", argValues, NULL);
  8795. if (addFunctionBindResult.mMethodInstance != NULL)
  8796. CreateCall(initExpr, addFunctionBindResult.mMethodInstance, addFunctionBindResult.mFunc, true, addFunctionBindResult.mIRArgs);
  8797. isFirstAdd = false;
  8798. }
  8799. else if ((addFunctionBindResult.mMethodInstance == NULL) || (addFunctionBindResult.mMethodInstance->GetParamCount() == 0))
  8800. {
  8801. mModule->CreateValueFromExpression(elementExpr, NULL, (BfEvalExprFlags)(mBfEvalExprFlags& BfEvalExprFlags_InheritFlags));
  8802. }
  8803. else
  8804. {
  8805. auto argValue = mModule->CreateValueFromExpression(elementExpr, addFunctionBindResult.mMethodInstance->GetParamType(0), (BfEvalExprFlags)(mBfEvalExprFlags & BfEvalExprFlags_InheritFlags));
  8806. if ((argValue) && (!mModule->mBfIRBuilder->mIgnoreWrites))
  8807. {
  8808. SizedArray<BfIRValue, 2> irArgs;
  8809. PushThis(elementExpr, initValue, addFunctionBindResult.mMethodInstance, irArgs);
  8810. PushArg(argValue, irArgs);
  8811. for (int argIdx = (int)irArgs.size(); argIdx < (int)addFunctionBindResult.mIRArgs.size(); argIdx++)
  8812. irArgs.Add(addFunctionBindResult.mIRArgs[argIdx]);
  8813. CreateCall(initExpr, addFunctionBindResult.mMethodInstance, addFunctionBindResult.mFunc, true, irArgs);
  8814. }
  8815. }
  8816. wasValidInitKind = true;
  8817. }
  8818. if (!wasValidInitKind)
  8819. {
  8820. mModule->Fail("Invalid initializer member declarator", initExpr);
  8821. }
  8822. }
  8823. if (unassignedFieldFlags != 0)
  8824. {
  8825. auto curBlock = mModule->mBfIRBuilder->GetInsertBlock();
  8826. mModule->mBfIRBuilder->SetInsertPointAtStart(initBlock);
  8827. mModule->mBfIRBuilder->CreateMemSet(initValue.mValue, mModule->GetConstValue(0, mModule->GetPrimitiveType(BfTypeCode_Int8)),
  8828. mModule->GetConstValue(initValue.mType->mSize), initValue.mType->mAlign);
  8829. mModule->mBfIRBuilder->SetInsertPoint(curBlock);
  8830. }
  8831. mResult = initValue;
  8832. }
  8833. void BfExprEvaluator::Visit(BfCollectionInitializerExpression* arrayInitExpr)
  8834. {
  8835. mModule->Fail("Collection initializer not usable here", arrayInitExpr);
  8836. }
  8837. void BfExprEvaluator::Visit(BfTypeOfExpression* typeOfExpr)
  8838. {
  8839. auto typeType = mModule->ResolveTypeDef(mModule->mCompiler->mTypeTypeDef);
  8840. auto autoComplete = GetAutoComplete();
  8841. if ((autoComplete != NULL) && (typeOfExpr->mTypeRef != NULL))
  8842. {
  8843. autoComplete->CheckTypeRef(typeOfExpr->mTypeRef, false, true);
  8844. }
  8845. BfType* type;
  8846. if (auto genericTypeRef = BfNodeDynCast<BfGenericInstanceTypeRef>(typeOfExpr->mTypeRef))
  8847. {
  8848. type = mModule->ResolveTypeRefAllowUnboundGenerics(typeOfExpr->mTypeRef, BfPopulateType_Identity);
  8849. }
  8850. else
  8851. {
  8852. type = ResolveTypeRef(typeOfExpr->mTypeRef, BfPopulateType_Identity);
  8853. }
  8854. if (type == NULL)
  8855. {
  8856. mResult = mModule->GetDefaultTypedValue(mModule->ResolveTypeDef(mModule->mCompiler->mTypeTypeDef));
  8857. return;
  8858. }
  8859. mModule->AddDependency(type, mModule->mCurTypeInstance, BfDependencyMap::DependencyFlag_ExprTypeReference);
  8860. mResult = BfTypedValue(mModule->CreateTypeDataRef(type), typeType);
  8861. }
  8862. bool BfExprEvaluator::LookupTypeProp(BfTypeOfExpression* typeOfExpr, BfIdentifierNode* propName)
  8863. {
  8864. // We ignore errors because we go through the normal Visit(BfTypeOfExpression) if this fails, which will throw the error again
  8865. SetAndRestoreValue<bool> prevIgnoreErrors(mModule->mIgnoreErrors, true);
  8866. auto typeType = mModule->ResolveTypeDef(mModule->mCompiler->mTypeTypeDef);
  8867. BfType* type;
  8868. if (auto genericTypeRef = BfNodeDynCast<BfGenericInstanceTypeRef>(typeOfExpr->mTypeRef))
  8869. {
  8870. type = mModule->ResolveTypeRefAllowUnboundGenerics(typeOfExpr->mTypeRef, BfPopulateType_Identity);
  8871. }
  8872. else
  8873. {
  8874. type = ResolveTypeRef(typeOfExpr->mTypeRef, BfPopulateType_Identity);
  8875. }
  8876. if (type == NULL)
  8877. {
  8878. mResult = mModule->GetDefaultTypedValue(mModule->ResolveTypeDef(mModule->mCompiler->mTypeTypeDef));
  8879. return false;
  8880. }
  8881. mModule->AddDependency(type, mModule->mCurTypeInstance, BfDependencyMap::DependencyFlag_ExprTypeReference);
  8882. mModule->PopulateType(type);
  8883. auto typeInstance = type->ToTypeInstance();
  8884. auto _BoolResult = [&](bool val)
  8885. {
  8886. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConst(BfTypeCode_Boolean, val ? 1 : 0), mModule->GetPrimitiveType(BfTypeCode_Boolean));
  8887. };
  8888. auto _Int32Result = [&](int32 val)
  8889. {
  8890. mResult = BfTypedValue(mModule->GetConstValue32(val), mModule->GetPrimitiveType(BfTypeCode_Int32));
  8891. };
  8892. String memberName;
  8893. propName->ToString(memberName);
  8894. bool handled = true;
  8895. if (memberName == "IsTypedPrimitive")
  8896. _BoolResult(type->IsPrimitiveType());
  8897. else if (memberName == "IsObject")
  8898. _BoolResult(type->IsObject());
  8899. else if (memberName == "IsValueType")
  8900. _BoolResult(type->IsValueType());
  8901. else if (memberName == "IsPrimitive")
  8902. _BoolResult(type->IsPrimitiveType());
  8903. else if (memberName == "IsInteger")
  8904. _BoolResult(type->IsInteger());
  8905. else if (memberName == "IsIntegral")
  8906. _BoolResult(type->IsIntegral());
  8907. else if (memberName == "IsSigned")
  8908. _BoolResult(type->IsSigned());
  8909. else if (memberName == "IsFloatingPoint")
  8910. _BoolResult(type->IsFloat());
  8911. else if (memberName == "IsPointer")
  8912. _BoolResult(type->IsPointer());
  8913. else if (memberName == "IsStruct")
  8914. _BoolResult(type->IsStruct());
  8915. else if (memberName == "IsSplattable")
  8916. _BoolResult(type->IsSplattable());
  8917. else if (memberName == "IsUnion")
  8918. _BoolResult(type->IsUnion());
  8919. else if (memberName == "IsBoxed")
  8920. _BoolResult(type->IsBoxed());
  8921. else if (memberName == "IsEnum")
  8922. _BoolResult(type->IsEnum());
  8923. else if (memberName == "IsTuple")
  8924. _BoolResult(type->IsTuple());
  8925. else if (memberName == "IsNullable")
  8926. _BoolResult(type->IsNullable());
  8927. else if (memberName == "IsGenericType")
  8928. _BoolResult(type->IsGenericTypeInstance());
  8929. else if (memberName == "IsArray")
  8930. _BoolResult(type->IsArray());
  8931. else if (memberName == "IsSizedArray")
  8932. _BoolResult(type->IsSizedArray());
  8933. else if (memberName == "TypeId")
  8934. {
  8935. _Int32Result(type->mTypeId);
  8936. mResult.mType = mModule->ResolveTypeDef(mModule->mCompiler->mReflectTypeIdTypeDef);
  8937. }
  8938. else if (memberName == "GenericParamCount")
  8939. {
  8940. auto genericTypeInst = type->ToGenericTypeInstance();
  8941. _Int32Result((genericTypeInst != NULL) ? (int)genericTypeInst->mGenericTypeInfo->mTypeGenericArguments.size() : 0);
  8942. }
  8943. else if (memberName == "Size")
  8944. _Int32Result(type->mSize);
  8945. else if (memberName == "Align")
  8946. _Int32Result(type->mAlign);
  8947. else if (memberName == "Stride")
  8948. _Int32Result(type->GetStride());
  8949. else if (memberName == "InstanceSize")
  8950. _Int32Result((typeInstance != NULL) ? typeInstance->mInstSize : type->mSize);
  8951. else if (memberName == "InstanceAlign")
  8952. _Int32Result((typeInstance != NULL) ? typeInstance->mInstAlign : type->mSize);
  8953. else if (memberName == "InstanceStride")
  8954. _Int32Result((typeInstance != NULL) ? typeInstance->GetInstStride() : type->GetStride());
  8955. else if ((memberName == "MinValue") || (memberName == "MaxValue"))
  8956. {
  8957. bool isMin = memberName == "MinValue";
  8958. BfType* checkType = typeInstance;
  8959. if (checkType->IsTypedPrimitive())
  8960. checkType = checkType->GetUnderlyingType();
  8961. if (checkType->IsPrimitiveType())
  8962. {
  8963. auto primType = (BfPrimitiveType*)checkType;
  8964. if (typeInstance->IsEnum())
  8965. {
  8966. if (typeInstance->mTypeInfoEx != NULL)
  8967. {
  8968. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConst(primType->mTypeDef->mTypeCode, isMin ? (uint64)typeInstance->mTypeInfoEx->mMinValue : (uint64)typeInstance->mTypeInfoEx->mMaxValue), typeInstance);
  8969. return true;
  8970. }
  8971. }
  8972. else
  8973. {
  8974. switch (primType->mTypeDef->mTypeCode)
  8975. {
  8976. case BfTypeCode_Int8:
  8977. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConst(primType->mTypeDef->mTypeCode, isMin ? -0x80 : 0x7F), typeInstance);
  8978. return true;
  8979. case BfTypeCode_Int16:
  8980. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConst(primType->mTypeDef->mTypeCode, isMin ? -0x8000 : 0x7FFF), typeInstance);
  8981. return true;
  8982. case BfTypeCode_Int32:
  8983. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConst(primType->mTypeDef->mTypeCode, isMin ? (uint64)-0x80000000LL : 0x7FFFFFFF), typeInstance);
  8984. return true;
  8985. case BfTypeCode_Int64:
  8986. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConst(primType->mTypeDef->mTypeCode, isMin ? (uint64)-0x8000000000000000LL : (uint64)0x7FFFFFFFFFFFFFFFLL), typeInstance);
  8987. return true;
  8988. case BfTypeCode_UInt8:
  8989. case BfTypeCode_Char8:
  8990. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConst(primType->mTypeDef->mTypeCode, isMin ? 0 : 0xFF), typeInstance);
  8991. return true;
  8992. case BfTypeCode_UInt16:
  8993. case BfTypeCode_Char16:
  8994. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConst(primType->mTypeDef->mTypeCode, isMin ? 0 : 0xFFFF), typeInstance);
  8995. return true;
  8996. case BfTypeCode_UInt32:
  8997. case BfTypeCode_Char32:
  8998. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConst(primType->mTypeDef->mTypeCode, isMin ? 0 : (uint64)0xFFFFFFFFLL), typeInstance);
  8999. return true;
  9000. case BfTypeCode_UInt64:
  9001. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConst(primType->mTypeDef->mTypeCode, isMin ? 0 : (uint64)0xFFFFFFFFFFFFFFFFLL), typeInstance);
  9002. return true;
  9003. default: break;
  9004. }
  9005. }
  9006. }
  9007. if (typeInstance->IsEnum())
  9008. {
  9009. mModule->Fail("'MinValue' cannot be used on enums with payloads", propName);
  9010. }
  9011. else
  9012. {
  9013. mModule->Fail(StrFormat("'%s' cannot be used on type '%s'", memberName.c_str(), mModule->TypeToString(typeInstance).c_str()), propName);
  9014. }
  9015. }
  9016. else
  9017. return false;
  9018. auto autoComplete = GetAutoComplete();
  9019. if ((autoComplete != NULL) && (typeOfExpr->mTypeRef != NULL))
  9020. {
  9021. autoComplete->CheckTypeRef(typeOfExpr->mTypeRef, false, true);
  9022. }
  9023. return true;
  9024. }
  9025. void BfExprEvaluator::DoTypeIntAttr(BfTypeReference* typeRef, BfToken token)
  9026. {
  9027. auto type = mModule->ResolveTypeRef(typeRef, BfPopulateType_Data, BfResolveTypeRefFlag_AutoComplete);
  9028. if (type == NULL)
  9029. return;
  9030. mModule->AddDependency(type, mModule->mCurTypeInstance, BfDependencyMap::DependencyFlag_LocalUsage); // Local usage ensures it changes when the type data changes
  9031. auto typeInst = type->ToTypeInstance();
  9032. if ((typeInst != NULL) && (typeInst->mTypeDef->mIsOpaque))
  9033. {
  9034. mModule->Fail(StrFormat("Unable to determine attributes for opaque type '%s'", mModule->TypeToString(type).c_str()), typeRef);
  9035. }
  9036. BfType* sizeType = mModule->GetPrimitiveType(BfTypeCode_Int32);
  9037. int attrVal = 0;
  9038. switch (token)
  9039. {
  9040. case BfToken_SizeOf: attrVal = type->mSize; break;
  9041. case BfToken_AlignOf: attrVal = type->mAlign; break;
  9042. case BfToken_StrideOf: attrVal = type->GetStride(); break;
  9043. default: break;
  9044. }
  9045. bool isUndefVal = false;
  9046. if (type->IsGenericParam())
  9047. isUndefVal = true;
  9048. if (type->IsSizedArray())
  9049. {
  9050. auto sizedArray = (BfSizedArrayType*)type;
  9051. if (sizedArray->mElementCount == -1)
  9052. isUndefVal = true;
  9053. }
  9054. if (isUndefVal)
  9055. {
  9056. // We do this so we know it's a constant but we can't assume anything about its value
  9057. // We make the value an Int32 which doesn't match the IntPtr type, but it allows us to
  9058. // assume it can be implicitly cased to int32
  9059. mResult = BfTypedValue(mModule->mBfIRBuilder->GetUndefConstValue(mModule->mBfIRBuilder->MapType(sizeType)), sizeType);
  9060. }
  9061. else
  9062. mResult = BfTypedValue(mModule->GetConstValue(attrVal, sizeType), sizeType);
  9063. }
  9064. void BfExprEvaluator::Visit(BfSizeOfExpression* sizeOfExpr)
  9065. {
  9066. DoTypeIntAttr(sizeOfExpr->mTypeRef, BfToken_SizeOf);
  9067. }
  9068. void BfExprEvaluator::Visit(BfAlignOfExpression* alignOfExpr)
  9069. {
  9070. DoTypeIntAttr(alignOfExpr->mTypeRef, BfToken_AlignOf);
  9071. }
  9072. void BfExprEvaluator::Visit(BfStrideOfExpression* strideOfExpr)
  9073. {
  9074. DoTypeIntAttr(strideOfExpr->mTypeRef, BfToken_StrideOf);
  9075. }
  9076. void BfExprEvaluator::Visit(BfDefaultExpression* defaultExpr)
  9077. {
  9078. auto autoComplete = GetAutoComplete();
  9079. if (autoComplete != NULL)
  9080. autoComplete->CheckTypeRef(defaultExpr->mTypeRef, false, true);
  9081. BfType* type = NULL;
  9082. if (defaultExpr->mOpenParen == NULL)
  9083. {
  9084. if (mExpectingType)
  9085. {
  9086. type = mExpectingType;
  9087. }
  9088. else
  9089. {
  9090. mModule->Fail("Type cannot be inferred, consider adding explicit type name", defaultExpr);
  9091. return;
  9092. }
  9093. }
  9094. else
  9095. type = mModule->ResolveTypeRef(defaultExpr->mTypeRef);
  9096. if (type == NULL)
  9097. return;
  9098. BfDefaultValueKind defaultKind = BfDefaultValueKind_Const;
  9099. if (type->IsRef())
  9100. {
  9101. mModule->Fail(StrFormat("There is no default value for type '%s'", mModule->TypeToString(type).c_str()), defaultExpr);
  9102. defaultKind = BfDefaultValueKind_Addr;
  9103. }
  9104. mModule->ValidateAllocation(type, defaultExpr->mTypeRef);
  9105. mModule->AddDependency(type, mModule->mCurTypeInstance, BfDependencyMap::DependencyFlag_ExprTypeReference);
  9106. mResult = mModule->GetDefaultTypedValue(type, true, defaultKind);
  9107. }
  9108. void BfExprEvaluator::Visit(BfUninitializedExpression* uninitialziedExpr)
  9109. {
  9110. mModule->Fail("Invalid use of the '?' uninitialized specifier", uninitialziedExpr);
  9111. }
  9112. void BfExprEvaluator::Visit(BfCheckTypeExpression* checkTypeExpr)
  9113. {
  9114. auto targetValue = mModule->CreateValueFromExpression(checkTypeExpr->mTarget, NULL, (BfEvalExprFlags)(mBfEvalExprFlags & BfEvalExprFlags_InheritFlags));
  9115. if (!targetValue)
  9116. return;
  9117. if (checkTypeExpr->mTypeRef == NULL)
  9118. {
  9119. mModule->AssertErrorState();
  9120. return;
  9121. }
  9122. auto autoComplete = GetAutoComplete();
  9123. if (autoComplete != NULL)
  9124. autoComplete->CheckTypeRef(checkTypeExpr->mTypeRef, false, true);
  9125. auto targetType = mModule->ResolveTypeRef(checkTypeExpr->mTypeRef);
  9126. if (!targetType)
  9127. {
  9128. mModule->AssertErrorState();
  9129. return;
  9130. }
  9131. mModule->AddDependency(targetType, mModule->mCurTypeInstance, BfDependencyMap::DependencyFlag_ExprTypeReference);
  9132. auto boolType = mModule->GetPrimitiveType(BfTypeCode_Boolean);
  9133. if (targetValue.mType->IsValueTypeOrValueTypePtr())
  9134. {
  9135. auto typeInstance = targetValue.mType->ToTypeInstance();
  9136. if (targetValue.mType->IsWrappableType())
  9137. typeInstance = mModule->GetWrappedStructType(targetValue.mType);
  9138. bool matches = (targetValue.mType == targetType) || (mModule->mContext->mBfObjectType == targetType);
  9139. if (!matches)
  9140. matches = mModule->TypeIsSubTypeOf(typeInstance, targetType->ToTypeInstance());
  9141. mResult = BfTypedValue(mModule->GetConstValue(matches ? 1 : 0, boolType), boolType);
  9142. return;
  9143. }
  9144. if (targetType->IsValueType())
  9145. {
  9146. if ((targetValue.mType != mModule->mContext->mBfObjectType) && (!targetValue.mType->IsInterface()))
  9147. {
  9148. mResult = BfTypedValue(mModule->GetConstValue(0, boolType), boolType);
  9149. return;
  9150. }
  9151. }
  9152. int wantTypeId = 0;
  9153. if (!targetType->IsGenericParam())
  9154. wantTypeId = targetType->mTypeId;
  9155. auto objectType = mModule->mContext->mBfObjectType;
  9156. mModule->PopulateType(objectType, BfPopulateType_Full);
  9157. targetValue = mModule->LoadValue(targetValue);
  9158. BfTypeInstance* srcTypeInstance = targetValue.mType->ToTypeInstance();
  9159. BfTypeInstance* targetTypeInstance = targetType->ToTypeInstance();
  9160. bool wasGenericParamType = false;
  9161. if ((srcTypeInstance != NULL) && (targetTypeInstance != NULL))
  9162. {
  9163. if (mModule->TypeIsSubTypeOf(srcTypeInstance, targetTypeInstance))
  9164. {
  9165. // We don't give this warning when we have wasGenericParmType set because that indicates we had a generic type constraint,
  9166. // and a type constraint infers that the ACTUAL type used will be equal to or derived from that type and therefore
  9167. // it may be a "necessary cast" indeed
  9168. if ((!wasGenericParamType) && (mModule->mCurMethodState->mMixinState == NULL))
  9169. {
  9170. if (srcTypeInstance == targetType)
  9171. mModule->Warn(BfWarning_BF4203_UnnecessaryDynamicCast, StrFormat("Unnecessary cast, the value is already type '%s'",
  9172. mModule->TypeToString(srcTypeInstance).c_str()), checkTypeExpr->mIsToken);
  9173. else
  9174. mModule->Warn(BfWarning_BF4203_UnnecessaryDynamicCast, StrFormat("Unnecessary cast, '%s' is a subtype of '%s'",
  9175. mModule->TypeToString(srcTypeInstance).c_str(), mModule->TypeToString(targetType).c_str()), checkTypeExpr->mIsToken);
  9176. }
  9177. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConst(BfTypeCode_Boolean, 1), boolType);
  9178. return;
  9179. }
  9180. else if ((!targetType->IsInterface()) && (srcTypeInstance != mModule->mContext->mBfObjectType) && (!mModule->TypeIsSubTypeOf(targetTypeInstance, srcTypeInstance)))
  9181. {
  9182. mModule->Fail(StrFormat("Cannot convert type '%s' to '%s' via any conversion",
  9183. mModule->TypeToString(targetValue.mType).c_str(), mModule->TypeToString(targetTypeInstance).c_str()), checkTypeExpr->mIsToken);
  9184. }
  9185. }
  9186. if (mModule->mCompiler->IsAutocomplete())
  9187. {
  9188. mResult = mModule->GetDefaultTypedValue(boolType, false, BfDefaultValueKind_Addr);
  9189. return;
  9190. }
  9191. auto irb = mModule->mBfIRBuilder;
  9192. auto prevBB = mModule->mBfIRBuilder->GetInsertBlock();
  9193. auto matchBB = mModule->mBfIRBuilder->CreateBlock("is.match");
  9194. auto endBB = mModule->mBfIRBuilder->CreateBlock("is.done");
  9195. BfIRValue boolResult = mModule->CreateAlloca(boolType);
  9196. irb->CreateStore(irb->CreateConst(BfTypeCode_Boolean, 0), boolResult);
  9197. mModule->EmitDynamicCastCheck(targetValue, targetType, matchBB, endBB);
  9198. mModule->AddBasicBlock(matchBB);
  9199. irb->CreateStore(irb->CreateConst(BfTypeCode_Boolean, 1), boolResult);
  9200. irb->CreateBr(endBB);
  9201. mModule->AddBasicBlock(endBB);
  9202. mResult = BfTypedValue(irb->CreateLoad(boolResult), boolType);
  9203. }
  9204. void BfExprEvaluator::Visit(BfDynamicCastExpression* dynCastExpr)
  9205. {
  9206. auto targetValue = mModule->CreateValueFromExpression(dynCastExpr->mTarget);
  9207. auto targetType = mModule->ResolveTypeRefAllowUnboundGenerics(dynCastExpr->mTypeRef, BfPopulateType_Data, false);
  9208. auto autoComplete = GetAutoComplete();
  9209. if (autoComplete != NULL)
  9210. {
  9211. autoComplete->CheckTypeRef(dynCastExpr->mTypeRef, false, true);
  9212. }
  9213. auto origTargetType = targetType;
  9214. if (!targetValue)
  9215. return;
  9216. if (!targetType)
  9217. {
  9218. mModule->AssertErrorState();
  9219. return;
  9220. }
  9221. bool wasGenericParamType = false;
  9222. if (targetType->IsGenericParam())
  9223. {
  9224. //targetType = mModule->ResolveGenericType(targetType);
  9225. //wasGenericParamType = true;
  9226. }
  9227. if ((targetValue.mType->IsMethodRef()) || (targetType->IsMethodRef()))
  9228. {
  9229. // We can never cast a MethodRef to any class type
  9230. mResult = mModule->GetDefaultTypedValue(targetType);
  9231. return;
  9232. }
  9233. if (mModule->mContext->mResolvingVarField)
  9234. {
  9235. mResult = mModule->GetDefaultTypedValue(targetType);
  9236. return;
  9237. }
  9238. mModule->AddDependency(targetType, mModule->mCurTypeInstance, BfDependencyMap::DependencyFlag_ExprTypeReference);
  9239. if (targetType->IsGenericParam())
  9240. {
  9241. wasGenericParamType = true;
  9242. //wasGenericParamType = false; // "was", not "is"
  9243. auto genericParamType = (BfGenericParamType*) targetType;
  9244. auto genericParam = mModule->GetGenericParamInstance(genericParamType);
  9245. auto typeConstraint = genericParam->mTypeConstraint;
  9246. if ((typeConstraint == NULL) && (genericParam->mGenericParamFlags & (BfGenericParamFlag_Class | BfGenericParamFlag_Interface)))
  9247. typeConstraint = mModule->mContext->mBfObjectType;
  9248. if ((typeConstraint == NULL) || (!typeConstraint->IsObject()))
  9249. {
  9250. 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",
  9251. genericParam->GetGenericParamDef()->mName.c_str()), dynCastExpr->mTypeRef);
  9252. return;
  9253. }
  9254. targetType = typeConstraint;
  9255. }
  9256. if ((!targetType->IsObjectOrInterface()) && (!targetType->IsNullable()))
  9257. {
  9258. mModule->Fail(StrFormat("The as operator must be used with a reference type or nullable type ('%s' is a non-nullable value type)",
  9259. mModule->TypeToString(origTargetType).c_str()), dynCastExpr->mTypeRef);
  9260. return;
  9261. }
  9262. if (targetValue.mType->IsGenericParam())
  9263. {
  9264. auto genericParamType = (BfGenericParamType*)targetValue.mType;
  9265. auto genericParam = mModule->GetGenericParamInstance(genericParamType);
  9266. auto typeConstraint = genericParam->mTypeConstraint;
  9267. if (typeConstraint == NULL)
  9268. typeConstraint = mModule->mContext->mBfObjectType;
  9269. if ((typeConstraint->IsDelegate()) && (typeConstraint == targetType))
  9270. {
  9271. // Delegate constraints may be matched by valueless method references, so this won't always match (don't warn)
  9272. mResult = mModule->GetDefaultTypedValue(targetType);
  9273. return;
  9274. }
  9275. targetValue = mModule->GetDefaultTypedValue(typeConstraint);
  9276. }
  9277. auto boolType = mModule->GetPrimitiveType(BfTypeCode_Boolean);
  9278. auto _CheckResult = [&]()
  9279. {
  9280. if ((mResult) && (origTargetType->IsGenericParam()))
  9281. mResult = mModule->GetDefaultTypedValue(origTargetType);
  9282. };
  9283. if ((targetValue.mType->IsNullable()) && (targetType->IsInterface()))
  9284. {
  9285. mResult = mModule->Cast(dynCastExpr, targetValue, targetType, BfCastFlags_SilentFail);
  9286. if (!mResult)
  9287. {
  9288. mModule->Warn(0, StrFormat("Conversion from '%s' to '%s' will always be null",
  9289. mModule->TypeToString(targetValue.mType).c_str(), mModule->TypeToString(origTargetType).c_str()), dynCastExpr->mAsToken);
  9290. mResult = BfTypedValue(mModule->GetDefaultValue(origTargetType), origTargetType);
  9291. }
  9292. _CheckResult();
  9293. return;
  9294. }
  9295. if (targetValue.mType->IsValueTypeOrValueTypePtr())
  9296. {
  9297. mModule->Warn(0, StrFormat("Type '%s' is not applicable for dynamic casting",
  9298. mModule->TypeToString(targetValue.mType).c_str()), dynCastExpr->mAsToken);
  9299. auto typeInstance = targetValue.mType->ToTypeInstance();
  9300. if (targetValue.mType->IsWrappableType())
  9301. typeInstance = mModule->GetWrappedStructType(targetValue.mType);
  9302. bool matches = (targetValue.mType == targetType) || (mModule->mContext->mBfObjectType == targetType);
  9303. if (targetType->IsNullable())
  9304. {
  9305. auto elementType = targetType->GetUnderlyingType();
  9306. if (elementType == targetValue.mType)
  9307. {
  9308. // We match nullable element
  9309. auto allocaInst = mModule->CreateAlloca(targetType);
  9310. auto hasValueAddr = mModule->mBfIRBuilder->CreateInBoundsGEP(allocaInst, 0, 1); // has_value
  9311. mModule->mBfIRBuilder->CreateStore(mModule->GetConstValue(1, boolType), hasValueAddr);
  9312. hasValueAddr = mModule->mBfIRBuilder->CreateInBoundsGEP(allocaInst, 0, 0); // value
  9313. mModule->mBfIRBuilder->CreateStore(targetValue.mValue, hasValueAddr);
  9314. mResult = BfTypedValue(allocaInst, targetType, true);
  9315. _CheckResult();
  9316. return;
  9317. }
  9318. }
  9319. if (!matches)
  9320. matches = mModule->TypeIsSubTypeOf(typeInstance, targetType->ToTypeInstance());
  9321. if (matches)
  9322. mResult = mModule->Cast(dynCastExpr, targetValue, targetType, BfCastFlags_Explicit);
  9323. else if (targetType->IsNullable())
  9324. {
  9325. auto allocaInst = mModule->CreateAlloca(targetType);
  9326. auto allocaBits = mModule->mBfIRBuilder->CreateBitCast(allocaInst, mModule->mBfIRBuilder->GetPrimitiveType(BfTypeCode_NullPtr));
  9327. mModule->mBfIRBuilder->CreateMemSet(allocaBits, mModule->GetConstValue(0, mModule->GetPrimitiveType(BfTypeCode_Int8)),
  9328. mModule->GetConstValue(targetType->mSize), targetType->mAlign);
  9329. mResult = BfTypedValue(allocaInst, targetType, true);
  9330. }
  9331. else
  9332. mResult = BfTypedValue(mModule->GetDefaultValue(targetType), targetType);
  9333. _CheckResult();
  9334. return;
  9335. }
  9336. if (targetType->IsNullable())
  9337. {
  9338. if (autoComplete != NULL)
  9339. {
  9340. mResult = mModule->GetDefaultTypedValue(targetType);
  9341. return;
  9342. }
  9343. auto elementType = targetType->GetUnderlyingType();
  9344. auto allocaInst = mModule->CreateAlloca(targetType);
  9345. auto hasValueAddr = mModule->mBfIRBuilder->CreateInBoundsGEP(allocaInst, 0, elementType->IsValuelessType() ? 1 : 2); // has_value
  9346. mModule->mBfIRBuilder->CreateStore(mModule->GetConstValue(0, boolType), hasValueAddr);
  9347. auto objectType = mModule->mContext->mBfObjectType;
  9348. auto prevBB = mModule->mBfIRBuilder->GetInsertBlock();
  9349. auto matchBB = mModule->mBfIRBuilder->CreateBlock("as.match");
  9350. auto endBB = mModule->mBfIRBuilder->CreateBlock("as.end");
  9351. mModule->EmitDynamicCastCheck(targetValue, elementType, matchBB, endBB);
  9352. BfBoxedType* boxedType = mModule->CreateBoxedType(elementType);
  9353. mModule->AddBasicBlock(matchBB);
  9354. if (elementType->IsValuelessType())
  9355. {
  9356. auto hasValueAddr = mModule->mBfIRBuilder->CreateInBoundsGEP(allocaInst, 0, 1); // has_value
  9357. mModule->mBfIRBuilder->CreateStore(mModule->GetConstValue(1, boolType), hasValueAddr);
  9358. }
  9359. else
  9360. {
  9361. auto hasValueAddr = mModule->mBfIRBuilder->CreateInBoundsGEP(allocaInst, 0, 2); // has_value
  9362. mModule->mBfIRBuilder->CreateStore(mModule->GetConstValue(1, boolType), hasValueAddr);
  9363. auto nullableValueAddr = mModule->mBfIRBuilder->CreateInBoundsGEP(allocaInst, 0, 1); // value
  9364. auto srcBoxedType = mModule->mBfIRBuilder->CreateBitCast(targetValue.mValue, mModule->mBfIRBuilder->MapType(boxedType, BfIRPopulateType_Full));
  9365. auto boxedValueAddr = mModule->mBfIRBuilder->CreateInBoundsGEP(srcBoxedType, 0, 1); // mValue
  9366. auto boxedValue = mModule->mBfIRBuilder->CreateLoad(boxedValueAddr);
  9367. mModule->mBfIRBuilder->CreateStore(boxedValue, nullableValueAddr);
  9368. }
  9369. mModule->mBfIRBuilder->CreateBr(endBB);
  9370. mModule->AddBasicBlock(endBB);
  9371. mResult = BfTypedValue(allocaInst, targetType, true);
  9372. _CheckResult();
  9373. return;
  9374. }
  9375. targetValue = mModule->LoadValue(targetValue);
  9376. if (targetType->IsValueType())
  9377. {
  9378. mModule->Fail("Invalid dynamic cast type", dynCastExpr->mTypeRef);
  9379. return;
  9380. }
  9381. BfTypeInstance* srcTypeInstance = targetValue.mType->ToTypeInstance();
  9382. BfTypeInstance* targetTypeInstance = targetType->ToTypeInstance();
  9383. if (mModule->TypeIsSubTypeOf(srcTypeInstance, targetTypeInstance))
  9384. {
  9385. // We don't give this warning when we have wasGenericParmType set because that indicates we had a generic type constraint,
  9386. // and a type constraint infers that the ACTUAL type used will be equal to or derived from that type and therefore
  9387. // it may be a "necessary cast" indeed
  9388. if ((!wasGenericParamType) && (mModule->mCurMethodState->mMixinState == NULL))
  9389. {
  9390. if (srcTypeInstance == targetType)
  9391. mModule->Warn(BfWarning_BF4203_UnnecessaryDynamicCast, StrFormat("Unnecessary cast, the value is already type '%s'",
  9392. mModule->TypeToString(srcTypeInstance).c_str()), dynCastExpr->mAsToken);
  9393. else
  9394. mModule->Warn(BfWarning_BF4203_UnnecessaryDynamicCast, StrFormat("Unnecessary cast, '%s' is a subtype of '%s'",
  9395. mModule->TypeToString(srcTypeInstance).c_str(), mModule->TypeToString(targetType).c_str()), dynCastExpr->mAsToken);
  9396. }
  9397. auto castedValue = mModule->mBfIRBuilder->CreateBitCast(targetValue.mValue, mModule->mBfIRBuilder->MapType(targetTypeInstance));
  9398. mResult = BfTypedValue(castedValue, targetTypeInstance);
  9399. _CheckResult();
  9400. return;
  9401. }
  9402. else if ((!targetType->IsInterface()) && (!mModule->TypeIsSubTypeOf(targetTypeInstance, srcTypeInstance)))
  9403. {
  9404. if (!mModule->IsInSpecializedSection())
  9405. {
  9406. mModule->Fail(StrFormat("Cannot convert type '%s' to '%s' via any conversion",
  9407. mModule->TypeToString(targetValue.mType).c_str(), mModule->TypeToString(targetTypeInstance).c_str()), dynCastExpr->mAsToken);
  9408. }
  9409. mResult = mModule->GetDefaultTypedValue(targetType);
  9410. return;
  9411. }
  9412. if (autoComplete != NULL)
  9413. {
  9414. mResult = mModule->GetDefaultTypedValue(targetType);
  9415. _CheckResult();
  9416. return;
  9417. }
  9418. auto irb = mModule->mBfIRBuilder;
  9419. auto objectType = mModule->mContext->mBfObjectType;
  9420. mModule->PopulateType(objectType, BfPopulateType_Full);
  9421. auto prevBB = mModule->mBfIRBuilder->GetInsertBlock();
  9422. auto endBB = mModule->mBfIRBuilder->CreateBlock("as.end");
  9423. auto matchBlock = irb->CreateBlock("as.match");
  9424. BfIRValue targetVal = mModule->CreateAlloca(targetType);
  9425. irb->CreateStore(irb->CreateConstNull(irb->MapType(targetType)), targetVal);
  9426. mModule->EmitDynamicCastCheck(targetValue, targetType, matchBlock, endBB);
  9427. mModule->AddBasicBlock(matchBlock);
  9428. BfIRValue castedCallResult = mModule->mBfIRBuilder->CreateBitCast(targetValue.mValue, mModule->mBfIRBuilder->MapType(targetType));
  9429. irb->CreateStore(castedCallResult, targetVal);
  9430. irb->CreateBr(endBB);
  9431. mModule->AddBasicBlock(endBB);
  9432. mResult = BfTypedValue(irb->CreateLoad(targetVal), targetType);
  9433. _CheckResult();
  9434. }
  9435. void BfExprEvaluator::Visit(BfCastExpression* castExpr)
  9436. {
  9437. auto autoComplete = GetAutoComplete();
  9438. if ((autoComplete != NULL) && (castExpr->mTypeRef != NULL))
  9439. {
  9440. // 'mayBeIdentifier' because this may be a misidentified cast - it could be a parenthesized expression
  9441. autoComplete->CheckTypeRef(castExpr->mTypeRef, true, true);
  9442. }
  9443. BfType* resolvedType = NULL;
  9444. if ((BfNodeDynCastExact<BfDotTypeReference>(castExpr->mTypeRef) != NULL) && (mExpectingType != NULL))
  9445. {
  9446. //mModule->SetElementType(castExpr->mTypeRef, BfSourceElementType_TypeRef);
  9447. resolvedType = mExpectingType;
  9448. }
  9449. else
  9450. resolvedType = ResolveTypeRef(castExpr->mTypeRef);
  9451. if (resolvedType != NULL)
  9452. mModule->AddDependency(resolvedType, mModule->mCurTypeInstance, BfDependencyMap::DependencyFlag_LocalUsage);
  9453. // If resolvedType is NULL then that's okay- we just leave the following expression uncasted
  9454. if (castExpr->mExpression == NULL)
  9455. {
  9456. mModule->AssertErrorState();
  9457. return;
  9458. }
  9459. auto exprFlags = (BfEvalExprFlags)((mBfEvalExprFlags & BfEvalExprFlags_NoAutoComplete) | BfEvalExprFlags_ExplicitCast);
  9460. mResult = mModule->CreateValueFromExpression(castExpr->mExpression, resolvedType, exprFlags);
  9461. }
  9462. bool BfExprEvaluator::IsExactMethodMatch(BfMethodInstance* methodA, BfMethodInstance* methodB, bool ignoreImplicitParams)
  9463. {
  9464. if (methodA->mReturnType != methodB->mReturnType)
  9465. return false;
  9466. int implicitParamCountA = methodA->GetImplicitParamCount();
  9467. if (methodA->HasExplicitThis())
  9468. implicitParamCountA++;
  9469. int implicitParamCountB = methodB->GetImplicitParamCount();
  9470. if (methodB->HasExplicitThis())
  9471. implicitParamCountB++;
  9472. if (methodA->GetParamCount() - implicitParamCountA != methodB->GetParamCount() - implicitParamCountB)
  9473. return false;
  9474. for (int i = 0; i < (int)methodA->GetParamCount() - implicitParamCountA; i++)
  9475. {
  9476. auto paramA = methodA->GetParamType(i + implicitParamCountA);
  9477. auto paramB = methodB->GetParamType(i + implicitParamCountB);
  9478. if (paramA != paramB)
  9479. return false;
  9480. }
  9481. return true;
  9482. }
  9483. void BfExprEvaluator::ConstResolve(BfExpression* expr)
  9484. {
  9485. BfConstResolver constResolver(mModule);
  9486. constResolver.Resolve(expr);
  9487. mResult = constResolver.mResult;
  9488. }
  9489. BfTypeInstance* BfExprEvaluator::VerifyBaseDelegateType(BfTypeInstance* baseDelegateType)
  9490. {
  9491. mModule->PopulateType(baseDelegateType, BfPopulateType_DataAndMethods);
  9492. if (baseDelegateType->mFieldInstances.size() != 2)
  9493. {
  9494. mModule->AssertErrorState();
  9495. return NULL;
  9496. }
  9497. return baseDelegateType;
  9498. }
  9499. bool BfExprEvaluator::CanBindDelegate(BfDelegateBindExpression* delegateBindExpr, BfMethodInstance** boundMethod, BfType* origMethodExpectingType, BfTypeVector* methodGenericArgumentsSubstitute)
  9500. {
  9501. if ((mExpectingType == NULL) && (origMethodExpectingType == NULL))
  9502. {
  9503. return false;
  9504. }
  9505. bool isGenericMatch = mExpectingType == NULL;
  9506. auto expectingType = mExpectingType;
  9507. if (expectingType == NULL)
  9508. expectingType = origMethodExpectingType;
  9509. auto typeInstance = expectingType->ToTypeInstance();
  9510. if ((typeInstance == NULL) ||
  9511. ((!typeInstance->mTypeDef->mIsDelegate) && (!typeInstance->mTypeDef->mIsFunction)))
  9512. return false;
  9513. mModule->PopulateType(typeInstance, BfPopulateType_DataAndMethods);
  9514. auto methodInstance = mModule->GetRawMethodInstanceAtIdx(typeInstance, 0, "Invoke");
  9515. if (methodInstance == NULL)
  9516. {
  9517. BF_DBG_FATAL("Invoke not found");
  9518. return false;
  9519. }
  9520. if (delegateBindExpr->mTarget == NULL)
  9521. return false;
  9522. BfAutoParentNodeEntry autoParentNodeEntry(mModule, delegateBindExpr);
  9523. SizedArray<BfTypedValueExpression, 4> typedValueExprs;
  9524. typedValueExprs.resize(methodInstance->GetParamCount());
  9525. SizedArray<BfExpression*, 4> args;
  9526. args.resize(methodInstance->GetParamCount());
  9527. auto _FixType = [&](BfType* type)
  9528. {
  9529. if (!isGenericMatch)
  9530. return type;
  9531. auto fixedType = mModule->ResolveGenericType(type, NULL, methodGenericArgumentsSubstitute);
  9532. if (fixedType != NULL)
  9533. return fixedType;
  9534. return (BfType*)mModule->GetPrimitiveType(BfTypeCode_Var);
  9535. };
  9536. auto _TypeMatches = [&](BfType* lhs, BfType* rhs)
  9537. {
  9538. if (lhs == rhs)
  9539. return true;
  9540. return lhs->IsVar();
  9541. };
  9542. for (int i = 0; i < (int) methodInstance->GetParamCount(); i++)
  9543. {
  9544. auto typedValueExpr = &typedValueExprs[i];
  9545. typedValueExpr->mTypedValue.mValue = BfIRValue(BfIRValueFlags_Value, -1);
  9546. typedValueExpr->mTypedValue.mType = _FixType(methodInstance->GetParamType(i));
  9547. typedValueExpr->mRefNode = NULL;
  9548. args[i] = typedValueExpr;
  9549. }
  9550. BfSizedArray<ASTREF(BfTypeReference*)>* methodGenericArguments = NULL;
  9551. if (delegateBindExpr->mGenericArgs != NULL)
  9552. methodGenericArguments = &delegateBindExpr->mGenericArgs->mGenericArgs;
  9553. BfFunctionBindResult bindResult;
  9554. bindResult.mSkipMutCheck = true; // Allow operating on copies
  9555. bindResult.mBindType = expectingType;
  9556. mFunctionBindResult = &bindResult;
  9557. SetAndRestoreValue<bool> ignoreError(mModule->mIgnoreErrors, true);
  9558. DoInvocation(delegateBindExpr->mTarget, delegateBindExpr, args, methodGenericArguments);
  9559. mFunctionBindResult = NULL;
  9560. if (bindResult.mMethodInstance == NULL)
  9561. return false;
  9562. if (boundMethod != NULL)
  9563. *boundMethod = bindResult.mMethodInstance;
  9564. auto matchedMethod = bindResult.mMethodInstance;
  9565. if (!_TypeMatches(_FixType(methodInstance->mReturnType), matchedMethod->mReturnType))
  9566. return false;
  9567. int implicitParamCountA = methodInstance->GetImplicitParamCount();
  9568. int implicitParamCountB = matchedMethod->GetImplicitParamCount();
  9569. if (methodInstance->GetParamCount() - implicitParamCountA != matchedMethod->GetParamCount() - implicitParamCountB)
  9570. return false;
  9571. for (int i = 0; i < (int)methodInstance->GetParamCount() - implicitParamCountA; i++)
  9572. {
  9573. auto paramA = _FixType(methodInstance->GetParamType(i + implicitParamCountA));
  9574. auto paramB = _FixType(matchedMethod->GetParamType(i + implicitParamCountB));
  9575. if (!_TypeMatches(paramA, paramB))
  9576. return false;
  9577. }
  9578. return true;
  9579. }
  9580. BfTypedValue BfExprEvaluator::DoImplicitArgCapture(BfAstNode* refNode, BfIdentifierNode* identifierNode, int shadowIdx)
  9581. {
  9582. String findName = identifierNode->ToString();
  9583. if (mModule->mCurMethodState != NULL)
  9584. {
  9585. auto rootMethodState = mModule->mCurMethodState->GetRootMethodState();
  9586. auto checkMethodState = mModule->mCurMethodState;
  9587. bool isMixinOuterVariablePass = false;
  9588. int shadowSkip = shadowIdx;
  9589. while (checkMethodState != NULL)
  9590. {
  9591. BP_ZONE("LookupIdentifier:DoImplicitArgCapture");
  9592. BfTypeInstance* closureTypeInst = NULL;
  9593. BfClosureInstanceInfo* closureInstanceInfo = NULL;
  9594. if ((checkMethodState->mClosureState != NULL) && (checkMethodState->mClosureState->mClosureType != NULL) && (!checkMethodState->mClosureState->mCapturing))
  9595. {
  9596. closureTypeInst = mModule->mCurMethodState->mClosureState->mClosureType;
  9597. }
  9598. BfLocalVarEntry* entry;
  9599. if (checkMethodState->mLocalVarSet.TryGetWith<StringImpl&>(findName, &entry))
  9600. {
  9601. auto varDecl = entry->mLocalVar;
  9602. while (varDecl != NULL)
  9603. {
  9604. if (varDecl->mNameNode == identifierNode)
  9605. {
  9606. if (shadowSkip > 0)
  9607. {
  9608. shadowSkip--;
  9609. }
  9610. else
  9611. {
  9612. BfTypedValue localResult = LoadLocal(varDecl);
  9613. if (!isMixinOuterVariablePass)
  9614. {
  9615. mResultLocalVar = varDecl;
  9616. mResultFieldInstance = NULL;
  9617. mResultLocalVarRefNode = identifierNode;
  9618. }
  9619. return localResult;
  9620. }
  9621. }
  9622. varDecl = varDecl->mShadowedLocal;
  9623. }
  9624. }
  9625. // Check for the captured locals. It's important we do it here so we get local-first precedence still
  9626. if (closureTypeInst != NULL)
  9627. {
  9628. closureTypeInst->mTypeDef->PopulateMemberSets();
  9629. BfMemberSetEntry* memberSetEntry = NULL;
  9630. if (closureTypeInst->mTypeDef->mFieldSet.TryGetWith(findName, &memberSetEntry))
  9631. {
  9632. auto fieldDef = (BfFieldDef*)memberSetEntry->mMemberDef;
  9633. while (fieldDef != NULL)
  9634. {
  9635. BfIdentifierNode* fieldNameNode = NULL;
  9636. if (fieldDef->mIdx < (int)checkMethodState->mClosureState->mClosureInstanceInfo->mCaptureEntries.size())
  9637. fieldNameNode = checkMethodState->mClosureState->mClosureInstanceInfo->mCaptureEntries[fieldDef->mIdx].mNameNode;
  9638. if (fieldNameNode == identifierNode)
  9639. {
  9640. auto& field = closureTypeInst->mFieldInstances[fieldDef->mIdx];
  9641. if (!field.mResolvedType->IsValuelessType())
  9642. {
  9643. if (mModule->mCurMethodState->mClosureState->mCapturing)
  9644. {
  9645. mModule->mCurMethodState->mClosureState->mReferencedOuterClosureMembers.Add(&field);
  9646. return mModule->GetDefaultTypedValue(field.mResolvedType);
  9647. }
  9648. auto localVar = mModule->mCurMethodState->mLocals[0];
  9649. auto thisValue = localVar->mValue;
  9650. mModule->mBfIRBuilder->PopulateType(localVar->mResolvedType);
  9651. BfTypedValue result = BfTypedValue(mModule->mBfIRBuilder->CreateInBoundsGEP(thisValue, 0, field.mDataIdx), field.mResolvedType, true);
  9652. if (field.mResolvedType->IsRef())
  9653. {
  9654. auto refType = (BfRefType*)field.mResolvedType;
  9655. auto underlyingType = refType->GetUnderlyingType();
  9656. result = BfTypedValue(mModule->mBfIRBuilder->CreateLoad(result.mValue), underlyingType, true);
  9657. }
  9658. else if (fieldDef->mIsReadOnly)
  9659. result = mModule->LoadValue(result);
  9660. mResultLocalVar = localVar;
  9661. mResultFieldInstance = &field;
  9662. mResultLocalVarField = -(field.mMergedDataIdx + 1);
  9663. return result;
  9664. }
  9665. }
  9666. fieldDef = fieldDef->mNextWithSameName;
  9667. }
  9668. }
  9669. }
  9670. if ((checkMethodState->mClosureState != NULL) && (checkMethodState->mClosureState->mCapturing) /*&& (checkMethodState->mClosureState->mIsLocalMethod)*/)
  9671. {
  9672. checkMethodState = checkMethodState->mPrevMethodState;
  9673. continue;
  9674. }
  9675. // Allow local mixin to see outside variables during its processing -- since we don't actually "capture" those into params
  9676. bool isLocalMixinProcessing = false;
  9677. if ((checkMethodState->mClosureState != NULL) && (!checkMethodState->mClosureState->mCapturing) && (closureTypeInst == NULL) &&
  9678. (mModule->mCurMethodInstance->mMethodDef->mMethodType == BfMethodType_Mixin))
  9679. isLocalMixinProcessing = true;
  9680. if (!isLocalMixinProcessing)
  9681. break;
  9682. isMixinOuterVariablePass = true;
  9683. checkMethodState = checkMethodState->mPrevMethodState;
  9684. }
  9685. }
  9686. return BfTypedValue();
  9687. }
  9688. BfTypedValue BfExprEvaluator::DoImplicitArgCapture(BfAstNode* refNode, BfMethodInstance* methodInstance, int paramIdx, bool& failed, BfImplicitParamKind paramKind, const BfTypedValue& methodRefTarget)
  9689. {
  9690. if ((methodRefTarget) && (methodRefTarget.mValue.mId != BfIRValue::ID_IMPLICIT))
  9691. {
  9692. if (methodRefTarget.mType->IsMethodRef())
  9693. {
  9694. BfMethodRefType* methodRefType = (BfMethodRefType*)methodRefTarget.mType;
  9695. BfMethodInstance* methodRefMethodInst = methodRefType->mMethodRef;
  9696. BF_ASSERT(methodRefMethodInst == methodInstance);
  9697. auto paramType = methodInstance->GetParamType(paramIdx);
  9698. int dataIdx = methodRefType->GetDataIdxFromParamIdx(paramIdx);
  9699. if (dataIdx == -1)
  9700. {
  9701. BF_ASSERT(paramType->IsValuelessType());
  9702. return BfTypedValue(mModule->mBfIRBuilder->GetFakeVal(), paramType);
  9703. }
  9704. if (methodRefTarget.IsSplat())
  9705. {
  9706. if (methodRefType->WantsDataPassedAsSplat(dataIdx))
  9707. {
  9708. BF_ASSERT(paramIdx == -1);
  9709. return BfTypedValue(methodRefTarget.mValue, paramType, BfTypedValueKind_SplatHead);
  9710. }
  9711. else
  9712. {
  9713. int splatIdx = dataIdx;
  9714. if (dataIdx > 0)
  9715. {
  9716. if (methodRefType->WantsDataPassedAsSplat(0))
  9717. splatIdx += methodRefType->GetCaptureType(0)->GetSplatCount() - 1;
  9718. }
  9719. bool isAddr = false;
  9720. BfIRValue value = mModule->ExtractSplatValue(methodRefTarget, splatIdx, paramType, &isAddr);
  9721. // We moved the composite load from ExtractSplatValue to here. Hopefully this is correct.
  9722. // 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)
  9723. // if ((paramType->IsComposite()) && (mModule->IsTargetingBeefBackend()))
  9724. // value = mModule->mBfIRBuilder->CreateLoad(value);
  9725. auto lookupVal = BfTypedValue(value, paramType, isAddr);
  9726. if ((isAddr) && (!lookupVal.mType->IsComposite()))
  9727. lookupVal = mModule->LoadValue(lookupVal);
  9728. return lookupVal;
  9729. }
  9730. }
  9731. BF_ASSERT(methodRefTarget.IsAddr());
  9732. if (paramType->IsComposite())
  9733. return BfTypedValue(mModule->mBfIRBuilder->CreateInBoundsGEP(methodRefTarget.mValue, 0, dataIdx), paramType, true);
  9734. return BfTypedValue(mModule->ExtractValue(methodRefTarget, dataIdx), paramType);
  9735. }
  9736. }
  9737. // 'Default' implicit arg lookup, by identifier. May match field (for lambda), or local variable
  9738. if (paramKind == BfImplicitParamKind_General)
  9739. {
  9740. if (paramIdx == -1)
  9741. {
  9742. if (auto delegateBindExpr = BfNodeDynCast<BfDelegateBindExpression>(refNode))
  9743. {
  9744. BfAstNode* thisNode = NULL;
  9745. BfTypedValue thisValue;
  9746. if (auto memberReferenceExpr = BfNodeDynCast<BfMemberReferenceExpression>(delegateBindExpr->mTarget))
  9747. thisNode = memberReferenceExpr->mTarget;
  9748. else if (auto qualifiedNameNode = BfNodeDynCast<BfQualifiedNameNode>(delegateBindExpr->mTarget))
  9749. thisNode = qualifiedNameNode->mLeft;
  9750. else if (auto identifierNode = BfNodeDynCast<BfIdentifierNode>(delegateBindExpr->mTarget))
  9751. {
  9752. // Implicit
  9753. thisValue = mModule->GetThis();
  9754. }
  9755. if (auto thisExpr = BfNodeDynCast<BfExpression>(thisNode))
  9756. {
  9757. thisValue = mModule->CreateValueFromExpression(thisExpr);
  9758. if (!thisValue)
  9759. return BfTypedValue();
  9760. }
  9761. if (thisValue)
  9762. {
  9763. //TODO: handle 'mut', throw error if trying to capture from a non-mut, etc...
  9764. return thisValue;
  9765. }
  9766. }
  9767. }
  9768. String captureName = methodInstance->GetParamName(paramIdx);
  9769. BfIdentifierNode* identifierNode = methodInstance->GetParamNameNode(paramIdx);
  9770. BfTypedValue lookupVal;
  9771. if (identifierNode != NULL)
  9772. {
  9773. lookupVal = DoImplicitArgCapture(refNode, identifierNode, 0);
  9774. }
  9775. else
  9776. {
  9777. lookupVal = LookupIdentifier(NULL, captureName);
  9778. }
  9779. if (lookupVal)
  9780. {
  9781. auto paramType = methodInstance->GetParamType(paramIdx);
  9782. if (paramType->IsRef())
  9783. {
  9784. auto refType = (BfRefType*)paramType;
  9785. if (mResultLocalVar != NULL)
  9786. {
  9787. // When we are capturing, we need to note that we require capturing by reference here
  9788. auto localVar = mResultLocalVar;
  9789. localVar->mWrittenToId = mModule->mCurMethodState->GetRootMethodState()->mCurAccessId++;
  9790. }
  9791. bool isValid = false;
  9792. if ((refType->mRefKind == BfRefType::RefKind_Mut) && (lookupVal.mKind == BfTypedValueKind_MutableValue))
  9793. isValid = true;
  9794. if ((lookupVal.mType->IsRef()) || (lookupVal.IsAddr()))
  9795. isValid = true;
  9796. if (!isValid)
  9797. {
  9798. // Is there another way this can fail than to be in a lambda?
  9799. auto error = mModule->Fail(StrFormat("Method '%s' requires that '%s' be captured by reference. Consider adding by-reference capture specifier [&] to lambda.",
  9800. mModule->MethodToString(methodInstance).c_str(), captureName.c_str()), refNode, true);
  9801. if ((error != NULL) && (methodInstance->mMethodDef->mMethodDeclaration != NULL))
  9802. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("See method declaration"), methodInstance->mMethodDef->GetRefNode());
  9803. failed = true;
  9804. }
  9805. }
  9806. else
  9807. {
  9808. if (lookupVal.mType->IsRef())
  9809. lookupVal = mModule->RemoveRef(lookupVal);
  9810. if (!lookupVal.mType->IsComposite())
  9811. lookupVal = mModule->LoadValue(lookupVal);
  9812. }
  9813. return lookupVal;
  9814. }
  9815. else
  9816. {
  9817. mModule->Fail(StrFormat("Failed to lookup implicit capture '%s'", captureName.c_str()), refNode, true);
  9818. failed = true;
  9819. return BfTypedValue();
  9820. }
  9821. }
  9822. return BfTypedValue();
  9823. }
  9824. void BfExprEvaluator::Visit(BfDelegateBindExpression* delegateBindExpr)
  9825. {
  9826. BfAutoParentNodeEntry autoParentNodeEntry(mModule, delegateBindExpr);
  9827. if (mExpectingType == NULL)
  9828. {
  9829. mModule->Fail("Cannot infer delegate type", delegateBindExpr);
  9830. return;
  9831. }
  9832. BfTokenNode* newToken = NULL;
  9833. BfAllocTarget allocTarget = ResolveAllocTarget(delegateBindExpr->mNewToken, newToken);
  9834. SizedArray<BfTypedValueExpression, 4> typedValueExprs;
  9835. SizedArray<BfExpression*, 4> args;
  9836. BfTypeInstance* delegateTypeInstance = NULL;
  9837. BfMethodInstance* methodInstance = NULL;
  9838. const char* bindTypeName = NULL;
  9839. bool isMethodRefMatch = false;
  9840. if (mExpectingType->IsMethodRef())
  9841. {
  9842. auto methodRefType = (BfMethodRefType*)mExpectingType;
  9843. BF_ASSERT(delegateBindExpr->mNewToken == NULL);
  9844. methodInstance = methodRefType->mMethodRef;
  9845. isMethodRefMatch = true;
  9846. }
  9847. else
  9848. {
  9849. if (mExpectingType->IsGenericParam())
  9850. {
  9851. auto genericParamInstance = mModule->GetGenericParamInstance((BfGenericParamType*)mExpectingType);
  9852. if ((genericParamInstance->mTypeConstraint != NULL) && (genericParamInstance->mTypeConstraint->IsDelegate()))
  9853. {
  9854. delegateTypeInstance = genericParamInstance->mTypeConstraint->ToTypeInstance();
  9855. }
  9856. }
  9857. else
  9858. delegateTypeInstance = mExpectingType->ToTypeInstance();
  9859. if ((delegateTypeInstance == NULL) ||
  9860. ((!delegateTypeInstance->IsDelegate()) && (!delegateTypeInstance->IsFunction())))
  9861. {
  9862. mModule->Fail(StrFormat("Type '%s' cannot be used for method binding. Only delegate or function types are allowed.", mModule->TypeToString(mExpectingType).c_str()), delegateBindExpr);
  9863. return;
  9864. }
  9865. bindTypeName = (delegateTypeInstance->IsDelegate()) ? "delegate" : "function";
  9866. mModule->PopulateType(delegateTypeInstance, BfPopulateType_DataAndMethods);
  9867. methodInstance = mModule->GetRawMethodInstanceAtIdx(delegateTypeInstance, 0, "Invoke");
  9868. if (methodInstance == NULL)
  9869. {
  9870. BF_DBG_FATAL("Invoke not found");
  9871. return;
  9872. }
  9873. if (auto tokenNode = BfNodeDynCast<BfTokenNode>(delegateBindExpr->mNewToken))
  9874. {
  9875. if (delegateTypeInstance->IsFunction())
  9876. mModule->Fail("Function bindings are direct assignments, allocation specifier is not applicable", delegateBindExpr->mNewToken);
  9877. else if (tokenNode->GetToken() == BfToken_Append)
  9878. {
  9879. mModule->Fail("Append allocation on delegate bind not supported", delegateBindExpr->mNewToken);
  9880. }
  9881. }
  9882. }
  9883. int paramOffset = methodInstance->HasExplicitThis() ? 1 : 0;
  9884. typedValueExprs.resize(methodInstance->GetParamCount() - paramOffset);
  9885. args.resize(methodInstance->GetParamCount() - paramOffset);
  9886. for (int i = 0; i < (int)methodInstance->GetParamCount() - paramOffset; i++)
  9887. {
  9888. auto typedValueExpr = &typedValueExprs[i];
  9889. typedValueExpr->mTypedValue.mValue = BfIRValue(BfIRValueFlags_Value, -1);
  9890. typedValueExpr->mTypedValue.mType = methodInstance->GetParamType(i + paramOffset);
  9891. typedValueExpr->mRefNode = NULL;
  9892. args[i] = typedValueExpr;
  9893. }
  9894. BfSizedArray<ASTREF(BfTypeReference*)>* methodGenericArguments = NULL;
  9895. if (delegateBindExpr->mGenericArgs != NULL)
  9896. methodGenericArguments = &delegateBindExpr->mGenericArgs->mGenericArgs;
  9897. if (delegateBindExpr->mTarget == NULL)
  9898. {
  9899. mModule->AssertErrorState();
  9900. return;
  9901. }
  9902. auto autoComplete = GetAutoComplete();
  9903. if (autoComplete != NULL)
  9904. {
  9905. SetAndRestoreValue<bool> prevForceAllowNonStatic(autoComplete->mForceAllowNonStatic, methodInstance->mMethodDef->mHasExplicitThis);
  9906. GetAutoComplete()->CheckNode(delegateBindExpr->mTarget);
  9907. }
  9908. if ((!delegateBindExpr->mTarget->IsA<BfIdentifierNode>()) &&
  9909. (!delegateBindExpr->mTarget->IsA<BfMemberReferenceExpression>()))
  9910. {
  9911. mModule->Fail(StrFormat("Invalid %s binding target, %s can only bind to method references. Consider wrapping expression in a lambda.", bindTypeName, bindTypeName), delegateBindExpr->mTarget);
  9912. mModule->CreateValueFromExpression(delegateBindExpr->mTarget);
  9913. return;
  9914. }
  9915. BfFunctionBindResult bindResult;
  9916. bindResult.mSkipMutCheck = true; // Allow operating on copies
  9917. bindResult.mBindType = delegateTypeInstance;
  9918. //
  9919. {
  9920. SetAndRestoreValue<BfType*> prevExpectingType(mExpectingType, methodInstance->mReturnType);
  9921. mFunctionBindResult = &bindResult;
  9922. DoInvocation(delegateBindExpr->mTarget, delegateBindExpr, args, methodGenericArguments);
  9923. mFunctionBindResult = NULL;
  9924. }
  9925. SetMethodElementType(delegateBindExpr->mTarget);
  9926. if (bindResult.mMethodInstance == NULL)
  9927. {
  9928. if ((mResult) && (mResult.mType->IsVar()))
  9929. return;
  9930. mResult = BfTypedValue();
  9931. return;
  9932. }
  9933. auto bindMethodInstance = bindResult.mMethodInstance;
  9934. if (isMethodRefMatch)
  9935. {
  9936. // WTF- this was always false, what was it supposed to catch?
  9937. // if (bindMethodInstance != bindResult.mMethodInstance)
  9938. // {
  9939. // mResult = BfTypedValue();
  9940. // return;
  9941. // }
  9942. }
  9943. else
  9944. {
  9945. if (!IsExactMethodMatch(methodInstance, bindMethodInstance, true))
  9946. {
  9947. if (bindResult.mCheckedMultipleMethods)
  9948. {
  9949. mModule->Fail(StrFormat("No overload for '%s' matches %s '%s'", bindMethodInstance->mMethodDef->mName.c_str(), bindTypeName,
  9950. mModule->TypeToString(delegateTypeInstance).c_str()), delegateBindExpr->mTarget);
  9951. }
  9952. else
  9953. {
  9954. mModule->Fail(StrFormat("Method '%s' does not match %s '%s'", mModule->MethodToString(bindMethodInstance).c_str(), bindTypeName,
  9955. mModule->TypeToString(delegateTypeInstance).c_str()), delegateBindExpr->mTarget);
  9956. }
  9957. mResult = BfTypedValue();
  9958. return;
  9959. }
  9960. }
  9961. bool isDirectFunction = false;
  9962. if ((bindResult.mMethodInstance->GetOwner()->IsFunction()) && (bindResult.mFunc))
  9963. isDirectFunction = true;
  9964. if (bindMethodInstance->mIsIntrinsic)
  9965. {
  9966. 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);
  9967. mResult = BfTypedValue();
  9968. return;
  9969. }
  9970. bool hasIncompatibleCallingConventions = !mModule->mSystem->IsCompatibleCallingConvention(methodInstance->mCallingConvention, bindMethodInstance->mCallingConvention);
  9971. auto _GetInvokeMethodName = [&]()
  9972. {
  9973. String methodName = "Invoke$";
  9974. methodName += mModule->mCurMethodInstance->mMethodDef->mName;
  9975. int prevSepPos = (int)methodName.LastIndexOf('$');
  9976. if (prevSepPos > 6)
  9977. {
  9978. methodName.RemoveToEnd(prevSepPos);
  9979. }
  9980. auto rootMethodState = mModule->mCurMethodState->GetRootMethodState();
  9981. HashContext hashCtx;
  9982. if (mModule->mCurMethodInstance->mMethodDef->mDeclaringType->mPartialIdx != -1)
  9983. hashCtx.Mixin(mModule->mCurMethodInstance->mMethodDef->mDeclaringType->mPartialIdx);
  9984. if (delegateBindExpr->mFatArrowToken != NULL)
  9985. {
  9986. hashCtx.Mixin(delegateBindExpr->mFatArrowToken->GetStartCharId());
  9987. }
  9988. if (rootMethodState->mMethodInstance->mMethodInfoEx != NULL)
  9989. {
  9990. for (auto methodGenericArg : rootMethodState->mMethodInstance->mMethodInfoEx->mMethodGenericArguments)
  9991. {
  9992. StringT<128> genericTypeName;
  9993. BfMangler::Mangle(genericTypeName, mModule->mCompiler->GetMangleKind(), methodGenericArg);
  9994. hashCtx.MixinStr(genericTypeName);
  9995. }
  9996. }
  9997. Val128 hashVal = hashCtx.Finish128();
  9998. methodName += '$';
  9999. methodName += BfTypeUtils::HashEncode64(hashVal.mLow);
  10000. String mangledName;
  10001. BfMangler::MangleMethodName(mangledName, mModule->mCompiler->GetMangleKind(), mModule->mCurTypeInstance, methodName);
  10002. return mangledName;
  10003. };
  10004. if ((delegateBindExpr->mNewToken == NULL) || (delegateTypeInstance->IsFunction()))
  10005. {
  10006. if ((mModule->mCurMethodState != NULL) && (mModule->mCurMethodState->mHotDataReferenceBuilder != NULL))
  10007. {
  10008. BF_ASSERT(bindResult.mMethodInstance->mHotMethod != NULL);
  10009. mModule->mCurMethodState->mHotDataReferenceBuilder->mFunctionPtrs.Add(bindResult.mMethodInstance->mHotMethod);
  10010. }
  10011. if (isDirectFunction)
  10012. {
  10013. //if ((delegateTypeInstance != NULL) && (delegateTypeInstance->IsFunction()))
  10014. if (mExpectingType->IsFunction())
  10015. {
  10016. auto intPtrVal = mModule->mBfIRBuilder->CreatePtrToInt(bindResult.mFunc, BfTypeCode_IntPtr);
  10017. mResult = BfTypedValue(intPtrVal, mExpectingType);
  10018. return;
  10019. }
  10020. }
  10021. if (mExpectingType->IsFunction())
  10022. {
  10023. BfIRValue result;
  10024. if ((hasIncompatibleCallingConventions) && (mModule->HasCompiledOutput()))
  10025. {
  10026. //
  10027. {
  10028. SetAndRestoreValue<bool> prevIgnore(mModule->mBfIRBuilder->mIgnoreWrites, true);
  10029. result = mModule->CastToFunction(delegateBindExpr->mTarget, bindResult.mOrigTarget, bindResult.mMethodInstance, mExpectingType);
  10030. }
  10031. if (result)
  10032. {
  10033. String methodName = _GetInvokeMethodName();
  10034. SizedArray<BfIRType, 8> irParamTypes;
  10035. BfIRType irReturnType;
  10036. bindMethodInstance->GetIRFunctionInfo(mModule, irReturnType, irParamTypes);
  10037. auto prevActiveFunction = mModule->mBfIRBuilder->GetActiveFunction();
  10038. auto prevInsertBlock = mModule->mBfIRBuilder->GetInsertBlock();
  10039. mModule->mBfIRBuilder->SaveDebugLocation();
  10040. auto funcType = mModule->mBfIRBuilder->CreateFunctionType(irReturnType, irParamTypes);
  10041. auto funcValue = mModule->mBfIRBuilder->CreateFunction(funcType, BfIRLinkageType_External, methodName);
  10042. auto srcCallingConv = mModule->GetIRCallingConvention(methodInstance);
  10043. mModule->mBfIRBuilder->SetFuncCallingConv(funcValue, srcCallingConv);
  10044. mModule->mBfIRBuilder->SetActiveFunction(funcValue);
  10045. auto entryBlock = mModule->mBfIRBuilder->CreateBlock("entry", true);
  10046. mModule->mBfIRBuilder->SetInsertPoint(entryBlock);
  10047. SizedArray<BfIRValue, 8> irArgs;
  10048. for (int paramIdx = 0; paramIdx < irParamTypes.size(); paramIdx++)
  10049. {
  10050. irArgs.push_back(mModule->mBfIRBuilder->GetArgument(paramIdx));
  10051. }
  10052. auto bindFuncVal = bindResult.mFunc;
  10053. if (mModule->mCompiler->mOptions.mAllowHotSwapping)
  10054. bindFuncVal = mModule->mBfIRBuilder->RemapBindFunction(bindFuncVal);
  10055. auto callResult = mModule->mBfIRBuilder->CreateCall(bindFuncVal, irArgs);
  10056. auto destCallingConv = mModule->GetIRCallingConvention(bindMethodInstance);
  10057. if (destCallingConv != BfIRCallingConv_CDecl)
  10058. mModule->mBfIRBuilder->SetCallCallingConv(callResult, destCallingConv);
  10059. if (methodInstance->mReturnType->IsValuelessType())
  10060. mModule->mBfIRBuilder->CreateRetVoid();
  10061. else
  10062. mModule->mBfIRBuilder->CreateRet(callResult);
  10063. mModule->mBfIRBuilder->SetActiveFunction(prevActiveFunction);
  10064. mModule->mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  10065. mModule->mBfIRBuilder->RestoreDebugLocation();
  10066. result = mModule->mBfIRBuilder->CreatePtrToInt(funcValue, BfTypeCode_IntPtr);
  10067. }
  10068. }
  10069. else
  10070. {
  10071. if ((bindResult.mOrigTarget) && (bindResult.mOrigTarget.mType->IsGenericParam()) && (bindResult.mMethodInstance->GetOwner()->IsInterface()))
  10072. {
  10073. bool matching = true;
  10074. if (methodInstance->HasExplicitThis())
  10075. {
  10076. auto thisType = methodInstance->GetParamType(0);
  10077. if (thisType->IsPointer())
  10078. thisType = thisType->GetUnderlyingType();
  10079. if (thisType->IsRef())
  10080. thisType = thisType->GetUnderlyingType();
  10081. matching = thisType == bindResult.mOrigTarget.mType;
  10082. }
  10083. if (matching)
  10084. {
  10085. mResult = BfTypedValue(mModule->mBfIRBuilder->GetFakeVal(), mExpectingType);
  10086. return;
  10087. }
  10088. }
  10089. result = mModule->CastToFunction(delegateBindExpr->mTarget, bindResult.mOrigTarget, bindResult.mMethodInstance, mExpectingType);
  10090. }
  10091. if (result)
  10092. mResult = BfTypedValue(result, mExpectingType);
  10093. return;
  10094. }
  10095. if (bindResult.mMethodInstance->mDisallowCalling)
  10096. {
  10097. BF_ASSERT(mModule->mBfIRBuilder->mIgnoreWrites);
  10098. mResult = mModule->GetDefaultTypedValue(mExpectingType, false, BfDefaultValueKind_Addr);
  10099. return;
  10100. }
  10101. auto methodRefType = mModule->CreateMethodRefType(bindResult.mMethodInstance);
  10102. mModule->AddDependency(methodRefType, mModule->mCurTypeInstance, BfDependencyMap::DependencyFlag_Calls);
  10103. mModule->AddCallDependency(bindResult.mMethodInstance);
  10104. if ((bindResult.mOrigTarget) && (bindResult.mOrigTarget.mType->IsMethodRef()))
  10105. {
  10106. mResult = bindResult.mOrigTarget;
  10107. }
  10108. else
  10109. {
  10110. if ((bindResult.mMethodInstance->mMethodDef->mIsLocalMethod) || (!bindResult.mTarget))
  10111. mResult = BfTypedValue(BfIRValue(BfIRValueFlags_Value, BfIRValue::ID_IMPLICIT), methodRefType);
  10112. else
  10113. {
  10114. auto methodRefPtr = mModule->CreateAlloca(methodRefType, "bindResult");
  10115. auto elemPtr = mModule->mBfIRBuilder->CreateInBoundsGEP(methodRefPtr, 0, 0);
  10116. BfTypedValue target;
  10117. if (bindResult.mTarget.IsSplat())
  10118. target = mModule->AggregateSplat(bindResult.mTarget, &bindResult.mIRArgs[0]);
  10119. else
  10120. target = mModule->LoadValue(bindResult.mTarget);
  10121. mModule->mBfIRBuilder->CreateStore(target.mValue, elemPtr);
  10122. mResult = BfTypedValue(methodRefPtr, methodRefType, true);
  10123. }
  10124. }
  10125. return;
  10126. }
  10127. int implicitParamCount = bindMethodInstance->GetImplicitParamCount();
  10128. BfTypeInstance* useTypeInstance = delegateTypeInstance;
  10129. BfClosureType* closureTypeInst = NULL;
  10130. auto origTarget = bindResult.mOrigTarget;
  10131. auto target = bindResult.mTarget;
  10132. BfTypedValue methodRefTarget;
  10133. if ((bindResult.mOrigTarget) && (bindResult.mOrigTarget.mType->IsMethodRef()))
  10134. methodRefTarget = bindResult.mOrigTarget;
  10135. bool isStructTarget = (target) && (target.mType->IsStruct());
  10136. bool bindCapturesThis = bindMethodInstance->HasThis() && !isStructTarget;
  10137. bool needsSplat = (isStructTarget) && (!bindMethodInstance->mMethodDef->mIsMutating) && (bindMethodInstance->AllowsSplatting(-1));
  10138. bool captureThisByValue = isStructTarget;
  10139. if (bindMethodInstance->mMethodDef->mIsLocalMethod)
  10140. {
  10141. // Local method captures always capture 'this' by reference
  10142. captureThisByValue = false;
  10143. }
  10144. if ((origTarget.mType != NULL) &&
  10145. ((origTarget.mType->IsRef()) || (origTarget.mType->IsPointer())))
  10146. {
  10147. captureThisByValue = false;
  10148. }
  10149. if (methodRefTarget)
  10150. BF_ASSERT(methodRefTarget.mType->IsMethodRef());
  10151. if (target.IsSplat())
  10152. target = mModule->AggregateSplat(target, &bindResult.mIRArgs[0]);
  10153. bool hasCaptures = false;
  10154. // Do we need a special delegate type for this?
  10155. if (((captureThisByValue) || (needsSplat) || (implicitParamCount > 0) /*|| (hasIncompatibleCallingConventions)*/) &&
  10156. (mModule->HasCompiledOutput()))
  10157. {
  10158. hasCaptures = true;
  10159. auto curProject = mModule->mCurTypeInstance->mTypeDef->mProject;
  10160. if (captureThisByValue)
  10161. target = mModule->LoadValue(target);
  10162. String delegateTypeName = mModule->TypeToString(delegateTypeInstance);
  10163. HashContext hashCtx;
  10164. hashCtx.MixinStr(delegateTypeName);
  10165. // We mix in the project for reasons described in the lambda binding handler
  10166. hashCtx.MixinStr(curProject->mName);
  10167. String structTargetTypeName;
  10168. String structTargetName;
  10169. // Implicit param separator
  10170. for (int implicitParamIdx = bindMethodInstance->HasThis() ? - 1 : 0; implicitParamIdx < implicitParamCount; implicitParamIdx++)
  10171. {
  10172. auto paramType = bindResult.mMethodInstance->GetParamType(implicitParamIdx);
  10173. if ((implicitParamIdx == -1) && (captureThisByValue))
  10174. {
  10175. if (paramType->IsPointer())
  10176. paramType = paramType->GetUnderlyingType();
  10177. }
  10178. structTargetTypeName = mModule->TypeToString(paramType);
  10179. structTargetName = bindResult.mMethodInstance->GetParamName(implicitParamIdx);
  10180. hashCtx.MixinStr(structTargetTypeName);
  10181. hashCtx.MixinStr(structTargetName);
  10182. }
  10183. Val128 hash128 = hashCtx.Finish128();
  10184. BfClosureType* checkClosureType = new BfClosureType(delegateTypeInstance, hash128);
  10185. checkClosureType->mContext = mModule->mContext;
  10186. checkClosureType->mBaseType = delegateTypeInstance;
  10187. BfType* resolvedClosureType = mModule->ResolveType(checkClosureType, BfPopulateType_TypeDef);
  10188. closureTypeInst = (BfClosureType*)resolvedClosureType;
  10189. if (checkClosureType == resolvedClosureType)
  10190. {
  10191. // This is a new closure type
  10192. closureTypeInst->Init(curProject);
  10193. for (int implicitParamIdx = bindMethodInstance->HasThis() ? -1 : 0; implicitParamIdx < implicitParamCount; implicitParamIdx++)
  10194. {
  10195. String fieldName = bindResult.mMethodInstance->GetParamName(implicitParamIdx);
  10196. BfType* paramType = bindResult.mMethodInstance->GetParamType(implicitParamIdx);
  10197. if ((implicitParamIdx == -1) && (captureThisByValue))
  10198. {
  10199. if (paramType->IsPointer())
  10200. paramType = paramType->GetUnderlyingType();
  10201. }
  10202. if (fieldName == "this")
  10203. fieldName = "__this";
  10204. closureTypeInst->AddField(paramType, fieldName);
  10205. }
  10206. closureTypeInst->Finish();
  10207. mModule->PopulateType(resolvedClosureType, BfPopulateType_Declaration);
  10208. }
  10209. else
  10210. {
  10211. // Already had this entry
  10212. delete checkClosureType;
  10213. }
  10214. useTypeInstance = closureTypeInst;
  10215. }
  10216. mModule->PopulateType(useTypeInstance);
  10217. if (delegateBindExpr->mTarget == NULL)
  10218. {
  10219. mModule->AssertErrorState();
  10220. return;
  10221. }
  10222. mResult = BfTypedValue(mModule->AllocFromType(useTypeInstance, allocTarget, BfIRValue(), BfIRValue(), 0, BfAllocFlags_None), useTypeInstance);
  10223. // Do we need specialized calling code for this?
  10224. BfIRValue funcValue;
  10225. if (((needsSplat) || (implicitParamCount > 0) || (hasIncompatibleCallingConventions)) &&
  10226. (mModule->HasCompiledOutput()))
  10227. {
  10228. int fieldIdx = 0;
  10229. for (int implicitParamIdx = bindMethodInstance->HasThis() ? -1 : 0; implicitParamIdx < implicitParamCount; implicitParamIdx++)
  10230. {
  10231. auto fieldInst = &useTypeInstance->mFieldInstances[fieldIdx];
  10232. int gepIdx = fieldInst->mDataIdx;
  10233. auto fieldPtr = mModule->mBfIRBuilder->CreateInBoundsGEP(mResult.mValue, 0, gepIdx);
  10234. auto fieldType = bindMethodInstance->GetParamType(implicitParamIdx);
  10235. if ((implicitParamIdx == -1) && (captureThisByValue))
  10236. {
  10237. if (fieldType->IsPointer())
  10238. fieldType = fieldType->GetUnderlyingType();
  10239. }
  10240. bool failed = false;
  10241. BfTypedValue lookupVal;
  10242. if (implicitParamIdx == -1)
  10243. lookupVal = target;
  10244. else
  10245. lookupVal = DoImplicitArgCapture(delegateBindExpr->mTarget, bindResult.mMethodInstance, implicitParamIdx, failed, BfImplicitParamKind_General, methodRefTarget);
  10246. if (!lookupVal)
  10247. continue;
  10248. if ((fieldType->IsPointer()) && (lookupVal.mType != fieldType))
  10249. {
  10250. BF_ASSERT(fieldType->GetUnderlyingType() == lookupVal.mType);
  10251. BF_ASSERT(lookupVal.IsAddr());
  10252. }
  10253. else if (!fieldType->IsRef())
  10254. lookupVal = mModule->LoadOrAggregateValue(lookupVal);
  10255. if (lookupVal)
  10256. mModule->mBfIRBuilder->CreateStore(lookupVal.mValue, fieldPtr);
  10257. fieldIdx++;
  10258. }
  10259. String methodName = _GetInvokeMethodName();
  10260. SizedArray<BfIRType, 8> irParamTypes;
  10261. BfIRType irReturnType;
  10262. bool hasThis = false;
  10263. if (hasCaptures)
  10264. {
  10265. hasThis = true;
  10266. methodInstance->GetIRFunctionInfo(mModule, irReturnType, irParamTypes);
  10267. int thisIdx = 0;
  10268. if (GetStructRetIdx(methodInstance) == 0)
  10269. thisIdx = 1;
  10270. irParamTypes[thisIdx] = mModule->mBfIRBuilder->MapType(useTypeInstance);
  10271. }
  10272. else
  10273. {
  10274. BF_ASSERT(hasIncompatibleCallingConventions);
  10275. bindMethodInstance->GetIRFunctionInfo(mModule, irReturnType, irParamTypes);
  10276. hasThis = bindMethodInstance->HasThis();
  10277. }
  10278. auto prevActiveFunction = mModule->mBfIRBuilder->GetActiveFunction();
  10279. auto prevInsertBlock = mModule->mBfIRBuilder->GetInsertBlock();
  10280. mModule->mBfIRBuilder->SaveDebugLocation();
  10281. auto funcType = mModule->mBfIRBuilder->CreateFunctionType(irReturnType, irParamTypes);
  10282. funcValue = mModule->mBfIRBuilder->CreateFunction(funcType, BfIRLinkageType_External, methodName);
  10283. if (GetStructRetIdx(methodInstance) != -1)
  10284. {
  10285. mModule->mBfIRBuilder->Func_AddAttribute(funcValue, GetStructRetIdx(methodInstance) + 1, BfIRAttribute_NoAlias);
  10286. mModule->mBfIRBuilder->Func_AddAttribute(funcValue, GetStructRetIdx(methodInstance) + 1, BfIRAttribute_StructRet);
  10287. }
  10288. auto srcCallingConv = mModule->GetIRCallingConvention(methodInstance);
  10289. if ((!hasThis) && (methodInstance->mCallingConvention == BfCallingConvention_Stdcall))
  10290. srcCallingConv = BfIRCallingConv_StdCall;
  10291. else if (methodInstance->mCallingConvention == BfCallingConvention_Fastcall)
  10292. srcCallingConv = BfIRCallingConv_FastCall;
  10293. mModule->mBfIRBuilder->SetFuncCallingConv(funcValue, srcCallingConv);
  10294. mModule->mBfIRBuilder->SetActiveFunction(funcValue);
  10295. auto entryBlock = mModule->mBfIRBuilder->CreateBlock("entry", true);
  10296. mModule->mBfIRBuilder->SetInsertPoint(entryBlock);
  10297. fieldIdx = 0;
  10298. SizedArray<BfIRValue, 8> irArgs;
  10299. int argIdx = 0;
  10300. if (GetStructRetIdx(bindMethodInstance) == 0)
  10301. {
  10302. irArgs.push_back(mModule->mBfIRBuilder->GetArgument(GetStructRetIdx(methodInstance)));
  10303. argIdx++;
  10304. }
  10305. for (int implicitParamIdx = bindMethodInstance->HasThis() ? -1 : 0; implicitParamIdx < implicitParamCount; implicitParamIdx++)
  10306. {
  10307. auto fieldInst = &useTypeInstance->mFieldInstances[fieldIdx];
  10308. int gepIdx = fieldInst->mDataIdx;
  10309. auto fieldType = bindMethodInstance->GetParamType(implicitParamIdx);
  10310. bool disableSplat = false;
  10311. if ((implicitParamIdx == -1) && (captureThisByValue))
  10312. {
  10313. if (fieldType->IsPointer())
  10314. {
  10315. fieldType = fieldType->GetUnderlyingType();
  10316. disableSplat = true;
  10317. }
  10318. }
  10319. int thisIdx = 0;
  10320. if (GetStructRetIdx(methodInstance) == 0)
  10321. thisIdx = 1;
  10322. auto fieldPtr = mModule->mBfIRBuilder->CreateInBoundsGEP(mModule->mBfIRBuilder->GetArgument(thisIdx), 0, gepIdx);
  10323. BfTypedValue typedVal(fieldPtr, fieldType, true);
  10324. PushArg(typedVal, irArgs, disableSplat);
  10325. fieldIdx++;
  10326. }
  10327. if (hasThis)
  10328. argIdx++;
  10329. if (GetStructRetIdx(bindMethodInstance) == 1)
  10330. {
  10331. irArgs.push_back(mModule->mBfIRBuilder->GetArgument(GetStructRetIdx(methodInstance)));
  10332. argIdx++;
  10333. }
  10334. for (int paramIdx = 0; paramIdx < methodInstance->GetParamCount(); paramIdx++)
  10335. {
  10336. auto paramType = methodInstance->GetParamType(paramIdx);
  10337. if ((paramType->IsSplattable()) && (!IsComptime()))
  10338. {
  10339. BfTypeUtils::SplatIterate([&](BfType* checkType) { irArgs.push_back(mModule->mBfIRBuilder->GetArgument(argIdx++)); }, paramType);
  10340. }
  10341. else if (!paramType->IsValuelessType())
  10342. {
  10343. irArgs.push_back(mModule->mBfIRBuilder->GetArgument(argIdx++));
  10344. }
  10345. }
  10346. auto bindFuncVal = bindResult.mFunc;
  10347. if (mModule->mCompiler->mOptions.mAllowHotSwapping)
  10348. bindFuncVal = mModule->mBfIRBuilder->RemapBindFunction(bindFuncVal);
  10349. auto callInst = mModule->mBfIRBuilder->CreateCall(bindFuncVal, irArgs);
  10350. if (GetStructRetIdx(bindMethodInstance) != -1)
  10351. mModule->mBfIRBuilder->Call_AddAttribute(callInst, GetStructRetIdx(bindMethodInstance) + 1, BfIRAttribute_StructRet);
  10352. auto destCallingConv = mModule->GetIRCallingConvention(bindMethodInstance);
  10353. if (destCallingConv != BfIRCallingConv_CDecl)
  10354. mModule->mBfIRBuilder->SetCallCallingConv(callInst, destCallingConv);
  10355. if ((methodInstance->mReturnType->IsValuelessType()) || (GetStructRetIdx(methodInstance) != -1))
  10356. {
  10357. mModule->mBfIRBuilder->CreateRetVoid();
  10358. }
  10359. else
  10360. {
  10361. mModule->mBfIRBuilder->CreateRet(callInst);
  10362. }
  10363. mModule->mBfIRBuilder->SetActiveFunction(prevActiveFunction);
  10364. mModule->mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  10365. mModule->mBfIRBuilder->RestoreDebugLocation();
  10366. }
  10367. else if ((closureTypeInst != NULL) && (captureThisByValue))
  10368. {
  10369. // 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
  10370. auto fieldPtr = mModule->mBfIRBuilder->CreateInBoundsGEP(mResult.mValue, 0, 1);
  10371. target = mModule->LoadValue(target);
  10372. mModule->mBfIRBuilder->CreateStore(target.mValue, fieldPtr);
  10373. target = BfTypedValue(fieldPtr, target.mType, true);
  10374. }
  10375. BfResolvedArgs resolvedArgs;
  10376. MatchConstructor(delegateBindExpr, delegateBindExpr, mResult, useTypeInstance, resolvedArgs, false, false);
  10377. auto baseDelegateType = VerifyBaseDelegateType(delegateTypeInstance->mBaseType);
  10378. auto baseDelegate = mModule->mBfIRBuilder->CreateBitCast(mResult.mValue, mModule->mBfIRBuilder->MapType(baseDelegateType, BfIRPopulateType_Full));
  10379. // >> delegate.mTarget = bindResult.mTarget
  10380. BfIRValue valPtr;
  10381. if (mModule->HasCompiledOutput())
  10382. {
  10383. if ((implicitParamCount > 0) || (needsSplat)) // Point back to self, it contains capture data
  10384. valPtr = mModule->mBfIRBuilder->CreateBitCast(mResult.mValue, mModule->mBfIRBuilder->GetPrimitiveType(BfTypeCode_NullPtr));
  10385. else if (bindResult.mTarget)
  10386. valPtr = mModule->mBfIRBuilder->CreateBitCast(target.mValue, mModule->mBfIRBuilder->GetPrimitiveType(BfTypeCode_NullPtr));
  10387. else
  10388. valPtr = mModule->GetDefaultValue(mModule->GetPrimitiveType(BfTypeCode_NullPtr));
  10389. auto fieldPtr = mModule->mBfIRBuilder->CreateInBoundsGEP(baseDelegate, 0, 2);
  10390. mModule->mBfIRBuilder->CreateStore(valPtr, fieldPtr);
  10391. }
  10392. if (!funcValue)
  10393. {
  10394. funcValue = bindResult.mFunc;
  10395. if (!funcValue)
  10396. {
  10397. if ((mModule->HasCompiledOutput()) && (!mModule->mBfIRBuilder->mIgnoreWrites))
  10398. mModule->AssertErrorState();
  10399. return;
  10400. }
  10401. if ((mModule->mCompiler->mOptions.mAllowHotSwapping) && (!bindResult.mMethodInstance->mMethodDef->mIsVirtual))
  10402. {
  10403. funcValue = mModule->mBfIRBuilder->RemapBindFunction(funcValue);
  10404. }
  10405. }
  10406. // >> delegate.mFuncPtr = bindResult.mFunc
  10407. auto nullPtrType = mModule->GetPrimitiveType(BfTypeCode_NullPtr);
  10408. valPtr = mModule->mBfIRBuilder->CreateBitCast(funcValue, mModule->mBfIRBuilder->MapType(nullPtrType));
  10409. auto fieldPtr = mModule->mBfIRBuilder->CreateInBoundsGEP(baseDelegate, 0, 1);
  10410. mModule->mBfIRBuilder->CreateStore(valPtr, fieldPtr);
  10411. }
  10412. void BfExprEvaluator::VisitLambdaBodies(BfAstNode* body, BfFieldDtorDeclaration* fieldDtor)
  10413. {
  10414. if (auto blockBody = BfNodeDynCast<BfBlock>(body))
  10415. mModule->VisitChild(blockBody);
  10416. else if (auto bodyExpr = BfNodeDynCast<BfExpression>(body))
  10417. {
  10418. auto result = mModule->CreateValueFromExpression(bodyExpr);
  10419. if ((result) && (mModule->mCurMethodState->mClosureState != NULL) &&
  10420. (mModule->mCurMethodState->mClosureState->mReturnTypeInferState == BfReturnTypeInferState_Inferring))
  10421. mModule->mCurMethodState->mClosureState->mReturnType = result.mType;
  10422. }
  10423. while (fieldDtor != NULL)
  10424. {
  10425. mModule->mCurMethodState->mLeftBlockUncond = false;
  10426. mModule->VisitChild(fieldDtor->mBody);
  10427. fieldDtor = fieldDtor->mNextFieldDtor;
  10428. }
  10429. }
  10430. BfLambdaInstance* BfExprEvaluator::GetLambdaInstance(BfLambdaBindExpression* lambdaBindExpr, BfAllocTarget& allocTarget)
  10431. {
  10432. auto rootMethodState = mModule->mCurMethodState->GetRootMethodState();
  10433. BfAstNodeList cacheNodeList;
  10434. cacheNodeList.mList.Add(lambdaBindExpr);
  10435. ///
  10436. {
  10437. auto checkMethodState = mModule->mCurMethodState;
  10438. while (checkMethodState != NULL)
  10439. {
  10440. if (checkMethodState->mMixinState != NULL)
  10441. cacheNodeList.mList.Add(checkMethodState->mMixinState->mSource);
  10442. checkMethodState = checkMethodState->mPrevMethodState;
  10443. }
  10444. }
  10445. bool isInferReturnType = (mBfEvalExprFlags & BfEvalExprFlags_InferReturnType) != 0;
  10446. BfLambdaInstance* lambdaInstance = NULL;
  10447. if ((!isInferReturnType) && (rootMethodState->mLambdaCache.TryGetValue(cacheNodeList, &lambdaInstance)))
  10448. return lambdaInstance;
  10449. static int sBindCount = 0;
  10450. sBindCount++;
  10451. bool isFunctionBind = false;
  10452. BfTypeInstance* delegateTypeInstance = NULL;
  10453. BfMethodInstance* invokeMethodInstance = NULL;
  10454. if (mExpectingType == NULL)
  10455. {
  10456. mModule->Fail("Cannot infer delegate type", lambdaBindExpr);
  10457. delegateTypeInstance = mModule->ResolveTypeDef(mModule->mCompiler->mActionTypeDef)->ToTypeInstance();
  10458. }
  10459. else
  10460. {
  10461. delegateTypeInstance = mExpectingType->ToTypeInstance();
  10462. if ((delegateTypeInstance == NULL) ||
  10463. ((!delegateTypeInstance->mTypeDef->mIsDelegate) && (!delegateTypeInstance->mTypeDef->mIsFunction)))
  10464. {
  10465. if (lambdaBindExpr->mFatArrowToken != NULL)
  10466. mModule->Fail("Can only bind lambdas to delegate types", lambdaBindExpr->mFatArrowToken);
  10467. delegateTypeInstance = mModule->ResolveTypeDef(mModule->mCompiler->mActionTypeDef)->ToTypeInstance();
  10468. }
  10469. else
  10470. {
  10471. invokeMethodInstance = mModule->GetRawMethodInstanceAtIdx(delegateTypeInstance, 0, "Invoke");
  10472. }
  10473. isFunctionBind = delegateTypeInstance->mTypeDef->mIsFunction;
  10474. }
  10475. if (auto tokenNode = BfNodeDynCast<BfTokenNode>(lambdaBindExpr->mNewToken))
  10476. {
  10477. if (isFunctionBind)
  10478. {
  10479. mModule->Fail("Function lambda binding does not require allocation", lambdaBindExpr->mNewToken);
  10480. }
  10481. else if (tokenNode->GetToken() == BfToken_Append)
  10482. {
  10483. mModule->Fail("Append allocation on delegate bind not supported", lambdaBindExpr->mNewToken);
  10484. }
  10485. }
  10486. if (invokeMethodInstance != NULL)
  10487. {
  10488. if ((int)lambdaBindExpr->mParams.size() < invokeMethodInstance->GetParamCount())
  10489. {
  10490. BfAstNode* refNode = lambdaBindExpr->mCloseParen;
  10491. if (refNode == NULL)
  10492. refNode = lambdaBindExpr;
  10493. mModule->Fail(StrFormat("Not enough parameters for delegate type '%s'. Expected %d more.",
  10494. mModule->TypeToString(delegateTypeInstance).c_str(), invokeMethodInstance->GetParamCount() - lambdaBindExpr->mParams.size()), refNode);
  10495. }
  10496. else if ((int)lambdaBindExpr->mParams.size() > invokeMethodInstance->GetParamCount())
  10497. {
  10498. BfAstNode* refNode = lambdaBindExpr->mParams[invokeMethodInstance->GetParamCount()];
  10499. mModule->Fail(StrFormat("Too many parameters for delegate type '%s'. Expected %d fewer.",
  10500. mModule->TypeToString(delegateTypeInstance).c_str(), lambdaBindExpr->mParams.size() - invokeMethodInstance->GetParamCount()), refNode);
  10501. }
  10502. }
  10503. auto autoComplete = GetAutoComplete();
  10504. bool wasCapturingMethodInfo = false;
  10505. if ((autoComplete != NULL) && (invokeMethodInstance != NULL))
  10506. {
  10507. wasCapturingMethodInfo = autoComplete->mIsCapturingMethodMatchInfo;
  10508. autoComplete->CheckInvocation(lambdaBindExpr, lambdaBindExpr->mOpenParen, lambdaBindExpr->mCloseParen, lambdaBindExpr->mCommas);
  10509. if (autoComplete->mIsCapturingMethodMatchInfo)
  10510. {
  10511. autoComplete->mMethodMatchInfo->mInstanceList.Clear();
  10512. auto methodMatchInfo = autoComplete->mMethodMatchInfo;
  10513. BfAutoComplete::MethodMatchEntry methodMatchEntry;
  10514. methodMatchEntry.mTypeInstance = invokeMethodInstance->GetOwner();
  10515. methodMatchEntry.mCurMethodInstance = mModule->mCurMethodInstance;
  10516. methodMatchEntry.mMethodDef = invokeMethodInstance->mMethodDef;
  10517. autoComplete->mMethodMatchInfo->mInstanceList.push_back(methodMatchEntry);
  10518. methodMatchInfo->mBestIdx = 0;
  10519. methodMatchInfo->mMostParamsMatched = 0;
  10520. int cursorIdx = lambdaBindExpr->GetParser()->mCursorIdx;
  10521. if ((lambdaBindExpr->mCloseParen == NULL) || (cursorIdx <= lambdaBindExpr->mCloseParen->GetSrcStart()))
  10522. {
  10523. int paramIdx = 0;
  10524. for (int commaIdx = 0; commaIdx < (int)lambdaBindExpr->mCommas.size(); commaIdx++)
  10525. {
  10526. auto commaNode = lambdaBindExpr->mCommas[commaIdx];
  10527. if ((commaNode != NULL) && (cursorIdx >= commaNode->GetSrcStart()))
  10528. paramIdx = commaIdx + 1;
  10529. }
  10530. bool isEmpty = true;
  10531. if (paramIdx < (int)lambdaBindExpr->mParams.size())
  10532. {
  10533. auto paramNode = lambdaBindExpr->mParams[paramIdx];
  10534. if (paramNode != NULL)
  10535. isEmpty = false;
  10536. }
  10537. if (isEmpty)
  10538. {
  10539. if (paramIdx < (int)invokeMethodInstance->GetParamCount())
  10540. {
  10541. String paramName = invokeMethodInstance->GetParamName(paramIdx);
  10542. autoComplete->mEntriesSet.Clear();
  10543. if (paramName.IsEmpty())
  10544. paramName += StrFormat("val%d", paramIdx + 1);
  10545. autoComplete->AddEntry(AutoCompleteEntry("paramName", paramName));
  10546. autoComplete->mInsertStartIdx = cursorIdx;
  10547. autoComplete->mInsertEndIdx = cursorIdx;
  10548. if ((paramIdx == 0) && (lambdaBindExpr->mParams.IsEmpty()))
  10549. {
  10550. String totalNames;
  10551. for (int checkIdx = 0; checkIdx < (int)invokeMethodInstance->GetParamCount(); checkIdx++)
  10552. {
  10553. if (!totalNames.IsEmpty())
  10554. totalNames += ", ";
  10555. String paramName = invokeMethodInstance->GetParamName(checkIdx);
  10556. if (paramName.IsEmpty())
  10557. paramName += StrFormat("val%d", checkIdx + 1);
  10558. totalNames += paramName;
  10559. }
  10560. autoComplete->AddEntry(AutoCompleteEntry("paramNames", totalNames));
  10561. }
  10562. }
  10563. }
  10564. }
  10565. }
  10566. }
  10567. defer
  10568. (
  10569. {
  10570. if (autoComplete != NULL)
  10571. autoComplete->mIsCapturingMethodMatchInfo = (wasCapturingMethodInfo) && (!autoComplete->mIsCapturingMethodMatchInfo);
  10572. }
  10573. );
  10574. if (lambdaBindExpr->mBody == NULL)
  10575. {
  10576. mModule->AssertErrorState();
  10577. return NULL;
  10578. }
  10579. if ((lambdaBindExpr->mNewToken == NULL) && (isInferReturnType))
  10580. {
  10581. // Method ref, but let this follow infer route
  10582. }
  10583. else if ((lambdaBindExpr->mNewToken == NULL) || (isFunctionBind))
  10584. {
  10585. if ((lambdaBindExpr->mNewToken != NULL) && (isFunctionBind))
  10586. mModule->Fail("Binds to functions should do not require allocations.", lambdaBindExpr->mNewToken);
  10587. if (lambdaBindExpr->mDtor != NULL)
  10588. {
  10589. mModule->Fail("Valueless method reference cannot contain destructor. Consider either removing destructor or using an allocated lambda.", lambdaBindExpr->mDtor->mTildeToken);
  10590. // Eat it
  10591. auto fieldDtor = lambdaBindExpr->mDtor;
  10592. while (fieldDtor != NULL)
  10593. {
  10594. mModule->VisitEmbeddedStatement(fieldDtor->mBody);
  10595. fieldDtor = fieldDtor->mNextFieldDtor;
  10596. }
  10597. }
  10598. if (invokeMethodInstance != NULL)
  10599. {
  10600. BfLocalMethod* localMethod = new BfLocalMethod();
  10601. localMethod->mMethodName = "anon";
  10602. localMethod->mSystem = mModule->mSystem;
  10603. localMethod->mModule = mModule;
  10604. localMethod->mExpectedFullName = mModule->GetLocalMethodName(localMethod->mMethodName, lambdaBindExpr->mFatArrowToken, mModule->mCurMethodState, mModule->mCurMethodState->mMixinState);
  10605. localMethod->mLambdaInvokeMethodInstance = invokeMethodInstance;
  10606. localMethod->mLambdaBindExpr = lambdaBindExpr;
  10607. localMethod->mDeclMethodState = mModule->mCurMethodState;
  10608. mModule->mContext->mLocalMethodGraveyard.push_back(localMethod);
  10609. auto moduleMethodInstance = mModule->GetLocalMethodInstance(localMethod, BfTypeVector());
  10610. if (moduleMethodInstance.mMethodInstance->mDisallowCalling)
  10611. {
  10612. mResult = mModule->GetDefaultTypedValue(mExpectingType, false, BfDefaultValueKind_Addr);
  10613. return NULL;
  10614. }
  10615. auto methodRefType = mModule->CreateMethodRefType(moduleMethodInstance.mMethodInstance);
  10616. mModule->AddDependency(methodRefType, mModule->mCurTypeInstance, BfDependencyMap::DependencyFlag_Calls);
  10617. mModule->AddCallDependency(moduleMethodInstance.mMethodInstance);
  10618. mResult = BfTypedValue(BfIRValue(BfIRValueFlags_Value, BfIRValue::ID_IMPLICIT), methodRefType);
  10619. return NULL;
  10620. }
  10621. }
  10622. //SetAndRestoreValue<bool> prevIgnoreIRWrites(mModule->mBfIRBuilder->mIgnoreWrites, mModule->mWantsIRIgnoreWrites);
  10623. SetAndRestoreValue<bool> prevIgnoreIRWrites(mModule->mBfIRBuilder->mIgnoreWrites, mModule->mWantsIRIgnoreWrites || mModule->mCurMethodInstance->mIsUnspecialized);
  10624. BfTypeInstance* outerClosure = NULL;
  10625. if ((mModule->mCurMethodState->mClosureState != NULL) && (!mModule->mCurMethodState->mClosureState->mCapturing))
  10626. outerClosure = mModule->mCurMethodState->mClosureState->mClosureType;
  10627. Val128 val128(delegateTypeInstance->mTypeId);
  10628. BfMethodState methodState;
  10629. methodState.mPrevMethodState = mModule->mCurMethodState;
  10630. BfIRFunctionType funcType;
  10631. auto voidType = mModule->GetPrimitiveType(BfTypeCode_None);
  10632. SizedArray<BfIRType, 0> paramTypes;
  10633. funcType = mModule->mBfIRBuilder->CreateFunctionType(mModule->mBfIRBuilder->MapType(voidType), paramTypes, false);
  10634. auto prevInsertBlock = mModule->mBfIRBuilder->GetInsertBlock();
  10635. BF_ASSERT(prevInsertBlock);
  10636. auto prevActiveFunction = mModule->mBfIRBuilder->GetActiveFunction();
  10637. mModule->mBfIRBuilder->SaveDebugLocation();
  10638. SetAndRestoreValue<bool> prevIgnoreWrites(mModule->mBfIRBuilder->mIgnoreWrites, true);
  10639. BfDeferredLocalAssignData deferredLocalAssignData;
  10640. if (mModule->mCurMethodState->mDeferredLocalAssignData != NULL)
  10641. deferredLocalAssignData.ExtendFrom(mModule->mCurMethodState->mDeferredLocalAssignData);
  10642. SetAndRestoreValue<BfMethodState*> prevMethodState(mModule->mCurMethodState, &methodState);
  10643. methodState.mIRHeadBlock = mModule->mBfIRBuilder->CreateBlock("head", true);
  10644. methodState.mIRInitBlock = mModule->mBfIRBuilder->CreateBlock("init", true);
  10645. methodState.mIREntryBlock = mModule->mBfIRBuilder->CreateBlock("entry", true);
  10646. methodState.mCurScope->mDIScope = prevMethodState.mPrevVal->mCurScope->mDIScope;//invokeMethodInstance->mDIFunction;
  10647. methodState.mCurLocalVarId = -1;
  10648. methodState.mIRFunction = prevMethodState.mPrevVal->mIRFunction;
  10649. methodState.mDeferredLocalAssignData = &deferredLocalAssignData;
  10650. mModule->mBfIRBuilder->SetInsertPoint(methodState.mIREntryBlock);
  10651. BfClosureState closureState;
  10652. if (delegateTypeInstance->IsDelegate())
  10653. closureState.mReturnType = mModule->GetDelegateReturnType(delegateTypeInstance);
  10654. else
  10655. closureState.mReturnType = mModule->mContext->mBfObjectType;
  10656. closureState.mCapturing = true;
  10657. closureState.mDeclaringMethodIsMutating = mModule->mCurMethodInstance->mMethodDef->mIsMutating;
  10658. methodState.mClosureState = &closureState;
  10659. closureState.mClosureType = outerClosure;
  10660. BF_ASSERT(methodState.mCurLocalVarId == -1);
  10661. int outerLocalsCount = (int)methodState.mLocals.size();
  10662. // static int sItrCount = 0;
  10663. // ++sItrCount;
  10664. // int itrCount = sItrCount;
  10665. // if ((itrCount == 8) || (itrCount == 10))
  10666. // {
  10667. // NOP;
  10668. // }
  10669. String delegateTypeName = mModule->TypeToString(delegateTypeInstance);
  10670. HashContext hashCtx;
  10671. hashCtx.MixinStr(delegateTypeName);
  10672. BfSource* bfSource = delegateTypeInstance->mTypeDef->mSource;
  10673. BfMethodDef* methodDef = new BfMethodDef();
  10674. methodDef->mDeclaringType = mModule->mCurMethodInstance->mMethodDef->mDeclaringType;
  10675. Val128 closureMethodHash;
  10676. OwnedVector<BfParameterDeclaration> tempParamDecls;
  10677. if ((autoComplete != NULL) && (autoComplete->mMethodMatchInfo != NULL) && (autoComplete->IsAutocompleteNode(lambdaBindExpr->mBody)))
  10678. {
  10679. // Don't show outer method match info when our cursor is inside a lambda expression (being passed as a parameter)
  10680. autoComplete->RemoveMethodMatchInfo();
  10681. }
  10682. if (invokeMethodInstance != NULL)
  10683. {
  10684. for (int paramIdx = 0; paramIdx < (int)invokeMethodInstance->mMethodDef->mParams.size(); paramIdx++)
  10685. {
  10686. auto invokeParamDef = invokeMethodInstance->mMethodDef->mParams[paramIdx];
  10687. BfParameterDef* paramDef = new BfParameterDef();
  10688. paramDef->mParamDeclaration = tempParamDecls.Alloc();
  10689. BfAstNode::Zero(paramDef->mParamDeclaration);
  10690. BfLocalVariable* localVar = new BfLocalVariable();
  10691. if (paramIdx < (int)lambdaBindExpr->mParams.size())
  10692. {
  10693. localVar->mName = lambdaBindExpr->mParams[paramIdx]->ToString();
  10694. localVar->mNameNode = lambdaBindExpr->mParams[paramIdx];
  10695. paramDef->mParamDeclaration->mNameNode = lambdaBindExpr->mParams[paramIdx];
  10696. }
  10697. else
  10698. {
  10699. mModule->AssertErrorState();
  10700. localVar->mName = invokeParamDef->mName;
  10701. paramDef->mParamDeclaration->mNameNode = NULL;
  10702. }
  10703. paramDef->mName = localVar->mName;
  10704. methodDef->mParams.push_back(paramDef);
  10705. localVar->mResolvedType = invokeMethodInstance->GetParamType(paramIdx);
  10706. localVar->mAssignedKind = BfLocalVarAssignKind_Unconditional;
  10707. localVar->mReadFromId = 0;
  10708. auto rootMethodState = methodState.GetRootMethodState();
  10709. localVar->mLocalVarId = rootMethodState->mCurLocalVarId++;
  10710. mModule->DoAddLocalVariable(localVar);
  10711. if (autoComplete != NULL)
  10712. autoComplete->CheckLocalDef(BfNodeDynCast<BfIdentifierNode>(paramDef->mParamDeclaration->mNameNode), methodState.mLocals.back());
  10713. auto resolvePassData = mModule->mCompiler->mResolvePassData;
  10714. if (resolvePassData != NULL)
  10715. resolvePassData->HandleLocalReference(BfNodeDynCast<BfIdentifierNode>(paramDef->mParamDeclaration->mNameNode), mModule->mCurTypeInstance->mTypeDef,
  10716. mModule->mCurMethodInstance->mMethodDef, localVar->mLocalVarId);
  10717. }
  10718. }
  10719. bool isAutocomplete = mModule->mCompiler->IsAutocomplete();
  10720. methodDef->mIdx = mModule->mCurMethodInstance->mMethodDef->mIdx;
  10721. methodDef->mBody = lambdaBindExpr->mBody;
  10722. ///
  10723. auto varMethodState = methodState.mPrevMethodState;
  10724. bool hasExplicitCaptureNames = false;
  10725. for (auto& captureEntry : allocTarget.mCaptureInfo.mCaptures)
  10726. {
  10727. if (captureEntry.mNameNode == NULL)
  10728. {
  10729. hasExplicitCaptureNames = false;
  10730. break;
  10731. }
  10732. hasExplicitCaptureNames = true;
  10733. }
  10734. auto _SetNotCapturedFlag = [&](bool notCaptured)
  10735. {
  10736. auto varMethodState = methodState.mPrevMethodState;
  10737. while (varMethodState != NULL)
  10738. {
  10739. for (int localIdx = 0; localIdx < varMethodState->mLocals.size(); localIdx++)
  10740. {
  10741. auto localVar = varMethodState->mLocals[localIdx];
  10742. localVar->mNotCaptured = notCaptured;
  10743. }
  10744. varMethodState = varMethodState->mPrevMethodState;
  10745. if (varMethodState == NULL)
  10746. break;
  10747. if (varMethodState->mMixinState != NULL)
  10748. break;
  10749. if (varMethodState->mClosureState != NULL)
  10750. {
  10751. if (!varMethodState->mClosureState->mCapturing)
  10752. break;
  10753. }
  10754. }
  10755. };
  10756. if (hasExplicitCaptureNames)
  10757. {
  10758. _SetNotCapturedFlag(true);
  10759. auto varMethodState = methodState.mPrevMethodState;
  10760. while (varMethodState != NULL)
  10761. {
  10762. for (auto& captureEntry : allocTarget.mCaptureInfo.mCaptures)
  10763. {
  10764. if (captureEntry.mNameNode != NULL)
  10765. {
  10766. StringT<64> captureName;
  10767. captureEntry.mNameNode->ToString(captureName);
  10768. BfLocalVarEntry* entry;
  10769. if (varMethodState->mLocalVarSet.TryGetWith<StringImpl&>(captureName, &entry))
  10770. {
  10771. auto localVar = entry->mLocalVar;
  10772. while (localVar != NULL)
  10773. {
  10774. if (autoComplete != NULL)
  10775. autoComplete->CheckLocalRef(captureEntry.mNameNode, localVar);
  10776. if (((mModule->mCurMethodState->mClosureState == NULL) || (mModule->mCurMethodState->mClosureState->mCapturing)) &&
  10777. (mModule->mCompiler->mResolvePassData != NULL) && (mModule->mCurMethodInstance != NULL))
  10778. mModule->mCompiler->mResolvePassData->HandleLocalReference(captureEntry.mNameNode, localVar->mNameNode, mModule->mCurTypeInstance->mTypeDef, rootMethodState->mMethodInstance->mMethodDef, localVar->mLocalVarId);
  10779. localVar->mNotCaptured = false;
  10780. localVar = localVar->mShadowedLocal;
  10781. }
  10782. }
  10783. }
  10784. }
  10785. varMethodState = varMethodState->mPrevMethodState;
  10786. if (varMethodState == NULL)
  10787. break;
  10788. if (varMethodState->mMixinState != NULL)
  10789. break;
  10790. if (varMethodState->mClosureState != NULL)
  10791. {
  10792. if (!varMethodState->mClosureState->mCapturing)
  10793. break;
  10794. }
  10795. }
  10796. }
  10797. BfClosureInstanceInfo* closureInstanceInfo = new BfClosureInstanceInfo();
  10798. auto checkInsertBlock = mModule->mBfIRBuilder->GetInsertBlock();
  10799. closureState.mCaptureStartAccessId = methodState.mPrevMethodState->GetRootMethodState()->mCurAccessId;
  10800. closureState.mCaptureVisitingBody = true;
  10801. closureState.mClosureInstanceInfo = closureInstanceInfo;
  10802. if ((mBfEvalExprFlags & BfEvalExprFlags_InferReturnType) != 0)
  10803. {
  10804. closureState.mReturnType = NULL;
  10805. closureState.mReturnTypeInferState = BfReturnTypeInferState_Inferring;
  10806. }
  10807. VisitLambdaBodies(lambdaBindExpr->mBody, lambdaBindExpr->mDtor);
  10808. if (hasExplicitCaptureNames)
  10809. _SetNotCapturedFlag(false);
  10810. // If we ended up being called by a method with a lower captureStartAccessId, propagate that to whoever is calling us, too...
  10811. if ((methodState.mPrevMethodState->mClosureState != NULL) && (methodState.mPrevMethodState->mClosureState->mCapturing))
  10812. {
  10813. auto prevClosureState = methodState.mPrevMethodState->mClosureState;
  10814. if (closureState.mCaptureStartAccessId < prevClosureState->mCaptureStartAccessId)
  10815. prevClosureState->mCaptureStartAccessId = closureState.mCaptureStartAccessId;
  10816. }
  10817. bool earlyExit = false;
  10818. if (isInferReturnType)
  10819. {
  10820. if ((closureState.mReturnTypeInferState == BfReturnTypeInferState_Fail) ||
  10821. (closureState.mReturnType == NULL))
  10822. {
  10823. mResult = BfTypedValue();
  10824. }
  10825. else
  10826. {
  10827. mResult = BfTypedValue(closureState.mReturnType);
  10828. }
  10829. earlyExit = true;
  10830. }
  10831. else if (mModule->mCurMethodInstance->mIsUnspecialized)
  10832. {
  10833. earlyExit = true;
  10834. mResult = mModule->GetDefaultTypedValue(delegateTypeInstance);
  10835. }
  10836. if (earlyExit)
  10837. {
  10838. prevIgnoreWrites.Restore();
  10839. mModule->mBfIRBuilder->RestoreDebugLocation();
  10840. mModule->mBfIRBuilder->SetActiveFunction(prevActiveFunction);
  10841. if (!prevInsertBlock.IsFake())
  10842. mModule->mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  10843. delete methodDef;
  10844. delete closureInstanceInfo;
  10845. return NULL;
  10846. }
  10847. closureState.mCaptureVisitingBody = false;
  10848. prevIgnoreWrites.Restore();
  10849. mModule->mBfIRBuilder->RestoreDebugLocation();
  10850. auto _GetCaptureType = [&](const StringImpl& str)
  10851. {
  10852. if (allocTarget.mCaptureInfo.mCaptures.IsEmpty())
  10853. return BfCaptureType_Copy;
  10854. for (auto& captureEntry : allocTarget.mCaptureInfo.mCaptures)
  10855. {
  10856. if ((captureEntry.mNameNode == NULL) || (captureEntry.mNameNode->Equals(str)))
  10857. {
  10858. captureEntry.mUsed = true;
  10859. return captureEntry.mCaptureType;
  10860. }
  10861. }
  10862. return BfCaptureType_None;
  10863. };
  10864. Array<BfClosureCapturedEntry> capturedEntries;
  10865. bool copyOuterCaptures = false;
  10866. //
  10867. {
  10868. auto varMethodState = methodState.mPrevMethodState;
  10869. while (varMethodState != NULL)
  10870. {
  10871. for (int localIdx = 0; localIdx < varMethodState->mLocals.size(); localIdx++)
  10872. {
  10873. auto localVar = varMethodState->mLocals[localIdx];
  10874. if ((localVar->mReadFromId >= closureState.mCaptureStartAccessId) || (localVar->mWrittenToId >= closureState.mCaptureStartAccessId))
  10875. {
  10876. if ((localVar->mIsThis) && (outerClosure != NULL))
  10877. {
  10878. continue;
  10879. }
  10880. auto outerLocal = localVar;
  10881. if ((localVar->mConstValue) || (localVar->mResolvedType->IsValuelessType()))
  10882. {
  10883. closureState.mConstLocals.push_back(*outerLocal);
  10884. continue;
  10885. }
  10886. BfClosureCapturedEntry capturedEntry;
  10887. auto capturedType = outerLocal->mResolvedType;
  10888. bool captureByRef = false;
  10889. auto captureType = _GetCaptureType(localVar->mName);
  10890. if (captureType == BfCaptureType_None)
  10891. {
  10892. continue;
  10893. }
  10894. if (!capturedType->IsRef())
  10895. {
  10896. if (captureType == BfCaptureType_Reference)
  10897. {
  10898. if (outerLocal->mIsThis)
  10899. {
  10900. if ((outerLocal->mResolvedType->IsValueType()) && (mModule->mCurMethodInstance->mMethodDef->HasNoThisSplat()))
  10901. captureByRef = true;
  10902. }
  10903. else if ((!localVar->mIsReadOnly) && (localVar->mWrittenToId >= closureState.mCaptureStartAccessId))
  10904. captureByRef = true;
  10905. }
  10906. }
  10907. else
  10908. {
  10909. if ((captureType != BfCaptureType_Reference) || (localVar->mWrittenToId < closureState.mCaptureStartAccessId))
  10910. {
  10911. capturedType = ((BfRefType*)capturedType)->mElementType;
  10912. }
  10913. }
  10914. if (captureByRef)
  10915. {
  10916. capturedType = mModule->CreateRefType(capturedType);
  10917. }
  10918. if (captureType == BfCaptureType_Reference)
  10919. capturedEntry.mExplicitlyByReference = true;
  10920. capturedEntry.mType = capturedType;
  10921. capturedEntry.mNameNode = outerLocal->mNameNode;
  10922. if (outerLocal->mName == "this")
  10923. capturedEntry.mName = "__this";
  10924. else
  10925. {
  10926. capturedEntry.mName = outerLocal->mName;
  10927. BfLocalVarEntry* entry = NULL;
  10928. if (varMethodState->mLocalVarSet.TryGetWith<StringImpl&>(capturedEntry.mName, &entry))
  10929. {
  10930. auto startCheckVar = entry->mLocalVar;
  10931. int shadowIdx = 0;
  10932. auto checkVar = startCheckVar;
  10933. while (checkVar != NULL)
  10934. {
  10935. if (checkVar == outerLocal)
  10936. {
  10937. // We only use mShadowIdx when we have duplicate name nodes (ie: in the case of for looks with iterator vs value)
  10938. auto shadowCheckVar = startCheckVar;
  10939. while (shadowCheckVar != checkVar)
  10940. {
  10941. if (shadowCheckVar->mNameNode == checkVar->mNameNode)
  10942. capturedEntry.mShadowIdx++;
  10943. shadowCheckVar = shadowCheckVar->mShadowedLocal;
  10944. }
  10945. for (int i = 0; i < shadowIdx; i++)
  10946. capturedEntry.mName.Insert(0, '@');
  10947. break;
  10948. }
  10949. shadowIdx++;
  10950. checkVar = checkVar->mShadowedLocal;
  10951. }
  10952. }
  10953. }
  10954. capturedEntries.Add(capturedEntry);
  10955. }
  10956. }
  10957. varMethodState = varMethodState->mPrevMethodState;
  10958. if (varMethodState == NULL)
  10959. break;
  10960. if (varMethodState->mMixinState != NULL)
  10961. break;
  10962. if (varMethodState->mClosureState != NULL)
  10963. {
  10964. if (!varMethodState->mClosureState->mCapturing)
  10965. break;
  10966. }
  10967. }
  10968. }
  10969. for (auto& captureEntry : allocTarget.mCaptureInfo.mCaptures)
  10970. {
  10971. if ((!captureEntry.mUsed) && (captureEntry.mNameNode != NULL))
  10972. mModule->Warn(0, "Capture specifier not used", captureEntry.mNameNode);
  10973. }
  10974. for (auto copyField : closureState.mReferencedOuterClosureMembers)
  10975. {
  10976. auto fieldDef = copyField->GetFieldDef();
  10977. auto captureType = _GetCaptureType(fieldDef->mName);
  10978. BfClosureCapturedEntry capturedEntry;
  10979. capturedEntry.mName = fieldDef->mName;
  10980. capturedEntry.mType = copyField->mResolvedType;
  10981. if ((captureType == BfCaptureType_Reference) && (capturedEntry.mType->IsRef()))
  10982. {
  10983. capturedEntry.mExplicitlyByReference = true;
  10984. }
  10985. else if ((captureType != BfCaptureType_Reference) && (capturedEntry.mType->IsRef()))
  10986. {
  10987. auto refType = (BfRefType*)capturedEntry.mType;
  10988. capturedEntry.mType = refType->mElementType;
  10989. }
  10990. else if ((captureType == BfCaptureType_Reference) && (!capturedEntry.mType->IsRef()) && (!fieldDef->mIsReadOnly))
  10991. {
  10992. capturedEntry.mType = mModule->CreateRefType(capturedEntry.mType);
  10993. }
  10994. }
  10995. std::sort(capturedEntries.begin(), capturedEntries.end());
  10996. bool hasCapture = false;
  10997. BfMethodInstanceGroup methodInstanceGroup;
  10998. methodInstanceGroup.mOwner = mModule->mCurTypeInstance;
  10999. methodInstanceGroup.mOnDemandKind = BfMethodOnDemandKind_AlwaysInclude;
  11000. BfMethodInstance* methodInstance = new BfMethodInstance();
  11001. methodInstance->mMethodInstanceGroup = &methodInstanceGroup;
  11002. methodInstance->GetMethodInfoEx()->mClosureInstanceInfo = closureInstanceInfo;
  11003. if (invokeMethodInstance != NULL)
  11004. methodInstance->mParams = invokeMethodInstance->mParams;
  11005. methodInstance->mIsClosure = true;
  11006. // We want the closure ID to match between hot reloads -- otherwise we wouldn't be able to modify them,
  11007. // so we use the charId from the 'fat arrow' token
  11008. int closureId = 0;
  11009. if (lambdaBindExpr->mFatArrowToken != NULL)
  11010. closureId = lambdaBindExpr->mFatArrowToken->GetStartCharId();
  11011. auto curProject = mModule->mCurTypeInstance->mTypeDef->mProject;
  11012. BF_ASSERT(curProject != NULL);
  11013. // We need to make these per-project even though you'd think we might not because we
  11014. // insert generic type specializations in the generic definition's project,
  11015. // BECAUSE: we would need to scan the captured fields the same way we scan the
  11016. // generic arguments to determine if each project can see it or not in the vdata
  11017. BfTypeInstance* useTypeInstance = delegateTypeInstance;
  11018. BfClosureType* closureTypeInst = NULL;
  11019. if ((capturedEntries.size() != 0) || (lambdaBindExpr->mDtor != NULL) || (copyOuterCaptures))
  11020. {
  11021. hashCtx.MixinStr(curProject->mName);
  11022. if (copyOuterCaptures)
  11023. {
  11024. // String typeName = mModule->DoTypeToString(outerClosure, BfTypeNameFlag_DisambiguateDups);
  11025. // hashCtx.MixinStr(typeName);
  11026. hashCtx.Mixin(outerClosure->mTypeId);
  11027. }
  11028. for (auto& capturedEntry : capturedEntries)
  11029. {
  11030. // String typeName = mModule->DoTypeToString(capturedEntry.mType, BfTypeNameFlag_DisambiguateDups);
  11031. // hashCtx.MixinStr(typeName);
  11032. hashCtx.Mixin(capturedEntry.mType->mTypeId);
  11033. hashCtx.MixinStr(capturedEntry.mName);
  11034. hashCtx.Mixin(capturedEntry.mExplicitlyByReference);
  11035. }
  11036. if (lambdaBindExpr->mDtor != NULL)
  11037. {
  11038. // Has DTOR thunk
  11039. bool hasDtorThunk = true;
  11040. hashCtx.Mixin(hasDtorThunk);
  11041. }
  11042. Val128 hash128 = hashCtx.Finish128();
  11043. BfClosureType* checkClosureType = new BfClosureType(delegateTypeInstance, hash128);
  11044. checkClosureType->mContext = mModule->mContext;
  11045. checkClosureType->mBaseType = delegateTypeInstance;
  11046. BfType* resolvedClosureType = mModule->ResolveType(checkClosureType, BfPopulateType_TypeDef);
  11047. closureTypeInst = (BfClosureType*)resolvedClosureType;
  11048. if (checkClosureType == resolvedClosureType)
  11049. {
  11050. // This is a new closure type
  11051. closureTypeInst->Init(curProject);
  11052. closureTypeInst->mTypeDef->mProject = curProject;
  11053. if (copyOuterCaptures)
  11054. {
  11055. for (auto& fieldInstance : outerClosure->mFieldInstances)
  11056. {
  11057. BfFieldDef* origFieldDef = fieldInstance.GetFieldDef();
  11058. BfFieldDef* fieldDef = closureTypeInst->AddField(fieldInstance.mResolvedType, origFieldDef->mName);
  11059. fieldDef->mIsReadOnly = origFieldDef->mIsReadOnly;
  11060. }
  11061. }
  11062. for (auto& capturedEntry : capturedEntries)
  11063. {
  11064. BfFieldDef* fieldDef = closureTypeInst->AddField(capturedEntry.mType, capturedEntry.mName);
  11065. if (!capturedEntry.mExplicitlyByReference)
  11066. fieldDef->mIsReadOnly = true;
  11067. }
  11068. if (lambdaBindExpr->mDtor != NULL)
  11069. {
  11070. auto dtorDef = closureTypeInst->AddDtor();
  11071. auto voidType = mModule->GetPrimitiveType(BfTypeCode_None);
  11072. auto voidPtrType = mModule->CreatePointerType(voidType);
  11073. closureTypeInst->AddField(voidPtrType, "__dtorThunk");
  11074. }
  11075. closureTypeInst->Finish();
  11076. }
  11077. else
  11078. {
  11079. // Already had this entry
  11080. delete checkClosureType;
  11081. }
  11082. useTypeInstance = closureTypeInst;
  11083. }
  11084. mModule->mBfIRBuilder->PopulateType(useTypeInstance);
  11085. mModule->PopulateType(useTypeInstance);
  11086. // If we are allowing hot swapping, we need to always mangle the name to non-static because if we add a capture
  11087. // later then we need to have the mangled names match
  11088. methodDef->mIsStatic = (closureTypeInst == NULL) && (!mModule->mCompiler->mOptions.mAllowHotSwapping);
  11089. SizedArray<BfIRType, 8> origParamTypes;
  11090. BfIRType origReturnType;
  11091. bool forceStatic = false;
  11092. if (invokeMethodInstance != NULL)
  11093. {
  11094. forceStatic = methodDef->mIsStatic;
  11095. auto invokeFunctionType = mModule->mBfIRBuilder->MapMethod(invokeMethodInstance);
  11096. invokeMethodInstance->GetIRFunctionInfo(mModule, origReturnType, origParamTypes, forceStatic);
  11097. }
  11098. else
  11099. {
  11100. origReturnType = mModule->mBfIRBuilder->MapType(mModule->GetPrimitiveType(BfTypeCode_None));
  11101. }
  11102. SizedArray<BfIRType, 3> newTypes;
  11103. if ((invokeMethodInstance != NULL) && (GetStructRetIdx(invokeMethodInstance, forceStatic) == 0))
  11104. newTypes.push_back(origParamTypes[0]);
  11105. if (!methodDef->mIsStatic)
  11106. newTypes.push_back(mModule->mBfIRBuilder->MapType(useTypeInstance));
  11107. if ((invokeMethodInstance != NULL) && (GetStructRetIdx(invokeMethodInstance, forceStatic) == 1))
  11108. newTypes.push_back(origParamTypes[1]);
  11109. int paramStartIdx = 0;
  11110. if ((invokeMethodInstance != NULL) && (GetStructRetIdx(invokeMethodInstance, forceStatic) != -1))
  11111. paramStartIdx++;
  11112. if (!methodDef->mIsStatic)
  11113. paramStartIdx++;
  11114. for (int i = paramStartIdx; i < (int)origParamTypes.size(); i++)
  11115. newTypes.push_back(origParamTypes[i]);
  11116. auto closureFuncType = mModule->mBfIRBuilder->CreateFunctionType(origReturnType, newTypes, false);
  11117. prevMethodState.Restore();
  11118. mModule->mBfIRBuilder->SetActiveFunction(prevActiveFunction);
  11119. if (!prevInsertBlock.IsFake())
  11120. mModule->mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  11121. // Just a check
  11122. mModule->mBfIRBuilder->GetInsertBlock();
  11123. //auto rootMethodState = mModule->mCurMethodState;
  11124. HashContext closureHashCtx;
  11125. closureHashCtx.Mixin(closureId);
  11126. // When we're a nested lambda, strip off the outer hash and closureTypeInst markers
  11127. methodDef->mName = mModule->mCurMethodInstance->mMethodDef->mName;
  11128. int prevSepPos = (int)methodDef->mName.LastIndexOf('$');
  11129. if (prevSepPos != -1)
  11130. {
  11131. closureHashCtx.Mixin(methodDef->mName.c_str() + prevSepPos, (int)methodDef->mName.length() - prevSepPos);
  11132. methodDef->mName.RemoveToEnd(prevSepPos);
  11133. }
  11134. // Mix in this because this can be emitted multiple times when there's multiple ctors and field initializers with lambdas
  11135. if (mModule->mCurMethodInstance->mMethodDef->mMethodType == BfMethodType_Ctor)
  11136. {
  11137. if (auto ctorDecl = BfNodeDynCast<BfConstructorDeclaration>(mModule->mCurMethodInstance->mMethodDef->mMethodDeclaration))
  11138. {
  11139. if (ctorDecl->mThisToken != NULL)
  11140. closureHashCtx.Mixin(ctorDecl->mThisToken->GetStartCharId());
  11141. }
  11142. }
  11143. auto checkMethodState = mModule->mCurMethodState;
  11144. while (checkMethodState != NULL)
  11145. {
  11146. if (checkMethodState->mMethodInstance != NULL)
  11147. {
  11148. if (checkMethodState->mMethodInstance->mMethodInfoEx != NULL)
  11149. {
  11150. for (auto methodGenericArg : checkMethodState->mMethodInstance->mMethodInfoEx->mMethodGenericArguments)
  11151. {
  11152. StringT<128> genericTypeName;
  11153. BfMangler::Mangle(genericTypeName, mModule->mCompiler->GetMangleKind(), methodGenericArg);
  11154. closureHashCtx.MixinStr(genericTypeName);
  11155. }
  11156. }
  11157. }
  11158. checkMethodState = checkMethodState->mPrevMethodState;
  11159. }
  11160. uint64 closureHash = closureHashCtx.Finish64();
  11161. methodDef->mName += "$";
  11162. methodDef->mName += BfTypeUtils::HashEncode64(closureHash);
  11163. methodInstance->mMethodDef = methodDef;
  11164. if (invokeMethodInstance != NULL)
  11165. {
  11166. methodInstance->mParams = invokeMethodInstance->mParams;
  11167. methodInstance->mReturnType = invokeMethodInstance->mReturnType;
  11168. }
  11169. else
  11170. methodInstance->mReturnType = mModule->GetPrimitiveType(BfTypeCode_None);
  11171. StringT<128> closureFuncName;
  11172. BfMangler::Mangle(closureFuncName, mModule->mCompiler->GetMangleKind(), methodInstance);
  11173. auto closureFunc = mModule->mBfIRBuilder->CreateFunction(closureFuncType, BfIRLinkageType_External, closureFuncName);
  11174. methodInstance->mIRFunction = closureFunc;
  11175. if (methodInstance->mIsReified)
  11176. mModule->CheckHotMethod(methodInstance, closureFuncName);
  11177. if ((methodInstance->mHotMethod != NULL) && (mModule->mCurMethodState->mHotDataReferenceBuilder))
  11178. mModule->mCurMethodState->mHotDataReferenceBuilder->mInnerMethods.Add(methodInstance->mHotMethod);
  11179. methodState.Reset();
  11180. lambdaInstance = new BfLambdaInstance();
  11181. rootMethodState->mLambdaCache[cacheNodeList] = lambdaInstance;
  11182. lambdaInstance->mDelegateTypeInstance = delegateTypeInstance;
  11183. lambdaInstance->mUseTypeInstance = useTypeInstance;
  11184. lambdaInstance->mClosureTypeInstance = closureTypeInst;
  11185. lambdaInstance->mOuterClosure = outerClosure;
  11186. lambdaInstance->mCopyOuterCaptures = copyOuterCaptures;
  11187. lambdaInstance->mDeclaringMethodIsMutating = mModule->mCurMethodInstance->mMethodDef->mIsMutating;
  11188. lambdaInstance->mIsStatic = methodDef->mIsStatic;
  11189. lambdaInstance->mClosureFunc = closureFunc;
  11190. lambdaInstance->mMethodInstance = methodInstance;
  11191. lambdaInstance->mConstLocals = closureState.mConstLocals;
  11192. lambdaInstance->mParamDecls = tempParamDecls;
  11193. lambdaInstance->mDeclMixinState = mModule->mCurMethodState->mMixinState;
  11194. if (lambdaInstance->mDeclMixinState != NULL)
  11195. lambdaInstance->mDeclMixinState->mHasDeferredUsage = true;
  11196. tempParamDecls.ClearWithoutDeleting();
  11197. closureState.mCapturing = false;
  11198. closureState.mClosureType = useTypeInstance;
  11199. closureInstanceInfo->mThisOverride = useTypeInstance;
  11200. mModule->mIncompleteMethodCount++;
  11201. SetAndRestoreValue<BfClosureState*> prevClosureState(mModule->mCurMethodState->mClosureState, &closureState);
  11202. if (mModule->HasCompiledOutput())
  11203. mModule->SetupIRMethod(methodInstance, methodInstance->mIRFunction, methodInstance->mAlwaysInline);
  11204. // This keeps us from giving errors twice. ProcessMethod can give errors when we capture by value but needed to
  11205. // capture by reference, so we still need to do it for resolve-only
  11206. bool processMethods = (mModule->mCompiler->GetAutoComplete() == NULL) && !mModule->mHadBuildError;
  11207. mModule->mBfIRBuilder->SaveDebugLocation();
  11208. //
  11209. {
  11210. BfGetSymbolReferenceKind prevSymbolRefKind = BfGetSymbolReferenceKind_None;
  11211. if (mModule->mCompiler->mResolvePassData != NULL)
  11212. {
  11213. prevSymbolRefKind = mModule->mCompiler->mResolvePassData->mGetSymbolReferenceKind;
  11214. mModule->mCompiler->mResolvePassData->mGetSymbolReferenceKind = BfGetSymbolReferenceKind_None;
  11215. }
  11216. if (processMethods)
  11217. {
  11218. // If we are in an always-ignored block, we will have mIgnoreWrites set
  11219. // SetAndRestoreValue<bool> prevWantsIgnoreWrite(mModule->mWantsIRIgnoreWrites, mModule->mBfIRBuilder->mIgnoreWrites);
  11220. // mModule->ProcessMethod(methodInstance);
  11221. }
  11222. if (mModule->mCompiler->mResolvePassData != NULL)
  11223. mModule->mCompiler->mResolvePassData->mGetSymbolReferenceKind = prevSymbolRefKind;
  11224. }
  11225. mModule->mBfIRBuilder->RestoreDebugLocation();
  11226. if (mModule->IsSkippingExtraResolveChecks())
  11227. closureFunc = BfIRFunction();
  11228. BfIRFunction dtorFunc;
  11229. if (lambdaBindExpr->mDtor != NULL)
  11230. {
  11231. SizedArray<BfIRType, 1> newTypes;
  11232. newTypes.push_back(mModule->mBfIRBuilder->MapType(useTypeInstance));
  11233. auto voidType = mModule->GetPrimitiveType(BfTypeCode_None);
  11234. auto dtorFuncType = mModule->mBfIRBuilder->CreateFunctionType(mModule->mBfIRBuilder->MapType(voidType), newTypes, false);
  11235. BfMethodDef* dtorMethodDef = new BfMethodDef();
  11236. dtorMethodDef->mDeclaringType = mModule->mCurMethodInstance->mMethodDef->mDeclaringType;
  11237. dtorMethodDef->mName = "~this$";
  11238. dtorMethodDef->mName += methodDef->mName;
  11239. dtorMethodDef->mMethodType = BfMethodType_Normal;
  11240. dtorMethodDef->mBody = lambdaBindExpr->mDtor;
  11241. dtorMethodDef->mIdx = mModule->mCurMethodInstance->mMethodDef->mIdx;
  11242. BfMethodInstance* dtorMethodInstance = new BfMethodInstance();
  11243. dtorMethodInstance->mMethodDef = dtorMethodDef;
  11244. dtorMethodInstance->mReturnType = mModule->GetPrimitiveType(BfTypeCode_None);
  11245. dtorMethodInstance->mMethodInstanceGroup = &methodInstanceGroup;
  11246. StringT<128> dtorMangledName;
  11247. BfMangler::Mangle(dtorMangledName, mModule->mCompiler->GetMangleKind(), dtorMethodInstance);
  11248. dtorFunc = mModule->mBfIRBuilder->CreateFunction(dtorFuncType, BfIRLinkageType_External, dtorMangledName);
  11249. mModule->SetupIRMethod(NULL, dtorFunc, false);
  11250. dtorMethodInstance->mIRFunction = dtorFunc;
  11251. mModule->mIncompleteMethodCount++;
  11252. mModule->mBfIRBuilder->SaveDebugLocation();
  11253. //
  11254. if (processMethods)
  11255. {
  11256. // If we are in an always-ignored block, we will have mIgnoreWrites set
  11257. // SetAndRestoreValue<bool> prevWantsIgnoreWrite(mModule->mWantsIRIgnoreWrites, mModule->mBfIRBuilder->mIgnoreWrites);
  11258. // mModule->ProcessMethod(dtorMethodInstance);
  11259. }
  11260. mModule->mBfIRBuilder->RestoreDebugLocation();
  11261. if (mModule->IsSkippingExtraResolveChecks())
  11262. dtorFunc = BfIRFunction();
  11263. if (dtorMethodInstance->mIsReified)
  11264. mModule->CheckHotMethod(dtorMethodInstance, dtorMangledName);
  11265. if ((dtorMethodInstance->mHotMethod != NULL) && (mModule->mCurMethodState->mHotDataReferenceBuilder))
  11266. mModule->mCurMethodState->mHotDataReferenceBuilder->mInnerMethods.Add(dtorMethodInstance->mHotMethod);
  11267. lambdaInstance->mDtorMethodInstance = dtorMethodInstance;
  11268. lambdaInstance->mDtorFunc = dtorFunc;
  11269. dtorMethodInstance->mMethodInstanceGroup = NULL;
  11270. }
  11271. prevClosureState.Restore();
  11272. if (!prevInsertBlock.IsFake())
  11273. mModule->mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  11274. for (auto& capturedEntry : capturedEntries)
  11275. {
  11276. BfLambdaCaptureInfo lambdaCapture;
  11277. if (capturedEntry.mName == "__this")
  11278. lambdaCapture.mName = "this";
  11279. else
  11280. lambdaCapture.mName = capturedEntry.mName;
  11281. lambdaInstance->mCaptures.Add(lambdaCapture);
  11282. closureInstanceInfo->mCaptureEntries.Add(capturedEntry);
  11283. }
  11284. if (processMethods)
  11285. rootMethodState->mDeferredLambdaInstances.Add(lambdaInstance);
  11286. methodInstance->mMethodInstanceGroup = NULL;
  11287. return lambdaInstance;
  11288. }
  11289. void BfExprEvaluator::Visit(BfLambdaBindExpression* lambdaBindExpr)
  11290. {
  11291. BfTokenNode* newToken = NULL;
  11292. BfAllocTarget allocTarget = ResolveAllocTarget(lambdaBindExpr->mNewToken, newToken);
  11293. if ((mModule->mCurMethodState != NULL) && (mModule->mCurMethodState->mClosureState != NULL) && (mModule->mCurMethodState->mClosureState->mBlindCapturing))
  11294. {
  11295. // We're just capturing. We just need to visit the bodies here. This helps infinite recursion with local methods containing lambdas calling each other
  11296. if (lambdaBindExpr->mBody != NULL)
  11297. mModule->VisitChild(lambdaBindExpr->mBody);
  11298. if ((lambdaBindExpr->mDtor != NULL) && (lambdaBindExpr->mDtor->mBody != NULL))
  11299. mModule->VisitChild(lambdaBindExpr->mDtor->mBody);
  11300. return;
  11301. }
  11302. BfLambdaInstance* lambdaInstance = GetLambdaInstance(lambdaBindExpr, allocTarget);
  11303. if (lambdaInstance == NULL)
  11304. return;
  11305. BfTypeInstance* delegateTypeInstance = lambdaInstance->mDelegateTypeInstance;
  11306. BfTypeInstance* useTypeInstance = lambdaInstance->mUseTypeInstance;
  11307. BfTypeInstance* closureTypeInst = lambdaInstance->mClosureTypeInstance;
  11308. mResult = BfTypedValue(mModule->AllocFromType(useTypeInstance, allocTarget, BfIRValue(), BfIRValue(), 0, BfAllocFlags_None), useTypeInstance);
  11309. if (!delegateTypeInstance->IsDelegate())
  11310. {
  11311. mModule->AssertErrorState();
  11312. return;
  11313. }
  11314. auto baseDelegateType = VerifyBaseDelegateType(delegateTypeInstance->mBaseType);
  11315. if (baseDelegateType == NULL)
  11316. {
  11317. mModule->Fail("Invalid delegate type", lambdaBindExpr);
  11318. return;
  11319. }
  11320. auto baseDelegate = mModule->mBfIRBuilder->CreateBitCast(mResult.mValue, mModule->mBfIRBuilder->MapType(baseDelegateType));
  11321. // >> delegate.mTarget = bindResult.mTarget
  11322. auto nullPtrType = mModule->GetPrimitiveType(BfTypeCode_NullPtr);
  11323. BfIRValue valPtr;
  11324. if (!lambdaInstance->mIsStatic)
  11325. valPtr = mModule->mBfIRBuilder->CreateBitCast(mResult.mValue, mModule->mBfIRBuilder->MapType(nullPtrType));
  11326. else
  11327. valPtr = mModule->GetDefaultValue(nullPtrType);
  11328. auto fieldPtr = mModule->mBfIRBuilder->CreateInBoundsGEP(baseDelegate, 0, 2);
  11329. mModule->mBfIRBuilder->CreateStore(valPtr, fieldPtr);
  11330. // >> delegate.mFuncPtr = bindResult.mFunc
  11331. if (lambdaInstance->mClosureFunc)
  11332. {
  11333. auto nullPtrType = mModule->GetPrimitiveType(BfTypeCode_NullPtr);
  11334. auto valPtr = mModule->mBfIRBuilder->CreateBitCast(lambdaInstance->mClosureFunc, mModule->mBfIRBuilder->MapType(nullPtrType));
  11335. auto fieldPtr = mModule->mBfIRBuilder->CreateInBoundsGEP(baseDelegate, 0, 1);
  11336. mModule->mBfIRBuilder->CreateStore(valPtr, fieldPtr);
  11337. }
  11338. mModule->AddDependency(useTypeInstance, mModule->mCurTypeInstance, BfDependencyMap::DependencyFlag_Calls);
  11339. // Copy captures into the delegate
  11340. if (lambdaInstance->mClosureTypeInstance != NULL)
  11341. {
  11342. int fieldIdx = 0;
  11343. if (lambdaInstance->mCopyOuterCaptures)
  11344. {
  11345. for (auto& fieldInstance : lambdaInstance->mOuterClosure->mFieldInstances)
  11346. {
  11347. if (!fieldInstance.mResolvedType->IsValuelessType())
  11348. {
  11349. BF_ASSERT(fieldInstance.mDataIdx == fieldIdx + 1);
  11350. auto localVar = mModule->mCurMethodState->mLocals[0];
  11351. auto capturedValue = mModule->mBfIRBuilder->CreateInBoundsGEP(localVar->mValue, 0, fieldInstance.mDataIdx);
  11352. capturedValue = mModule->mBfIRBuilder->CreateLoad(capturedValue);
  11353. auto fieldPtr = mModule->mBfIRBuilder->CreateInBoundsGEP(mResult.mValue, 0, fieldInstance.mDataIdx);
  11354. mModule->mBfIRBuilder->CreateStore(capturedValue, fieldPtr);
  11355. fieldIdx++;
  11356. }
  11357. }
  11358. }
  11359. int captureIdx = 0;
  11360. for (int captureIdx = 0; captureIdx < (int)lambdaInstance->mCaptures.size(); captureIdx++)
  11361. {
  11362. auto& capturedEntry = lambdaInstance->mCaptures[captureIdx];
  11363. auto& closureCaptureEntry = lambdaInstance->mMethodInstance->mMethodInfoEx->mClosureInstanceInfo->mCaptureEntries[captureIdx];
  11364. BfIdentifierNode* identifierNode = closureCaptureEntry.mNameNode;
  11365. BfIRValue capturedValue;
  11366. auto fieldInstance = &closureTypeInst->mFieldInstances[fieldIdx];
  11367. BfTypedValue capturedTypedVal;
  11368. if (identifierNode != NULL)
  11369. capturedTypedVal = DoImplicitArgCapture(NULL, identifierNode, closureCaptureEntry.mShadowIdx);
  11370. else
  11371. capturedTypedVal = LookupIdentifier(NULL, capturedEntry.mName);
  11372. if (!fieldInstance->mResolvedType->IsRef())
  11373. capturedTypedVal = mModule->LoadOrAggregateValue(capturedTypedVal);
  11374. else if (!capturedTypedVal.IsAddr())
  11375. {
  11376. mModule->Fail(StrFormat("Unable to capture '%s' by reference", capturedEntry.mName.c_str()), lambdaBindExpr);
  11377. break;
  11378. }
  11379. capturedValue = capturedTypedVal.mValue;
  11380. if (capturedValue)
  11381. {
  11382. if (!capturedTypedVal.mType->IsVar())
  11383. {
  11384. auto fieldPtr = mModule->mBfIRBuilder->CreateInBoundsGEP(mResult.mValue, 0, fieldInstance->mDataIdx);
  11385. mModule->mBfIRBuilder->CreateStore(capturedValue, fieldPtr);
  11386. }
  11387. }
  11388. else
  11389. {
  11390. mModule->Fail(StrFormat("Unable to capture '%s'", capturedEntry.mName.c_str()), lambdaBindExpr);
  11391. mModule->AssertErrorState();
  11392. }
  11393. fieldIdx++;
  11394. }
  11395. if (lambdaInstance->mDtorFunc)
  11396. {
  11397. auto fieldPtr = mModule->mBfIRBuilder->CreateInBoundsGEP(mResult.mValue, 0, closureTypeInst->mFieldInstances[fieldIdx].mDataIdx);
  11398. auto voidType = mModule->GetPrimitiveType(BfTypeCode_None);
  11399. auto voidPtrType = mModule->CreatePointerType(voidType);
  11400. auto dtorThunk = mModule->mBfIRBuilder->CreateBitCast(lambdaInstance->mDtorFunc, mModule->mBfIRBuilder->MapType(voidPtrType));
  11401. mModule->mBfIRBuilder->CreateStore(dtorThunk, fieldPtr);
  11402. fieldIdx++;
  11403. }
  11404. }
  11405. }
  11406. void BfExprEvaluator::ProcessArrayInitializer(BfTokenNode* openToken, const BfSizedArray<BfExpression*>& valueExprs, const BfSizedArray<BfTokenNode*>& commas, BfTokenNode* closeToken, int dimensions, SizedArrayImpl<int64>& dimLengths, int dim, bool& hasFailed)
  11407. {
  11408. bool setSize = false;
  11409. if (dim == dimLengths.size())
  11410. {
  11411. dimLengths.push_back((int)valueExprs.size());
  11412. setSize = true;
  11413. }
  11414. else if (dimLengths[dim] == -1)
  11415. {
  11416. dimLengths[dim] = (int)valueExprs.size();
  11417. setSize = true;
  11418. }
  11419. int64 initCountDiff = (int)valueExprs.size() - dimLengths[dim];
  11420. if ((dimLengths[dim] != -1) && (initCountDiff != 0) && (!hasFailed))
  11421. {
  11422. if (initCountDiff > 0)
  11423. {
  11424. mModule->Fail(StrFormat("Too many initializers, expected %d fewer", initCountDiff), valueExprs[(int)dimLengths[dim]]);
  11425. hasFailed = true;
  11426. }
  11427. else
  11428. {
  11429. // If it ends with ", ?) or ",)" then allow unsized
  11430. if (((valueExprs.size() == 0) || (BfNodeDynCast<BfUninitializedExpression>(valueExprs.back()) == NULL)) &&
  11431. (commas.size() < valueExprs.size()))
  11432. {
  11433. BfAstNode* refNode = closeToken;
  11434. if ((refNode == NULL) && (mModule->mParentNodeEntry != NULL))
  11435. refNode = mModule->mParentNodeEntry->mNode;
  11436. mModule->Fail(StrFormat("Too few initializer, expected %d more", -initCountDiff), refNode);
  11437. hasFailed = true;
  11438. }
  11439. }
  11440. }
  11441. for (int i = 0; i < (int)valueExprs.size(); i++)
  11442. {
  11443. BfExpression* expr = valueExprs[i];
  11444. if (auto uninitExpr = BfNodeDynCast<BfUninitializedExpression>(expr))
  11445. {
  11446. continue;
  11447. }
  11448. auto innerInitExpr = BfNodeDynCast<BfCollectionInitializerExpression>(expr);
  11449. if (dim < dimensions - 1)
  11450. {
  11451. if (innerInitExpr == NULL)
  11452. {
  11453. if (auto innerTupleExpr = BfNodeDynCast<BfTupleExpression>(expr))
  11454. {
  11455. ProcessArrayInitializer(innerTupleExpr->mOpenParen, innerTupleExpr->mValues, innerTupleExpr->mCommas, innerTupleExpr->mCloseParen, dimensions, dimLengths, dim + 1, hasFailed);
  11456. }
  11457. else if (auto parenExpr = BfNodeDynCast<BfParenthesizedExpression>(expr))
  11458. {
  11459. SizedArray<BfExpression*, 1> values;
  11460. values.Add(parenExpr->mExpression);
  11461. SizedArray<BfTokenNode*, 1> commas;
  11462. ProcessArrayInitializer(parenExpr->mOpenParen, values, commas, parenExpr->mCloseParen, dimensions, dimLengths, dim + 1, hasFailed);
  11463. }
  11464. else
  11465. {
  11466. hasFailed = true;
  11467. mModule->Fail("A nested array initializer is expected", expr);
  11468. continue;
  11469. }
  11470. }
  11471. else
  11472. ProcessArrayInitializer(innerInitExpr->mOpenBrace, innerInitExpr->mValues, innerInitExpr->mCommas, innerInitExpr->mCloseBrace, dimensions, dimLengths, dim + 1, hasFailed);
  11473. }
  11474. else if (innerInitExpr != NULL)
  11475. {
  11476. hasFailed = true;
  11477. mModule->Fail("Unexpected nested initializer", expr);
  11478. ProcessArrayInitializer(innerInitExpr->mOpenBrace, innerInitExpr->mValues, innerInitExpr->mCommas, innerInitExpr->mCloseBrace, dimensions, dimLengths, dim + 1, hasFailed);
  11479. }
  11480. else
  11481. {
  11482. //mModule->Fail("Expected initializer", )
  11483. }
  11484. }
  11485. }
  11486. void BfExprEvaluator::CheckObjectCreateTypeRef(BfType* expectingType, BfAstNode* afterNode)
  11487. {
  11488. auto autoComplete = GetAutoComplete();
  11489. if ((autoComplete != NULL) && (afterNode != NULL) && (autoComplete->mIsAutoComplete) &&
  11490. (afterNode->IsFromParser(mModule->mCompiler->mResolvePassData->mParser)) &&
  11491. (afterNode->GetParser()->mCursorIdx == afterNode->GetSrcEnd() + 1))
  11492. {
  11493. BfType* expectingType = mExpectingType;
  11494. BfTypeInstance* expectingTypeInst = NULL;
  11495. if (mExpectingType != NULL)
  11496. {
  11497. expectingTypeInst = mExpectingType->ToTypeInstance();
  11498. }
  11499. if ((mExpectingType != NULL) && (((expectingTypeInst == NULL) || (!expectingTypeInst->mTypeDef->mIsDelegate))))
  11500. {
  11501. // Why were we doing this? It floods the autocomplete with every possible type
  11502. //autoComplete->AddTopLevelTypes(NULL);
  11503. autoComplete->mInsertStartIdx = afterNode->GetSourceData()->ToParser()->mCursorIdx;
  11504. BF_ASSERT(autoComplete->mInsertStartIdx != -1);
  11505. auto expectingType = mExpectingType;
  11506. while (expectingType->IsArray())
  11507. {
  11508. auto arrayType = (BfArrayType*)expectingType;
  11509. expectingType = arrayType->mGenericTypeInfo->mTypeGenericArguments[0];
  11510. }
  11511. auto expectingTypeInst = expectingType->ToTypeInstance();
  11512. if (expectingTypeInst != NULL)
  11513. {
  11514. autoComplete->AddTypeInstanceEntry(expectingTypeInst);
  11515. }
  11516. else
  11517. autoComplete->mDefaultSelection = mModule->TypeToString(expectingType);
  11518. }
  11519. }
  11520. }
  11521. void BfExprEvaluator::Visit(BfObjectCreateExpression* objCreateExpr)
  11522. {
  11523. CreateObject(objCreateExpr, objCreateExpr->mNewNode, NULL);
  11524. }
  11525. void BfExprEvaluator::CreateObject(BfObjectCreateExpression* objCreateExpr, BfAstNode* allocNode, BfType* wantAllocType)
  11526. {
  11527. auto autoComplete = GetAutoComplete();
  11528. if ((autoComplete != NULL) && (objCreateExpr != NULL) && (objCreateExpr->mTypeRef != NULL))
  11529. {
  11530. autoComplete->CheckTypeRef(objCreateExpr->mTypeRef, false, true);
  11531. }
  11532. if ((autoComplete != NULL) && (objCreateExpr != NULL) && (objCreateExpr->mOpenToken != NULL) && (objCreateExpr->mCloseToken != NULL) &&
  11533. (objCreateExpr->mOpenToken->mToken == BfToken_LBrace) && (autoComplete->CheckFixit(objCreateExpr->mOpenToken)))
  11534. {
  11535. auto refNode = objCreateExpr->mOpenToken;
  11536. BfParserData* parser = refNode->GetSourceData()->ToParserData();
  11537. if (parser != NULL)
  11538. {
  11539. autoComplete->AddEntry(AutoCompleteEntry("fixit", StrFormat("Change initializer braces to parentheses\treformat|%s|%d-1|(\x01|%s|%d-1|)",
  11540. parser->mFileName.c_str(), refNode->mSrcStart,
  11541. parser->mFileName.c_str(), objCreateExpr->mCloseToken->mSrcStart).c_str()));
  11542. }
  11543. }
  11544. CheckObjectCreateTypeRef(mExpectingType, allocNode);
  11545. BfAttributeState attributeState;
  11546. attributeState.mTarget = BfAttributeTargets_Alloc;
  11547. SetAndRestoreValue<BfAttributeState*> prevAttributeState(mModule->mAttributeState, &attributeState);
  11548. BfTokenNode* newToken = NULL;
  11549. BfAllocTarget allocTarget = ResolveAllocTarget(allocNode, newToken, &attributeState.mCustomAttributes);
  11550. bool isScopeAlloc = newToken->GetToken() == BfToken_Scope;
  11551. bool isAppendAlloc = newToken->GetToken() == BfToken_Append;
  11552. bool isStackAlloc = (newToken->GetToken() == BfToken_Stack) || (isScopeAlloc);
  11553. bool isArrayAlloc = false;// (objCreateExpr->mArraySizeSpecifier != NULL);
  11554. bool isRawArrayAlloc = (objCreateExpr != NULL) && (objCreateExpr->mStarToken != NULL);
  11555. if (isScopeAlloc)
  11556. {
  11557. if ((mBfEvalExprFlags & BfEvalExprFlags_FieldInitializer) != 0)
  11558. {
  11559. mModule->Warn(0, "This allocation will only be in scope during the constructor. Consider using a longer-term allocation such as 'new'", allocNode);
  11560. }
  11561. if (allocNode == newToken) // Scope, no target specified
  11562. {
  11563. if (mModule->mParentNodeEntry != NULL)
  11564. {
  11565. if (auto assignExpr = BfNodeDynCastExact<BfAssignmentExpression>(mModule->mParentNodeEntry->mNode))
  11566. {
  11567. if (mModule->mCurMethodState->mCurScope->mCloseNode == NULL)
  11568. {
  11569. // 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
  11570. if ((mBfEvalExprFlags & BfEvalExprFlags_PendingPropSet) == 0)
  11571. mModule->Warn(0, "This allocation will immediately go out of scope. Consider specifying a wider scope target such as 'scope::'", allocNode);
  11572. }
  11573. }
  11574. }
  11575. }
  11576. }
  11577. BfAutoParentNodeEntry autoParentNodeEntry(mModule, objCreateExpr);
  11578. SizedArray<BfAstNode*, 2> dimLengthRefs;
  11579. SizedArray<BfIRValue, 2> dimLengthVals;
  11580. BfArrayType* arrayType = NULL;
  11581. BfType* unresolvedTypeRef = NULL;
  11582. BfType* resolvedTypeRef = NULL;
  11583. if (wantAllocType != NULL)
  11584. {
  11585. unresolvedTypeRef = wantAllocType;
  11586. resolvedTypeRef = wantAllocType;
  11587. }
  11588. else if (objCreateExpr->mTypeRef == NULL)
  11589. {
  11590. if ((!mExpectingType) || (!mExpectingType->IsArray()))
  11591. {
  11592. mModule->Fail("Cannot imply array type. Explicitly state array type or use array in an assignment to an array type.", objCreateExpr);
  11593. resolvedTypeRef = mModule->mContext->mBfObjectType;
  11594. unresolvedTypeRef = resolvedTypeRef;
  11595. }
  11596. else
  11597. {
  11598. auto arrayType = (BfArrayType*)mExpectingType;
  11599. unresolvedTypeRef = arrayType->GetUnderlyingType();
  11600. resolvedTypeRef = unresolvedTypeRef;
  11601. }
  11602. }
  11603. else
  11604. {
  11605. if ((objCreateExpr->mTypeRef->IsExact<BfDotTypeReference>()) && (mExpectingType != NULL))
  11606. {
  11607. //mModule->SetElementType(objCreateExpr->mTypeRef, BfSourceElementType_TypeRef);
  11608. if ((mExpectingType->IsObject()) || (mExpectingType->IsGenericParam()))
  11609. {
  11610. unresolvedTypeRef = mExpectingType;
  11611. if (unresolvedTypeRef->IsArray())
  11612. {
  11613. arrayType = (BfArrayType*)unresolvedTypeRef;
  11614. unresolvedTypeRef = unresolvedTypeRef->GetUnderlyingType();
  11615. isArrayAlloc = true;
  11616. }
  11617. }
  11618. else if (mExpectingType->IsPointer())
  11619. {
  11620. unresolvedTypeRef = mExpectingType->GetUnderlyingType();
  11621. }
  11622. }
  11623. if (unresolvedTypeRef == NULL)
  11624. {
  11625. if (auto arrayTypeRef = BfNodeDynCast<BfArrayTypeRef>(objCreateExpr->mTypeRef))
  11626. {
  11627. isArrayAlloc = true;
  11628. if (auto dotTypeRef = BfNodeDynCast<BfDotTypeReference>(arrayTypeRef->mElementType))
  11629. {
  11630. if ((mExpectingType != NULL) &&
  11631. ((mExpectingType->IsArray()) || (mExpectingType->IsPointer()) || (mExpectingType->IsSizedArray())))
  11632. unresolvedTypeRef = mExpectingType->GetUnderlyingType();
  11633. }
  11634. if (unresolvedTypeRef == NULL)
  11635. unresolvedTypeRef = mModule->ResolveTypeRef(arrayTypeRef->mElementType);
  11636. if (unresolvedTypeRef == NULL)
  11637. unresolvedTypeRef = mModule->mContext->mBfObjectType;
  11638. int dimensions = 1;
  11639. bool commaExpected = false;
  11640. if (arrayTypeRef->mParams.size() != 0)
  11641. {
  11642. auto intType = mModule->ResolveTypeDef(mModule->mSystem->mTypeIntPtr);
  11643. for (auto arg : arrayTypeRef->mParams)
  11644. {
  11645. if (auto tokenNode = BfNodeDynCastExact<BfTokenNode>(arg))
  11646. {
  11647. if (tokenNode->GetToken() == BfToken_Comma)
  11648. {
  11649. if (isRawArrayAlloc)
  11650. {
  11651. mModule->Fail("Sized arrays cannot be multidimensional.", tokenNode);
  11652. continue;
  11653. }
  11654. dimensions++;
  11655. if (dimensions == 5)
  11656. {
  11657. mModule->Fail("Too many array dimensions, consider using a jagged array.", tokenNode);
  11658. }
  11659. commaExpected = false;
  11660. continue;
  11661. }
  11662. }
  11663. auto expr = BfNodeDynCast<BfExpression>(arg);
  11664. if ((isRawArrayAlloc) && (!dimLengthVals.IsEmpty()))
  11665. {
  11666. mModule->CreateValueFromExpression(expr, intType);
  11667. continue;
  11668. }
  11669. dimLengthRefs.Add(expr);
  11670. BfTypedValue dimLength;
  11671. if (expr == NULL)
  11672. {
  11673. // Not specified
  11674. dimLengthVals.push_back(BfIRValue());
  11675. continue;
  11676. }
  11677. if (arg != NULL)
  11678. {
  11679. dimLength = mModule->CreateValueFromExpression(expr, intType, BfEvalExprFlags_NoCast);
  11680. BfCastFlags castFlags = BfCastFlags_None;
  11681. if ((dimLength) && (dimLength.mType->IsInteger()))
  11682. {
  11683. // Allow uint for size - just force to int
  11684. if (!((BfPrimitiveType*)dimLength.mType)->IsSigned())
  11685. castFlags = BfCastFlags_Explicit;
  11686. }
  11687. if (dimLength)
  11688. dimLength = mModule->Cast(expr, dimLength, intType, castFlags);
  11689. }
  11690. if (commaExpected)
  11691. {
  11692. mModule->AssertErrorState();
  11693. continue;
  11694. }
  11695. if (!dimLength)
  11696. {
  11697. dimLength = mModule->GetDefaultTypedValue(intType);
  11698. }
  11699. dimLengthVals.push_back(dimLength.mValue);
  11700. commaExpected = true;
  11701. }
  11702. }
  11703. if ((arrayTypeRef->mParams.size() == 0) && (objCreateExpr->mOpenToken == NULL))
  11704. mModule->Fail("Array size or array initializer expected", arrayTypeRef->mOpenBracket);
  11705. if (dimensions > 4)
  11706. dimensions = 4;
  11707. if (!isRawArrayAlloc)
  11708. arrayType = mModule->CreateArrayType(unresolvedTypeRef, dimensions);
  11709. }
  11710. if (unresolvedTypeRef == NULL)
  11711. {
  11712. unresolvedTypeRef = ResolveTypeRef(objCreateExpr->mTypeRef, BfPopulateType_Declaration, BfResolveTypeRefFlag_NoResolveGenericParam);
  11713. }
  11714. }
  11715. resolvedTypeRef = unresolvedTypeRef;
  11716. if ((resolvedTypeRef != NULL) && (resolvedTypeRef->IsVar()))
  11717. resolvedTypeRef = unresolvedTypeRef;
  11718. }
  11719. if (resolvedTypeRef == NULL)
  11720. {
  11721. unresolvedTypeRef = mModule->GetPrimitiveType(BfTypeCode_Var);
  11722. resolvedTypeRef = unresolvedTypeRef;
  11723. }
  11724. auto resultType = resolvedTypeRef;
  11725. if ((resolvedTypeRef->IsInterface()) && (!isArrayAlloc))
  11726. {
  11727. mModule->Fail("Cannot create an instance of an interface", objCreateExpr->mTypeRef);
  11728. resolvedTypeRef = mModule->mContext->mBfObjectType;
  11729. }
  11730. BfTypeInstance* typeInstance = resolvedTypeRef->ToTypeInstance();
  11731. int elementSize = resolvedTypeRef->mSize;
  11732. int elementAlign = resolvedTypeRef->mAlign;
  11733. BfIRType allocType = mModule->mBfIRBuilder->MapType(resolvedTypeRef);
  11734. if (typeInstance != NULL)
  11735. {
  11736. if (!mModule->mCurTypeInstance->mResolvingVarField)
  11737. mModule->PopulateType(typeInstance);
  11738. if ((typeInstance->mTypeDef->mIsDelegate) && (!isArrayAlloc))
  11739. mModule->Fail("Delegates must be constructed through delegate binding", objCreateExpr->mTypeRef);
  11740. elementSize = BF_MAX(0, typeInstance->mInstSize);
  11741. elementAlign = typeInstance->mInstAlign;
  11742. allocType = mModule->mBfIRBuilder->MapTypeInst(typeInstance);
  11743. }
  11744. if (isAppendAlloc)
  11745. {
  11746. if (!mModule->mCurTypeInstance->IsObject())
  11747. {
  11748. mModule->Fail("Append allocations are only allowed in classes", allocNode);
  11749. isAppendAlloc = false;
  11750. }
  11751. else if ((mBfEvalExprFlags & BfEvalExprFlags_VariableDeclaration) == 0)
  11752. {
  11753. mModule->Fail("Append allocations are only allowed as local variable initializers in constructor body", allocNode);
  11754. isAppendAlloc = false;
  11755. }
  11756. else
  11757. {
  11758. auto methodDef = mModule->mCurMethodInstance->mMethodDef;
  11759. if (methodDef->mMethodType == BfMethodType_CtorCalcAppend)
  11760. {
  11761. mModule->Fail("Append allocations are only allowed as local variable declarations in the main method body", allocNode);
  11762. isAppendAlloc = false;
  11763. }
  11764. else if (!methodDef->mHasAppend)
  11765. {
  11766. mModule->Fail("Append allocations can only be used on constructors with [AllowAppend] specified", allocNode);
  11767. isAppendAlloc = false;
  11768. }
  11769. else if (methodDef->mMethodType != BfMethodType_Ctor)
  11770. {
  11771. mModule->Fail("Append allocations are only allowed in constructors", allocNode);
  11772. isAppendAlloc = false;
  11773. }
  11774. else if (methodDef->mIsStatic)
  11775. {
  11776. mModule->Fail("Append allocations are only allowed in non-static constructors", allocNode);
  11777. isAppendAlloc = false;
  11778. }
  11779. }
  11780. }
  11781. if (isArrayAlloc)
  11782. {
  11783. const int MAX_DIMENSIONS = 2;
  11784. int dimensions = 1;
  11785. if (arrayType != NULL)
  11786. {
  11787. dimensions = arrayType->mDimensions;
  11788. mModule->AddDependency(arrayType, mModule->mCurTypeInstance, BfDependencyMap::DependencyFlag_Calls);
  11789. }
  11790. bool zeroMemory = true;
  11791. if (objCreateExpr->mOpenToken != NULL)
  11792. {
  11793. if ((objCreateExpr->mArguments.size() == 1) &&
  11794. (BfNodeDynCastExact<BfUninitializedExpression>(objCreateExpr->mArguments[0]) != NULL))
  11795. {
  11796. // Special case for a single "{ ? }"
  11797. zeroMemory = false;
  11798. }
  11799. else
  11800. {
  11801. SizedArray<int64, 2> dimLengths;
  11802. if (dimLengthVals.size() != 0)
  11803. {
  11804. for (int dim = 0; dim < dimensions; dim++)
  11805. {
  11806. BfIRValue dimLengthVal;
  11807. if (dim < (int)dimLengthVals.size())
  11808. dimLengthVal = dimLengthVals[dim];
  11809. if (!dimLengthVal)
  11810. {
  11811. dimLengths.push_back(-1);
  11812. continue;
  11813. }
  11814. auto constant = mModule->mBfIRBuilder->GetConstant(dimLengthVal);
  11815. if ((constant != NULL) && (mModule->mBfIRBuilder->IsInt(constant->mTypeCode)))
  11816. {
  11817. int64 dimLength = constant->mInt64;
  11818. dimLengths.push_back(dimLength);
  11819. }
  11820. else
  11821. {
  11822. mModule->Fail("A constant length is required when using an initializer", dimLengthRefs[dim]);
  11823. dimLengths.push_back(-1);
  11824. }
  11825. }
  11826. }
  11827. // Ending in an ", )" means we need to zero-fill ending
  11828. zeroMemory = objCreateExpr->mCommas.size() >= objCreateExpr->mArguments.size();
  11829. bool hasFailed = false;
  11830. ProcessArrayInitializer(objCreateExpr->mOpenToken, objCreateExpr->mArguments, objCreateExpr->mCommas, objCreateExpr->mCloseToken, dimensions, dimLengths, 0, hasFailed);
  11831. dimLengthVals.resize(dimLengths.size());
  11832. for (int i = 0; i < (int)dimLengthVals.size(); i++)
  11833. {
  11834. if (!dimLengthVals[i])
  11835. {
  11836. auto intType = mModule->GetPrimitiveType(BfTypeCode_IntPtr);
  11837. dimLengthVals[i] = mModule->GetConstValue(dimLengths[i], intType);
  11838. }
  11839. }
  11840. }
  11841. }
  11842. while ((int)dimLengthVals.size() < dimensions)
  11843. dimLengthVals.push_back(mModule->GetConstValue(0));
  11844. BfTypedValue arrayValue;
  11845. BfIRValue arraySize;
  11846. for (BfIRValue dimSize : dimLengthVals)
  11847. {
  11848. if (!arraySize)
  11849. arraySize = dimSize;
  11850. else
  11851. arraySize = mModule->mBfIRBuilder->CreateMul(arraySize, dimSize);
  11852. }
  11853. BfAllocFlags allocFlags = BfAllocFlags_None;
  11854. if (isRawArrayAlloc)
  11855. allocFlags = (BfAllocFlags)(allocFlags | BfAllocFlags_RawArray);
  11856. int writeIdx = 0;
  11857. struct BfInitContext
  11858. {
  11859. public:
  11860. BfModule* mModule;
  11861. BfType* resultType;
  11862. int dimensions;
  11863. SizedArray<BfIRValue, 2>& dimLengthVals;
  11864. BfIRValue arraySize;
  11865. int& writeIdx;
  11866. BfInitContext(BfModule* module, BfType* resultType, int dimensions, SizedArray<BfIRValue, 2>& dimLengthVals, BfIRValue arraySize, int& writeIdx) :
  11867. mModule(module), resultType(resultType), dimensions(dimensions), dimLengthVals(dimLengthVals), arraySize(arraySize), writeIdx(writeIdx)
  11868. {
  11869. }
  11870. void Handle(BfIRValue addr, int curDim, const BfSizedArray<BfExpression*>& valueExprs)
  11871. {
  11872. int exprIdx = 0;
  11873. int dimWriteIdx = 0;
  11874. bool isUninit = false;
  11875. int dimLength = -1;
  11876. if (dimLengthVals[curDim].IsConst())
  11877. {
  11878. auto constant = mModule->mBfIRBuilder->GetConstant(dimLengthVals[curDim]);
  11879. dimLength = constant->mInt32;
  11880. }
  11881. while (exprIdx < (int)valueExprs.size())
  11882. {
  11883. auto initExpr = valueExprs[exprIdx];
  11884. exprIdx++;
  11885. if (!initExpr)
  11886. break;
  11887. if (auto unintExpr = BfNodeDynCastExact<BfUninitializedExpression>(initExpr))
  11888. {
  11889. isUninit = true;
  11890. break;
  11891. }
  11892. if (exprIdx > dimLength)
  11893. break;
  11894. if (curDim < dimensions - 1)
  11895. {
  11896. if (auto innerTupleExpr = BfNodeDynCast<BfTupleExpression>(initExpr))
  11897. {
  11898. Handle(addr, curDim + 1, innerTupleExpr->mValues);
  11899. }
  11900. else if (auto parenExpr = BfNodeDynCast<BfParenthesizedExpression>(initExpr))
  11901. {
  11902. SizedArray<BfExpression*, 1> values;
  11903. values.Add(parenExpr->mExpression);
  11904. Handle(addr, curDim + 1, values);
  11905. }
  11906. else if (auto innerInitExpr = BfNodeDynCast<BfCollectionInitializerExpression>(initExpr))
  11907. {
  11908. Handle(addr, curDim + 1, innerInitExpr->mValues);
  11909. }
  11910. dimWriteIdx++;
  11911. continue;
  11912. }
  11913. BfIRValue elemAddr;
  11914. if (!resultType->IsValuelessType())
  11915. elemAddr = mModule->CreateIndexedValue(resultType, addr, writeIdx);
  11916. else
  11917. elemAddr = mModule->mBfIRBuilder->GetFakeVal();
  11918. writeIdx++;
  11919. dimWriteIdx++;
  11920. BfTypedValue elemPtrTypedVal = BfTypedValue(elemAddr, resultType, BfTypedValueKind_Addr);
  11921. BfExprEvaluator exprEvaluator(mModule);
  11922. exprEvaluator.mExpectingType = resultType;
  11923. exprEvaluator.mReceivingValue = &elemPtrTypedVal;
  11924. exprEvaluator.Evaluate(initExpr);
  11925. exprEvaluator.GetResult();
  11926. if (exprEvaluator.mReceivingValue == NULL)
  11927. {
  11928. // We wrote directly to the array in-place, we're done with this element
  11929. continue;
  11930. }
  11931. auto storeValue = exprEvaluator.mResult;
  11932. if (!storeValue)
  11933. continue;
  11934. storeValue = mModule->Cast(initExpr, storeValue, resultType);
  11935. if (!storeValue)
  11936. continue;
  11937. if (!resultType->IsValuelessType())
  11938. {
  11939. storeValue = mModule->LoadOrAggregateValue(storeValue);
  11940. mModule->mBfIRBuilder->CreateStore(storeValue.mValue, elemAddr);
  11941. }
  11942. }
  11943. int clearFromIdx = writeIdx;
  11944. int sectionElemCount = 1;
  11945. BfIRValue numElemsLeft = arraySize;
  11946. if (dimLength != -1)
  11947. {
  11948. int clearCount = dimLength - dimWriteIdx;
  11949. if (clearCount > 0)
  11950. {
  11951. for (int checkDim = curDim + 1; checkDim < (int)dimLengthVals.size(); checkDim++)
  11952. {
  11953. if (dimLengthVals[checkDim].IsConst())
  11954. {
  11955. auto constant = mModule->mBfIRBuilder->GetConstant(dimLengthVals[checkDim]);
  11956. clearCount *= constant->mInt32;
  11957. sectionElemCount *= constant->mInt32;
  11958. }
  11959. }
  11960. }
  11961. writeIdx += clearCount;
  11962. numElemsLeft = mModule->GetConstValue(clearCount);
  11963. }
  11964. // Actually leave it alone?
  11965. if ((isUninit) &&
  11966. ((mModule->IsOptimized()) || (mModule->mIsComptimeModule) || (mModule->mBfIRBuilder->mIgnoreWrites)))
  11967. return;
  11968. bool doClear = true;
  11969. if (numElemsLeft.IsConst())
  11970. {
  11971. auto constant = mModule->mBfIRBuilder->GetConstant(numElemsLeft);
  11972. doClear = constant->mInt64 > 0;
  11973. }
  11974. if (doClear)
  11975. {
  11976. // We multiply by GetStride. This relies on the fact that we over-allocate on the array allocation -- the last
  11977. // element doesn't need to be padded out to the element alignment, but we do anyway. Otherwise this would be
  11978. // a more complicated computation
  11979. auto clearBytes = mModule->mBfIRBuilder->CreateMul(numElemsLeft, mModule->GetConstValue(resultType->GetStride()));
  11980. if (isUninit)
  11981. {
  11982. // Limit to a reasonable number of bytes to stomp with 0xCC
  11983. int maxStompBytes = BF_MIN(128, resultType->GetStride() * sectionElemCount);
  11984. if (clearBytes.IsConst())
  11985. {
  11986. auto constant = mModule->mBfIRBuilder->GetConstant(clearBytes);
  11987. if (constant->mInt64 > maxStompBytes)
  11988. clearBytes = mModule->GetConstValue(maxStompBytes);
  11989. }
  11990. else
  11991. {
  11992. auto insertBlock = mModule->mBfIRBuilder->GetInsertBlock();
  11993. auto gtBlock = mModule->mBfIRBuilder->CreateBlock("unint.gt");
  11994. auto contBlock = mModule->mBfIRBuilder->CreateBlock("unint.cont");
  11995. auto cmp = mModule->mBfIRBuilder->CreateCmpLTE(clearBytes, mModule->GetConstValue(maxStompBytes), true);
  11996. mModule->mBfIRBuilder->CreateCondBr(cmp, contBlock, gtBlock);
  11997. mModule->mBfIRBuilder->AddBlock(gtBlock);
  11998. mModule->mBfIRBuilder->SetInsertPoint(gtBlock);
  11999. mModule->mBfIRBuilder->CreateBr(contBlock);
  12000. mModule->mBfIRBuilder->AddBlock(contBlock);
  12001. mModule->mBfIRBuilder->SetInsertPoint(contBlock);
  12002. auto phi = mModule->mBfIRBuilder->CreatePhi(mModule->mBfIRBuilder->MapType(mModule->GetPrimitiveType(BfTypeCode_IntPtr)), 2);
  12003. mModule->mBfIRBuilder->AddPhiIncoming(phi, clearBytes, insertBlock);
  12004. mModule->mBfIRBuilder->AddPhiIncoming(phi, mModule->GetConstValue(maxStompBytes), gtBlock);
  12005. clearBytes = phi;
  12006. }
  12007. }
  12008. mModule->mBfIRBuilder->PopulateType(resultType);
  12009. if (!resultType->IsValuelessType())
  12010. {
  12011. mModule->mBfIRBuilder->CreateMemSet(mModule->CreateIndexedValue(resultType, addr, clearFromIdx),
  12012. mModule->mBfIRBuilder->CreateConst(BfTypeCode_Int8, isUninit ? 0xCC : 0), clearBytes, resultType->mAlign);
  12013. }
  12014. }
  12015. }
  12016. };
  12017. BfInitContext initContext(mModule, resultType, dimensions, dimLengthVals, arraySize, writeIdx);
  12018. if (resultType->IsVar())
  12019. {
  12020. SetAndRestoreValue<bool> prevIgnoreWrites(mModule->mBfIRBuilder->mIgnoreWrites, true);
  12021. mResult = BfTypedValue(BfTypedValue(mModule->mBfIRBuilder->GetFakeVal(), mModule->GetPrimitiveType(BfTypeCode_Var)));
  12022. initContext.Handle(mResult.mValue, 0, objCreateExpr->mArguments);
  12023. return;
  12024. }
  12025. if (isRawArrayAlloc)
  12026. {
  12027. // 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
  12028. BfType* ptrType = mModule->CreatePointerType(resultType);
  12029. if (isAppendAlloc)
  12030. arrayValue = BfTypedValue(mModule->AppendAllocFromType(resultType, BfIRValue(), 0, arraySize, (int)dimLengthVals.size(), isRawArrayAlloc, false), ptrType);
  12031. else
  12032. {
  12033. arrayValue = BfTypedValue(mModule->AllocFromType(resultType, allocTarget, BfIRValue(), arraySize, (int)dimLengthVals.size(), allocFlags, allocTarget.mAlignOverride), ptrType);
  12034. }
  12035. initContext.Handle(arrayValue.mValue, 0, objCreateExpr->mArguments);
  12036. mResult = arrayValue;
  12037. return;
  12038. }
  12039. if (dimLengthVals.size() > 4)
  12040. {
  12041. dimLengthVals.RemoveRange(4, dimLengthVals.size() - 4);
  12042. mModule->Fail("Too many array dimensions, consider using a jagged array.", objCreateExpr);
  12043. }
  12044. if (isAppendAlloc)
  12045. arrayValue = BfTypedValue(mModule->AppendAllocFromType(resultType, BfIRValue(), 0, arraySize, (int)dimLengthVals.size(), isRawArrayAlloc, zeroMemory), arrayType);
  12046. else
  12047. {
  12048. arrayValue = BfTypedValue(mModule->AllocFromType(resultType, allocTarget, BfIRValue(), arraySize, (int)dimLengthVals.size(), allocFlags, allocTarget.mAlignOverride), arrayType);
  12049. if (isScopeAlloc)
  12050. {
  12051. // See notes below on "general" SkipObjectAccessCheck usage on why we can do this
  12052. mModule->SkipObjectAccessCheck(arrayValue);
  12053. }
  12054. }
  12055. //mModule->InitTypeInst(arrayValue, scopeData);
  12056. BfAstNode* refNode = objCreateExpr->mTypeRef;
  12057. while (true)
  12058. {
  12059. if (auto arrayRef = BfNodeDynCast<BfElementedTypeRef>(refNode))
  12060. {
  12061. refNode = arrayRef->mElementType;
  12062. continue;
  12063. }
  12064. break;
  12065. }
  12066. BfResolvedArgs resolvedArgs;
  12067. auto rawAutoComplete = mModule->mCompiler->GetAutoComplete();
  12068. if (rawAutoComplete != NULL)
  12069. {
  12070. SetAndRestoreValue<bool> prevCapturing(rawAutoComplete->mIsCapturingMethodMatchInfo, false);
  12071. MatchConstructor(refNode, objCreateExpr, arrayValue, arrayType, resolvedArgs, false, false);
  12072. }
  12073. else
  12074. {
  12075. MatchConstructor(refNode, objCreateExpr, arrayValue, arrayType, resolvedArgs, false, false);
  12076. }
  12077. //TODO: Assert 'length' var is at slot 1
  12078. mModule->PopulateType(arrayType->mBaseType, BfPopulateType_DataAndMethods);
  12079. mModule->mBfIRBuilder->PopulateType(arrayType);
  12080. auto arrayBits = mModule->mBfIRBuilder->CreateBitCast(arrayValue.mValue, mModule->mBfIRBuilder->MapTypeInstPtr(arrayType->mBaseType));
  12081. int arrayLengthBitCount = arrayType->GetLengthBitCount();
  12082. if (arrayLengthBitCount == 0)
  12083. {
  12084. mModule->Fail("INTERNAL ERROR: Unable to find array 'length' field", objCreateExpr);
  12085. return;
  12086. }
  12087. mResult = arrayValue;
  12088. auto lengthFieldInstance = mModule->GetFieldByName(arrayType->mBaseType->ToTypeInstance(), "mLength");
  12089. if (lengthFieldInstance == NULL)
  12090. return;
  12091. auto firstElementFieldInstance = mModule->GetFieldByName(arrayType->ToTypeInstance(), "mFirstElement");
  12092. if (firstElementFieldInstance == NULL)
  12093. return;
  12094. auto addr = mModule->mBfIRBuilder->CreateInBoundsGEP(arrayBits, 0, lengthFieldInstance->mDataIdx);
  12095. if (arrayLengthBitCount == 64)
  12096. mModule->mBfIRBuilder->CreateAlignedStore(arraySize, addr, 8);
  12097. else
  12098. {
  12099. auto arraySize32 = mModule->mBfIRBuilder->CreateNumericCast(arraySize, true, BfTypeCode_Int32);
  12100. mModule->mBfIRBuilder->CreateAlignedStore(arraySize32, addr, 4);
  12101. }
  12102. for (int lowerDim = 1; lowerDim < (int)dimLengthVals.size(); lowerDim++)
  12103. {
  12104. auto length1FieldInstance = mModule->GetFieldByName(arrayType->ToTypeInstance(), "mLength1");
  12105. if (length1FieldInstance == NULL)
  12106. return;
  12107. addr = mModule->mBfIRBuilder->CreateInBoundsGEP(arrayValue.mValue, 0, length1FieldInstance->mDataIdx + lowerDim - 1);
  12108. auto lowerDimVal = mModule->mBfIRBuilder->CreateNumericCast(dimLengthVals[lowerDim], true, (arrayLengthBitCount == 64) ? BfTypeCode_Int64 : BfTypeCode_Int32);
  12109. mModule->mBfIRBuilder->CreateStore(lowerDimVal, addr);
  12110. }
  12111. if (resultType->IsValuelessType())
  12112. addr = mModule->mBfIRBuilder->GetFakeVal();
  12113. else
  12114. addr = mModule->mBfIRBuilder->CreateInBoundsGEP(arrayValue.mValue, 0, firstElementFieldInstance->mDataIdx);
  12115. initContext.Handle(addr, 0, objCreateExpr->mArguments);
  12116. return;
  12117. }
  12118. else
  12119. {
  12120. if (resolvedTypeRef->IsVar())
  12121. {
  12122. // Leave as a var
  12123. }
  12124. else if ((!resolvedTypeRef->IsObjectOrInterface()) && (!resolvedTypeRef->IsGenericParam()))
  12125. {
  12126. resultType = mModule->CreatePointerType(resolvedTypeRef);
  12127. }
  12128. }
  12129. if ((isStackAlloc) && (mModule->mCurMethodState == NULL))
  12130. {
  12131. mModule->Fail("Cannot use 'stack' here", allocNode);
  12132. isStackAlloc = false;
  12133. isScopeAlloc = false;
  12134. }
  12135. bool isGenericParam = unresolvedTypeRef->IsGenericParam();
  12136. if (resolvedTypeRef->IsGenericParam())
  12137. {
  12138. auto genericParam = mModule->GetGenericParamInstance((BfGenericParamType*)resolvedTypeRef);
  12139. if (genericParam->mTypeConstraint == NULL)
  12140. {
  12141. if ((genericParam->mGenericParamFlags & BfGenericParamFlag_Var) != 0)
  12142. {
  12143. // Allow it
  12144. }
  12145. else
  12146. {
  12147. if ((genericParam->mGenericParamFlags & BfGenericParamFlag_New) == 0)
  12148. {
  12149. mModule->Fail(StrFormat("Must add 'where %s : new' constraint to generic parameter to instantiate type", genericParam->GetName().c_str()), objCreateExpr->mTypeRef);
  12150. }
  12151. if (objCreateExpr->mArguments.size() != 0)
  12152. {
  12153. mModule->Fail(StrFormat("Only default parameterless constructors can be called on generic argument '%s'", genericParam->GetName().c_str()), objCreateExpr->mTypeRef);
  12154. }
  12155. }
  12156. }
  12157. if (((genericParam->mTypeConstraint != NULL) && (genericParam->mTypeConstraint->IsValueType())) ||
  12158. ((genericParam->mGenericParamFlags & (BfGenericParamFlag_Struct | BfGenericParamFlag_StructPtr)) != 0))
  12159. {
  12160. resultType = mModule->CreatePointerType(resolvedTypeRef);
  12161. }
  12162. else if (((genericParam->mTypeConstraint != NULL) && (!genericParam->mTypeConstraint->IsValueType())) ||
  12163. ((genericParam->mGenericParamFlags & (BfGenericParamFlag_Class)) != 0))
  12164. {
  12165. // Leave as 'T'
  12166. resultType = resolvedTypeRef;
  12167. }
  12168. else
  12169. resultType = mModule->CreateModifiedTypeType(resolvedTypeRef, BfToken_AllocType);
  12170. mResult.mType = resultType;
  12171. if (typeInstance == NULL)
  12172. {
  12173. mResult = mModule->GetDefaultTypedValue(resultType);
  12174. return;
  12175. }
  12176. }
  12177. else if (resolvedTypeRef->IsSizedArray())
  12178. {
  12179. // Handle the case of "int[3]* val = new .(1, 2, 3)"
  12180. if (auto dotTypeRef = BfNodeDynCastExact<BfDotTypeReference>(objCreateExpr->mTypeRef))
  12181. {
  12182. BfIRValue allocValue;
  12183. if (isAppendAlloc)
  12184. allocValue = mModule->AppendAllocFromType(resolvedTypeRef, BfIRValue(), 0, BfIRValue(), 0, false, false);
  12185. else
  12186. allocValue = mModule->AllocFromType(resolvedTypeRef, allocTarget, BfIRValue(), BfIRValue(), 0, BfAllocFlags_None);
  12187. auto result = BfTypedValue(allocValue, resolvedTypeRef, BfTypedValueKind_Addr);
  12188. InitializedSizedArray((BfSizedArrayType*)resolvedTypeRef, objCreateExpr->mOpenToken, objCreateExpr->mArguments, objCreateExpr->mCommas, objCreateExpr->mCloseToken, &result);
  12189. // Turn from an addr of a sized array to pointer of sized array
  12190. mResult = BfTypedValue(mResult.mValue, resultType);
  12191. return;
  12192. }
  12193. }
  12194. SetAndRestoreValue<bool> prevNoBind(mNoBind, mNoBind || isGenericParam);
  12195. if ((typeInstance != NULL) && (typeInstance->mTypeDef->mIsAbstract))
  12196. {
  12197. mModule->Fail("Cannot create an instance of an abstract class", objCreateExpr->mTypeRef);
  12198. return;
  12199. }
  12200. BfFunctionBindResult bindResult;
  12201. bindResult.mSkipThis = true;
  12202. bindResult.mWantsArgs = true;
  12203. SetAndRestoreValue<BfFunctionBindResult*> prevBindResult(mFunctionBindResult, &bindResult);
  12204. BfIRValue appendSizeValue;
  12205. BfTypedValue emtpyThis(mModule->mBfIRBuilder->GetFakeVal(), resolvedTypeRef, resolvedTypeRef->IsStruct());
  12206. BfResolvedArgs argValues;
  12207. if (objCreateExpr != NULL)
  12208. {
  12209. argValues.Init(objCreateExpr->mOpenToken, &objCreateExpr->mArguments, &objCreateExpr->mCommas, objCreateExpr->mCloseToken);
  12210. ResolveArgValues(argValues, BfResolveArgsFlag_DeferParamEval); ////
  12211. }
  12212. if (typeInstance == NULL)
  12213. {
  12214. // No CTOR needed
  12215. if (objCreateExpr->mArguments.size() != 0)
  12216. {
  12217. mModule->Fail(StrFormat("Only default parameterless constructors can be called on primitive type '%s'", mModule->TypeToString(resolvedTypeRef).c_str()), objCreateExpr->mTypeRef);
  12218. }
  12219. }
  12220. else if ((autoComplete != NULL) && (objCreateExpr != NULL) && (objCreateExpr->mOpenToken != NULL))
  12221. {
  12222. auto wasCapturingMethodInfo = autoComplete->mIsCapturingMethodMatchInfo;
  12223. autoComplete->CheckInvocation(objCreateExpr, objCreateExpr->mOpenToken, objCreateExpr->mCloseToken, objCreateExpr->mCommas);
  12224. MatchConstructor(objCreateExpr->mTypeRef, objCreateExpr, emtpyThis, typeInstance, argValues, false, true);
  12225. if ((wasCapturingMethodInfo) && (!autoComplete->mIsCapturingMethodMatchInfo))
  12226. {
  12227. if (autoComplete->mMethodMatchInfo != NULL)
  12228. autoComplete->mIsCapturingMethodMatchInfo = true;
  12229. }
  12230. else
  12231. autoComplete->mIsCapturingMethodMatchInfo = false;
  12232. }
  12233. else if (!resolvedTypeRef->IsFunction())
  12234. {
  12235. auto refNode = allocNode;
  12236. if (objCreateExpr != NULL)
  12237. refNode = objCreateExpr->mTypeRef;
  12238. MatchConstructor(refNode, objCreateExpr, emtpyThis, typeInstance, argValues, false, true);
  12239. }
  12240. if (objCreateExpr != NULL)
  12241. mModule->ValidateAllocation(typeInstance, objCreateExpr->mTypeRef);
  12242. prevBindResult.Restore();
  12243. int allocAlign = resolvedTypeRef->mAlign;
  12244. if (typeInstance != NULL)
  12245. allocAlign = typeInstance->mInstAlign;
  12246. int appendAllocAlign = 0;
  12247. if ((bindResult.mMethodInstance != NULL) && (bindResult.mMethodInstance->mMethodDef->mHasAppend))
  12248. {
  12249. if (!bindResult.mFunc)
  12250. {
  12251. BF_ASSERT((!mModule->HasCompiledOutput()) || (mModule->mBfIRBuilder->mIgnoreWrites));
  12252. appendSizeValue = mModule->GetConstValue(0);
  12253. }
  12254. else
  12255. {
  12256. auto calcAppendMethodModule = mModule->GetMethodInstanceAtIdx(bindResult.mMethodInstance->GetOwner(), bindResult.mMethodInstance->mMethodDef->mIdx + 1, BF_METHODNAME_CALCAPPEND);
  12257. SizedArray<BfIRValue, 2> irArgs;
  12258. if (bindResult.mIRArgs.size() > 1)
  12259. irArgs.Insert(0, &bindResult.mIRArgs[1], bindResult.mIRArgs.size() - 1);
  12260. BfTypedValue appendSizeTypedValue = mModule->TryConstCalcAppend(calcAppendMethodModule.mMethodInstance, irArgs);
  12261. if (!appendSizeTypedValue)
  12262. {
  12263. BF_ASSERT(calcAppendMethodModule.mFunc);
  12264. appendSizeTypedValue = CreateCall(objCreateExpr, calcAppendMethodModule.mMethodInstance, calcAppendMethodModule.mFunc, false, irArgs);
  12265. BF_ASSERT(appendSizeTypedValue.mType == mModule->GetPrimitiveType(BfTypeCode_IntPtr));
  12266. }
  12267. appendSizeValue = appendSizeTypedValue.mValue;
  12268. allocAlign = BF_MAX(allocAlign, calcAppendMethodModule.mMethodInstance->mAppendAllocAlign);
  12269. appendAllocAlign = calcAppendMethodModule.mMethodInstance->mAppendAllocAlign;
  12270. }
  12271. if (appendAllocAlign != 0)
  12272. {
  12273. int endingAlign = typeInstance->GetEndingInstanceAlignment();
  12274. if (endingAlign % appendAllocAlign != 0)
  12275. {
  12276. int extraSize = appendAllocAlign - (endingAlign % appendAllocAlign);
  12277. appendSizeValue = mModule->mBfIRBuilder->CreateAdd(appendSizeValue, mModule->GetConstValue(extraSize));
  12278. }
  12279. }
  12280. }
  12281. // WTF? I'm not even sure this is correct - add more tests
  12282. appendAllocAlign = BF_MAX(appendAllocAlign, allocAlign);
  12283. BfIRValue allocValue;
  12284. if (resolvedTypeRef->IsVar())
  12285. {
  12286. mResult = mModule->GetDefaultTypedValue(resultType);
  12287. return;
  12288. }
  12289. else
  12290. {
  12291. if (isAppendAlloc)
  12292. {
  12293. allocValue = mModule->AppendAllocFromType(resolvedTypeRef, appendSizeValue, appendAllocAlign);
  12294. }
  12295. else
  12296. {
  12297. allocValue = mModule->AllocFromType(resolvedTypeRef, allocTarget, appendSizeValue, BfIRValue(), 0, BfAllocFlags_None, allocAlign);
  12298. }
  12299. if (((mBfEvalExprFlags & BfEvalExprFlags_Comptime) != 0) && (mModule->mCompiler->mCEMachine != NULL))
  12300. {
  12301. mModule->mCompiler->mCEMachine->SetAppendAllocInfo(mModule, allocValue, appendSizeValue);
  12302. }
  12303. mResult = BfTypedValue(allocValue, resultType);
  12304. }
  12305. if (isScopeAlloc)
  12306. {
  12307. // This allows readonly (ie: 'let') local usage to not require an access check. No matter what scope the alloc is tied to, the
  12308. // lifetime of the local variable will be no longer than that of the allocated value
  12309. mModule->SkipObjectAccessCheck(mResult);
  12310. }
  12311. /*if (typeInstance != NULL)
  12312. {
  12313. mModule->InitTypeInst(mResult, scopeData, true);
  12314. }
  12315. if (isStackAlloc)
  12316. {
  12317. mModule->AddStackAlloc(mResult, objCreateExpr, scopeData);
  12318. }*/
  12319. if (mResult)
  12320. {
  12321. if (bindResult.mMethodInstance == NULL)
  12322. {
  12323. // Why did we have this? It was already zeroed right?
  12324. // Zero
  12325. //mModule->mBfIRBuilder->CreateMemSet(mResult.mValue, mModule->GetConstValue8(0), mModule->GetConstValue(resolvedTypeRef->mSize), resolvedTypeRef->mAlign);
  12326. }
  12327. else if (bindResult.mFunc)
  12328. {
  12329. if (typeInstance->IsObject())
  12330. {
  12331. bool wantsCtorClear = true;
  12332. if (mModule->mCompiler->mOptions.mEnableRealtimeLeakCheck)
  12333. {
  12334. // Dbg_ObjectAlloc clears internally so we don't need to call CtorClear for those
  12335. if ((!isStackAlloc) && (!allocTarget.mCustomAllocator) && (allocTarget.mScopedInvocationTarget == NULL))
  12336. wantsCtorClear = false;
  12337. }
  12338. if (wantsCtorClear)
  12339. {
  12340. auto ctorClear = mModule->GetMethodByName(typeInstance, "__BfCtorClear");
  12341. if (!ctorClear)
  12342. {
  12343. mModule->AssertErrorState();
  12344. }
  12345. else if ((mBfEvalExprFlags & BfEvalExprFlags_Comptime) == 0)
  12346. {
  12347. SizedArray<BfIRValue, 1> irArgs;
  12348. irArgs.push_back(mResult.mValue);
  12349. CreateCall(objCreateExpr, ctorClear.mMethodInstance, ctorClear.mFunc, false, irArgs);
  12350. }
  12351. }
  12352. if ((!mModule->mIsComptimeModule) && (isStackAlloc) && (mModule->mCompiler->mOptions.mEnableRealtimeLeakCheck))
  12353. {
  12354. BfMethodInstance* markMethod = mModule->GetRawMethodByName(mModule->mContext->mBfObjectType, "GCMarkMembers");
  12355. BF_ASSERT(markMethod != NULL);
  12356. if (markMethod != NULL)
  12357. {
  12358. auto& vtableEntry = typeInstance->mVirtualMethodTable[markMethod->mVirtualTableIdx];
  12359. if (vtableEntry.mImplementingMethod.mTypeInstance != mModule->mContext->mBfObjectType)
  12360. {
  12361. auto impMethodInstance = (BfMethodInstance*)vtableEntry.mImplementingMethod;
  12362. bool needsCall = false;
  12363. if (impMethodInstance != NULL)
  12364. {
  12365. needsCall = impMethodInstance->mMethodDef->mBody != NULL;
  12366. }
  12367. else
  12368. {
  12369. needsCall = true;
  12370. BF_ASSERT(vtableEntry.mImplementingMethod.mKind == BfMethodRefKind_AmbiguousRef);
  12371. }
  12372. if (needsCall)
  12373. {
  12374. SizedArray<BfIRValue, 1> irArgs;
  12375. irArgs.push_back(mModule->mBfIRBuilder->CreateBitCast(mResult.mValue, mModule->mBfIRBuilder->MapType(mModule->mContext->mBfObjectType)));
  12376. auto gcType = mModule->ResolveTypeDef(mModule->mCompiler->mGCTypeDef);
  12377. BF_ASSERT(gcType != NULL);
  12378. if (gcType != NULL)
  12379. {
  12380. auto addStackObjMethod = mModule->GetMethodByName(gcType->ToTypeInstance(), "AddStackMarkableObject", 1);
  12381. BF_ASSERT(addStackObjMethod);
  12382. if (addStackObjMethod)
  12383. {
  12384. mModule->mBfIRBuilder->CreateCall(addStackObjMethod.mFunc, irArgs);
  12385. }
  12386. auto removeStackObjMethod = mModule->GetMethodByName(gcType->ToTypeInstance(), "RemoveStackMarkableObject", 1);
  12387. BF_ASSERT(removeStackObjMethod);
  12388. if (removeStackObjMethod)
  12389. {
  12390. mModule->AddDeferredCall(removeStackObjMethod, irArgs, allocTarget.mScopeData, allocNode);
  12391. }
  12392. }
  12393. }
  12394. }
  12395. }
  12396. }
  12397. }
  12398. if ((bindResult.mMethodInstance->mMethodDef->mHasAppend) && (mResult.mType->IsObject()))
  12399. {
  12400. BF_ASSERT(bindResult.mIRArgs[0].IsFake());
  12401. auto typeInst = mResult.mType->ToTypeInstance();
  12402. auto intPtrType = mModule->GetPrimitiveType(BfTypeCode_IntPtr);
  12403. auto thisVal = mResult;
  12404. BfIRValue intPtrVal = mModule->CreateAlloca(intPtrType);
  12405. auto intPtrThisVal = mModule->mBfIRBuilder->CreatePtrToInt(thisVal.mValue, (intPtrType->mSize == 4) ? BfTypeCode_Int32 : BfTypeCode_Int64);
  12406. auto curValPtr = mModule->mBfIRBuilder->CreateAdd(intPtrThisVal, mModule->GetConstValue(typeInst->mInstSize, intPtrType));
  12407. mModule->mBfIRBuilder->CreateStore(curValPtr, intPtrVal);
  12408. bindResult.mIRArgs[0] = intPtrVal;
  12409. }
  12410. if (!typeInstance->IsValuelessType())
  12411. bindResult.mIRArgs.Insert(0, mResult.mValue);
  12412. auto result = CreateCall(objCreateExpr, bindResult.mMethodInstance, bindResult.mFunc, false, bindResult.mIRArgs);
  12413. if ((result) && (!result.mType->IsVoid()))
  12414. mResult = result;
  12415. }
  12416. }
  12417. if (((mBfEvalExprFlags & BfEvalExprFlags_Comptime) != 0) && (mModule->mCompiler->mCEMachine != NULL))
  12418. {
  12419. mModule->mCompiler->mCEMachine->ClearAppendAllocInfo();
  12420. }
  12421. }
  12422. void BfExprEvaluator::Visit(BfBoxExpression* boxExpr)
  12423. {
  12424. /*if ((boxExpr->mAllocNode == NULL) || (boxExpr->mExpression == NULL))
  12425. {
  12426. mModule->AssertErrorState();
  12427. return;
  12428. }*/
  12429. BfTokenNode* newToken = NULL;
  12430. BfAllocTarget allocTarget = ResolveAllocTarget(boxExpr->mAllocNode, newToken);
  12431. if ((boxExpr->mAllocNode != NULL) && (boxExpr->mAllocNode->mToken == BfToken_Scope))
  12432. {
  12433. if ((mBfEvalExprFlags & BfEvalExprFlags_FieldInitializer) != 0)
  12434. {
  12435. mModule->Warn(0, "This allocation will only be in scope during the constructor. Consider using a longer-term allocation such as 'new'", boxExpr->mAllocNode);
  12436. }
  12437. }
  12438. if (boxExpr->mExpression == NULL)
  12439. {
  12440. mModule->AssertErrorState();
  12441. return;
  12442. }
  12443. auto exprValue = mModule->CreateValueFromExpression(boxExpr->mExpression);
  12444. if (exprValue)
  12445. {
  12446. bool doFail = false;
  12447. bool doWarn = false;
  12448. if (exprValue.mType->IsGenericParam())
  12449. {
  12450. BF_ASSERT(mModule->mCurMethodInstance->mIsUnspecialized);
  12451. auto genericParamTarget = (BfGenericParamType*)exprValue.mType;
  12452. auto genericParamInstance = mModule->GetGenericParamInstance(genericParamTarget);
  12453. if ((genericParamInstance->mGenericParamFlags & (BfGenericParamFlag_Struct | BfGenericParamFlag_StructPtr | BfGenericParamFlag_Class)) == BfGenericParamFlag_Class)
  12454. doWarn = true;
  12455. if ((genericParamInstance->mTypeConstraint != NULL) && (genericParamInstance->mTypeConstraint->IsObjectOrInterface()))
  12456. doWarn = true;
  12457. }
  12458. else
  12459. {
  12460. doFail = !exprValue.mType->IsValueTypeOrValueTypePtr();
  12461. doWarn = exprValue.mType->IsObjectOrInterface();
  12462. }
  12463. if (doWarn)
  12464. {
  12465. mModule->Warn(0, StrFormat("Boxing is unnecessary since type '%s' is already a reference type.", mModule->TypeToString(exprValue.mType).c_str()), boxExpr->mExpression);
  12466. mResult = exprValue;
  12467. return;
  12468. }
  12469. if (doFail)
  12470. {
  12471. 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);
  12472. return;
  12473. }
  12474. BfType* boxedType = mModule->CreateBoxedType(exprValue.mType);
  12475. if (boxedType == NULL)
  12476. boxedType = mModule->mContext->mBfObjectType;
  12477. mResult = mModule->BoxValue(boxExpr->mExpression, exprValue, boxedType, allocTarget);
  12478. if (!mResult)
  12479. {
  12480. mModule->Fail(StrFormat("Type '%s' is not boxable", mModule->TypeToString(exprValue.mType).c_str()), boxExpr->mExpression);
  12481. return;
  12482. }
  12483. }
  12484. }
  12485. BfAllocTarget BfExprEvaluator::ResolveAllocTarget(BfAstNode* allocNode, BfTokenNode*& newToken, BfCustomAttributes** outCustomAttributes)
  12486. {
  12487. auto autoComplete = GetAutoComplete();
  12488. BfAttributeDirective* attributeDirective = NULL;
  12489. BfAllocTarget allocTarget;
  12490. allocTarget.mRefNode = allocNode;
  12491. newToken = BfNodeDynCast<BfTokenNode>(allocNode);
  12492. if (newToken == NULL)
  12493. {
  12494. if (auto scopeNode = BfNodeDynCast<BfScopeNode>(allocNode))
  12495. {
  12496. newToken = scopeNode->mScopeToken;
  12497. allocTarget.mScopeData = mModule->FindScope(scopeNode->mTargetNode, true);
  12498. if (autoComplete != NULL)
  12499. {
  12500. auto targetIdentifier = BfNodeDynCast<BfIdentifierNode>(scopeNode->mTargetNode);
  12501. if ((scopeNode->mTargetNode == NULL) || (targetIdentifier != NULL))
  12502. autoComplete->CheckLabel(targetIdentifier, scopeNode->mColonToken, allocTarget.mScopeData);
  12503. }
  12504. attributeDirective = scopeNode->mAttributes;
  12505. }
  12506. if (auto newNode = BfNodeDynCast<BfNewNode>(allocNode))
  12507. {
  12508. newToken = newNode->mNewToken;
  12509. if (auto allocExpr = BfNodeDynCast<BfExpression>(newNode->mAllocNode))
  12510. {
  12511. allocTarget.mCustomAllocator = mModule->CreateValueFromExpression(allocExpr);
  12512. allocTarget.mRefNode = allocExpr;
  12513. }
  12514. else if (auto scopedInvocationTarget = BfNodeDynCast<BfScopedInvocationTarget>(newNode->mAllocNode))
  12515. {
  12516. allocTarget.mScopedInvocationTarget = scopedInvocationTarget;
  12517. }
  12518. attributeDirective = newNode->mAttributes;
  12519. }
  12520. }
  12521. else if (newToken->GetToken() == BfToken_Scope)
  12522. {
  12523. if (mModule->mCurMethodState != NULL)
  12524. allocTarget.mScopeData = mModule->mCurMethodState->mCurScope->GetTargetable();
  12525. }
  12526. else if (newToken->GetToken() == BfToken_Stack)
  12527. {
  12528. if (mModule->mCurMethodState != NULL)
  12529. allocTarget.mScopeData = &mModule->mCurMethodState->mHeadScope;
  12530. }
  12531. if (attributeDirective != NULL)
  12532. {
  12533. auto customAttrs = mModule->GetCustomAttributes(attributeDirective, BfAttributeTargets_Alloc, true, &allocTarget.mCaptureInfo);
  12534. if (customAttrs != NULL)
  12535. {
  12536. for (auto& attrib : customAttrs->mAttributes)
  12537. {
  12538. if (attrib.mType->mTypeDef == mModule->mCompiler->mAlignAttributeTypeDef)
  12539. {
  12540. allocTarget.mAlignOverride = 16; // System conservative default
  12541. if (!attrib.mCtorArgs.IsEmpty())
  12542. {
  12543. BfIRConstHolder* constHolder = mModule->mCurTypeInstance->mConstHolder;
  12544. auto constant = constHolder->GetConstant(attrib.mCtorArgs[0]);
  12545. if (constant != NULL)
  12546. {
  12547. int alignOverride = (int)BF_MAX(1, constant->mInt64);
  12548. if ((alignOverride & (alignOverride - 1)) == 0)
  12549. allocTarget.mAlignOverride = alignOverride;
  12550. else
  12551. mModule->Fail("Alignment must be a power of 2", attrib.GetRefNode());
  12552. }
  12553. }
  12554. }
  12555. else if (attrib.mType->mTypeDef == mModule->mCompiler->mFriendAttributeTypeDef)
  12556. allocTarget.mIsFriend = true;
  12557. }
  12558. if (outCustomAttributes != NULL)
  12559. *outCustomAttributes = customAttrs;
  12560. else
  12561. delete customAttrs;
  12562. }
  12563. }
  12564. return allocTarget;
  12565. }
  12566. BfTypedValue BfExprEvaluator::MakeCallableTarget(BfAstNode* targetSrc, BfTypedValue target)
  12567. {
  12568. if ((target.mType->IsRef()) || (target.mType->IsPointer()))
  12569. {
  12570. auto underlying = target.mType->GetUnderlyingType();
  12571. bool underlyingIsStruct = underlying->IsStruct();
  12572. // if (underlying->IsGenericParam())
  12573. // {
  12574. // auto genericParam = mModule->GetGenericParamInstance((BfGenericParamType*)underlying);
  12575. // if (((genericParam->mTypeConstraint != NULL) && (genericParam->mTypeConstraint->IsValueType())) ||
  12576. // ((genericParam->mGenericParamFlags & (BfGenericParamFlag_Struct)) != 0))
  12577. // underlyingIsStruct = true;
  12578. // }
  12579. if (underlyingIsStruct)
  12580. {
  12581. auto pointerType = (BfPointerType*)target.mType;
  12582. target = mModule->LoadValue(target);
  12583. target.mType = pointerType->mElementType;
  12584. target.mKind = BfTypedValueKind_Addr;
  12585. }
  12586. }
  12587. if ((target.mType->IsStruct()) && (!target.IsAddr()))
  12588. {
  12589. if (IsComptimeEntry())
  12590. return target;
  12591. target = mModule->MakeAddressable(target);
  12592. }
  12593. if (target.mType->IsVar())
  12594. {
  12595. target.mType = mModule->mContext->mBfObjectType;
  12596. return target;
  12597. }
  12598. if ((target.mType->IsPointer()) && (target.mType->GetUnderlyingType()->IsObjectOrInterface()))
  12599. {
  12600. mModule->Fail(StrFormat("Methods cannot be called on type '%s' because the type is a pointer to a reference type (ie: a double-reference).",
  12601. mModule->TypeToString(target.mType).c_str()), targetSrc);
  12602. target.mType = mModule->mContext->mBfObjectType;
  12603. return target;
  12604. }
  12605. if (target.mType->IsWrappableType())
  12606. {
  12607. auto primStructType = mModule->GetWrappedStructType(target.mType);
  12608. if (primStructType != NULL)
  12609. {
  12610. mModule->PopulateType(primStructType);
  12611. if (primStructType->IsTypedPrimitive())
  12612. {
  12613. // Type is already the same
  12614. target.mType = primStructType;
  12615. }
  12616. else if (target.IsAddr())
  12617. {
  12618. auto ptrType = mModule->CreatePointerType(primStructType);
  12619. target = BfTypedValue(mModule->mBfIRBuilder->CreateBitCast(target.mValue, mModule->mBfIRBuilder->MapType(ptrType)), primStructType, true);
  12620. }
  12621. else if ((primStructType->IsSplattable()) && (target.IsSplat()) && (!IsComptime()))
  12622. {
  12623. target.mType = primStructType;
  12624. target.mKind = BfTypedValueKind_SplatHead;
  12625. }
  12626. else
  12627. {
  12628. auto allocPtr = mModule->CreateAlloca(primStructType);
  12629. auto srcPtrType = mModule->mBfIRBuilder->CreateBitCast(allocPtr, mModule->mBfIRBuilder->GetPointerTo(mModule->mBfIRBuilder->MapType(target.mType)));
  12630. mModule->mBfIRBuilder->CreateStore(target.mValue, srcPtrType);
  12631. target = BfTypedValue(allocPtr, primStructType, true);
  12632. }
  12633. }
  12634. return target;
  12635. }
  12636. if (target.mType->IsGenericParam())
  12637. {
  12638. target.mType = mModule->mContext->mBfObjectType;
  12639. return target;
  12640. }
  12641. if ((!target.mType->IsTypeInstance()) && (!target.mType->IsConcreteInterfaceType()))
  12642. {
  12643. mModule->Fail(StrFormat("Methods cannot be called on type '%s'", mModule->TypeToString(target.mType).c_str()), targetSrc);
  12644. return BfTypedValue();
  12645. }
  12646. return target;
  12647. }
  12648. int BfExprEvaluator::GetMixinVariable()
  12649. {
  12650. auto curMethodState = mModule->mCurMethodState;
  12651. for (int localIdx = (int)curMethodState->mLocals.size() - 1; localIdx >= 0; localIdx--)
  12652. {
  12653. auto varDecl = curMethodState->mLocals[localIdx];
  12654. if (varDecl->mName == "mixin")
  12655. return localIdx;
  12656. }
  12657. return -1;
  12658. }
  12659. BfModuleMethodInstance BfExprEvaluator::GetSelectedMethod(BfAstNode* targetSrc, BfTypeInstance* curTypeInst, BfMethodDef* methodDef, BfMethodMatcher& methodMatcher, BfType** overrideReturnType)
  12660. {
  12661. bool failed = false;
  12662. BfTypeVector resolvedGenericArguments;
  12663. BfMethodState* rootMethodState = NULL;
  12664. if (mModule->mCurMethodState != NULL)
  12665. rootMethodState = mModule->mCurMethodState->GetRootMethodState();
  12666. int localInferrableGenericArgCount = -1;
  12667. if ((methodMatcher.mBestMethodGenericArguments.size() == 0) && (!methodMatcher.mExplicitMethodGenericArguments.IsEmpty()))
  12668. {
  12669. int uniqueGenericStartIdx = mModule->GetLocalInferrableGenericArgCount(methodDef);
  12670. int64 genericArgCountDiff = (int)methodMatcher.mExplicitMethodGenericArguments.size() + uniqueGenericStartIdx - (int)methodDef->mGenericParams.size();
  12671. BfInvocationExpression* invocationExpr = NULL;
  12672. if (mModule->mParentNodeEntry != NULL)
  12673. {
  12674. invocationExpr = BfNodeDynCast<BfInvocationExpression>(mModule->mParentNodeEntry->mNode);
  12675. }
  12676. if (genericArgCountDiff > 0)
  12677. {
  12678. BfAstNode* errorNode = targetSrc;
  12679. if ((invocationExpr != NULL) && (invocationExpr->mGenericArgs != NULL))
  12680. {
  12681. errorNode = invocationExpr->mGenericArgs->mGenericArgs[(int)methodDef->mGenericParams.size()];
  12682. if (errorNode == NULL)
  12683. invocationExpr->mGenericArgs->mCommas.GetSafe((int)methodDef->mGenericParams.size() - 1, errorNode);
  12684. if (errorNode == NULL)
  12685. errorNode = targetSrc;
  12686. }
  12687. mModule->Fail(StrFormat("Too many generic arguments, expected %d fewer", genericArgCountDiff), errorNode);
  12688. }
  12689. else if (genericArgCountDiff < 0)
  12690. {
  12691. BfAstNode* errorNode = targetSrc;
  12692. if ((invocationExpr != NULL) && (invocationExpr->mGenericArgs != NULL) && (invocationExpr->mGenericArgs->mCloseChevron != NULL))
  12693. errorNode = invocationExpr->mGenericArgs->mCloseChevron;
  12694. mModule->Fail(StrFormat("Too few generic arguments, expected %d more", -genericArgCountDiff), errorNode);
  12695. }
  12696. methodMatcher.mBestMethodGenericArguments.resize(methodDef->mGenericParams.size());
  12697. for (int i = 0; i < std::min(methodDef->mGenericParams.size() - uniqueGenericStartIdx, methodMatcher.mExplicitMethodGenericArguments.size()); i++)
  12698. {
  12699. methodMatcher.mBestMethodGenericArguments[i + uniqueGenericStartIdx] = methodMatcher.mExplicitMethodGenericArguments[i];
  12700. }
  12701. }
  12702. BfMethodInstance* unspecializedMethod = NULL;
  12703. bool hasVarGenerics = false;
  12704. for (int checkGenericIdx = 0; checkGenericIdx < (int)methodMatcher.mBestMethodGenericArguments.size(); checkGenericIdx++)
  12705. {
  12706. BfMethodInstance* outerMethodInstance = NULL;
  12707. auto& genericArg = methodMatcher.mBestMethodGenericArguments[checkGenericIdx];
  12708. if (genericArg == NULL)
  12709. {
  12710. if ((methodDef->mIsLocalMethod) && (checkGenericIdx < mModule->mCurMethodInstance->GetNumGenericArguments()))
  12711. {
  12712. // If the root method is generic and we need that param then use that...
  12713. auto rootMethodInstance = rootMethodState->mMethodInstance;
  12714. if ((rootMethodInstance->mMethodInfoEx != NULL) && (checkGenericIdx < rootMethodInstance->mMethodInfoEx->mMethodGenericArguments.size()))
  12715. {
  12716. genericArg = rootMethodInstance->mMethodInfoEx->mMethodGenericArguments[checkGenericIdx];
  12717. }
  12718. else
  12719. {
  12720. if (localInferrableGenericArgCount == -1)
  12721. localInferrableGenericArgCount = mModule->GetLocalInferrableGenericArgCount(methodDef);
  12722. // Otherwise we can only infer generics at the level that the called method was contained
  12723. if (checkGenericIdx < localInferrableGenericArgCount)
  12724. genericArg = mModule->mCurMethodInstance->mMethodInfoEx->mMethodGenericArguments[checkGenericIdx];
  12725. }
  12726. }
  12727. }
  12728. if (genericArg == NULL)
  12729. {
  12730. if (unspecializedMethod == NULL)
  12731. unspecializedMethod = mModule->GetRawMethodInstance(curTypeInst, methodDef);
  12732. auto genericParam = unspecializedMethod->mMethodInfoEx->mGenericParams[checkGenericIdx];
  12733. if ((genericParam->mTypeConstraint != NULL) && (genericParam->mTypeConstraint->IsDelegate()))
  12734. {
  12735. // The only other option was to bind to a MethodRef
  12736. genericArg = mModule->ResolveGenericType(genericParam->mTypeConstraint, NULL, &methodMatcher.mBestMethodGenericArguments);
  12737. }
  12738. else
  12739. {
  12740. if (((genericParam->mGenericParamFlags & BfGenericParamFlag_Const) != 0) && (genericParam->mTypeConstraint != NULL))
  12741. {
  12742. for (int paramIdx = 0; paramIdx < (int)unspecializedMethod->mDefaultValues.size(); paramIdx++)
  12743. {
  12744. auto defaultVal = unspecializedMethod->mDefaultValues[paramIdx];
  12745. if (!defaultVal)
  12746. continue;
  12747. auto& param = unspecializedMethod->mParams[paramIdx];
  12748. if (param.mResolvedType->IsGenericParam())
  12749. {
  12750. auto genericParamType = (BfGenericParamType*)param.mResolvedType;
  12751. if ((genericParamType->mGenericParamKind == BfGenericParamKind_Method) && (genericParamType->mGenericParamIdx == checkGenericIdx))
  12752. {
  12753. BfTypedValue constExprVal;
  12754. constExprVal.mType = genericParam->mTypeConstraint;
  12755. auto constant = curTypeInst->mConstHolder->GetConstant(defaultVal.mValue);
  12756. constExprVal.mValue = mModule->ConstantToCurrent(constant, curTypeInst->mConstHolder, genericParam->mTypeConstraint);
  12757. genericArg = mModule->CreateConstExprValueType(constExprVal);
  12758. }
  12759. }
  12760. }
  12761. }
  12762. }
  12763. if (genericArg == NULL)
  12764. {
  12765. BfGenericInferContext genericInferContext;
  12766. genericInferContext.mModule = mModule;
  12767. genericInferContext.mCheckMethodGenericArguments = &methodMatcher.mBestMethodGenericArguments;
  12768. genericInferContext.InferGenericArguments(unspecializedMethod);
  12769. }
  12770. if (genericArg == NULL)
  12771. {
  12772. failed = true;
  12773. BfError* error = mModule->Fail(StrFormat("Unable to determine generic argument '%s'", methodDef->mGenericParams[checkGenericIdx]->mName.c_str()).c_str(), targetSrc);
  12774. if ((genericParam->mTypeConstraint != NULL) && (!genericParam->mTypeConstraint->IsUnspecializedType()))
  12775. genericArg = genericParam->mTypeConstraint;
  12776. else
  12777. genericArg = mModule->mContext->mBfObjectType;
  12778. if (error != NULL)
  12779. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("See method declaration"), unspecializedMethod->mMethodDef->GetRefNode());
  12780. }
  12781. }
  12782. if (genericArg->IsVar())
  12783. {
  12784. BF_ASSERT(methodMatcher.mHasVarArguments);
  12785. hasVarGenerics = true;
  12786. }
  12787. if (genericArg->IsIntUnknown())
  12788. genericArg = mModule->FixIntUnknown(genericArg);
  12789. auto resolvedGenericArg = genericArg;
  12790. resolvedGenericArguments.push_back(genericArg);
  12791. }
  12792. BfTypeInstance* foreignType = NULL;
  12793. BfGetMethodInstanceFlags flags = BfGetMethodInstanceFlag_None;
  12794. if ((mModule->mAttributeState != NULL) && (mModule->mAttributeState->mCustomAttributes != NULL) && (mModule->mAttributeState->mCustomAttributes->Contains(mModule->mCompiler->mInlineAttributeTypeDef)))
  12795. {
  12796. flags = (BfGetMethodInstanceFlags)(flags | BfGetMethodInstanceFlag_ForceInline);
  12797. }
  12798. if ((!mModule->mCurTypeInstance->IsInterface()) && (methodDef->mBody != NULL))
  12799. {
  12800. if ((methodMatcher.mBypassVirtual) && (methodMatcher.mBestMethodTypeInstance->IsInterface()))
  12801. {
  12802. // This is an explicit 'base' call to a default interface method. We pull the methodDef into our own concrete type.
  12803. foreignType = curTypeInst;
  12804. curTypeInst = mModule->mCurTypeInstance;
  12805. flags = (BfGetMethodInstanceFlags)(flags | BfGetMethodInstanceFlag_ForeignMethodDef);
  12806. }
  12807. else if ((methodDef->mIsStatic) && (curTypeInst->IsInterface()))
  12808. {
  12809. if (mModule->TypeIsSubTypeOf(mModule->mCurTypeInstance, curTypeInst))
  12810. {
  12811. // This is an explicit call to a default static interface method. We pull the methodDef into our own concrete type.
  12812. foreignType = curTypeInst;
  12813. curTypeInst = mModule->mCurTypeInstance;
  12814. flags = (BfGetMethodInstanceFlags)(flags | BfGetMethodInstanceFlag_ForeignMethodDef);
  12815. }
  12816. }
  12817. }
  12818. if (hasVarGenerics)
  12819. return BfModuleMethodInstance();
  12820. BfModuleMethodInstance moduleMethodInstance;
  12821. if (methodMatcher.mBestMethodInstance)
  12822. {
  12823. moduleMethodInstance = methodMatcher.mBestMethodInstance;
  12824. }
  12825. else
  12826. {
  12827. moduleMethodInstance = mModule->GetMethodInstance(curTypeInst, methodDef, resolvedGenericArguments, flags, foreignType);
  12828. }
  12829. if (mModule->IsSkippingExtraResolveChecks())
  12830. {
  12831. //BF_ASSERT(methodInstance.mFunc == NULL);
  12832. }
  12833. if (moduleMethodInstance.mMethodInstance == NULL)
  12834. return NULL;
  12835. if (methodDef->IsEmptyPartial())
  12836. return moduleMethodInstance;
  12837. if (moduleMethodInstance.mMethodInstance->mMethodInfoEx != NULL)
  12838. {
  12839. for (int checkGenericIdx = 0; checkGenericIdx < (int)moduleMethodInstance.mMethodInstance->mMethodInfoEx->mGenericParams.size(); checkGenericIdx++)
  12840. {
  12841. auto genericParams = moduleMethodInstance.mMethodInstance->mMethodInfoEx->mGenericParams[checkGenericIdx];
  12842. BfTypeVector* checkMethodGenericArgs = NULL;
  12843. BfType* genericArg = NULL;
  12844. if (checkGenericIdx < (int)methodMatcher.mBestMethodGenericArguments.size())
  12845. {
  12846. genericArg = methodMatcher.mBestMethodGenericArguments[checkGenericIdx];
  12847. }
  12848. else
  12849. {
  12850. checkMethodGenericArgs = &methodMatcher.mBestMethodGenericArguments;
  12851. genericArg = genericParams->mExternType;
  12852. auto owner = moduleMethodInstance.mMethodInstance->GetOwner();
  12853. BfTypeVector* typeGenericArguments = NULL;
  12854. if (owner->mGenericTypeInfo != NULL)
  12855. typeGenericArguments = &owner->mGenericTypeInfo->mTypeGenericArguments;
  12856. //genericArg = mModule->ResolveGenericType(genericArg, typeGenericArguments, checkMethodGenericArgs);
  12857. }
  12858. if (genericArg->IsVar())
  12859. continue;
  12860. BfAstNode* paramSrc;
  12861. if (checkGenericIdx >= methodMatcher.mBestMethodGenericArgumentSrcs.size())
  12862. {
  12863. paramSrc = targetSrc;
  12864. }
  12865. else
  12866. paramSrc = methodMatcher.mArguments[methodMatcher.mBestMethodGenericArgumentSrcs[checkGenericIdx]].mExpression;
  12867. // Note: don't pass methodMatcher.mBestMethodGenericArguments into here, this method is already specialized
  12868. BfError* error = NULL;
  12869. if (!mModule->CheckGenericConstraints(BfGenericParamSource(moduleMethodInstance.mMethodInstance), genericArg, paramSrc, genericParams, NULL,
  12870. failed ? NULL : &error))
  12871. {
  12872. if (moduleMethodInstance.mMethodInstance->IsSpecializedGenericMethod())
  12873. {
  12874. // We mark this as failed to make sure we don't try to process a method that doesn't even follow the constraints
  12875. moduleMethodInstance.mMethodInstance->mFailedConstraints = true;
  12876. }
  12877. if (moduleMethodInstance.mMethodInstance->mMethodDef->mMethodDeclaration != NULL)
  12878. {
  12879. if (error != NULL)
  12880. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("See method declaration"), moduleMethodInstance.mMethodInstance->mMethodDef->GetRefNode());
  12881. }
  12882. }
  12883. }
  12884. }
  12885. else
  12886. BF_ASSERT(methodMatcher.mBestMethodGenericArguments.IsEmpty());
  12887. if ((overrideReturnType != NULL) && (moduleMethodInstance.mMethodInstance->mIsUnspecializedVariation) &&
  12888. ((moduleMethodInstance.mMethodInstance->mReturnType->IsUnspecializedTypeVariation()) || (moduleMethodInstance.mMethodInstance->mReturnType->IsVar())))
  12889. {
  12890. if (unspecializedMethod == NULL)
  12891. unspecializedMethod = mModule->GetRawMethodInstance(curTypeInst, methodDef);
  12892. BfTypeVector* typeGenericArgs = NULL;
  12893. auto typeUnspecMethodInstance = unspecializedMethod;
  12894. if (curTypeInst->IsUnspecializedTypeVariation())
  12895. {
  12896. typeUnspecMethodInstance = mModule->GetUnspecializedMethodInstance(typeUnspecMethodInstance, true);
  12897. typeGenericArgs = &curTypeInst->mGenericTypeInfo->mTypeGenericArguments;
  12898. }
  12899. BfType* specializedReturnType = mModule->ResolveGenericType(typeUnspecMethodInstance->mReturnType, typeGenericArgs, &methodMatcher.mBestMethodGenericArguments);
  12900. if (specializedReturnType != NULL)
  12901. *overrideReturnType = specializedReturnType;
  12902. }
  12903. return moduleMethodInstance;
  12904. }
  12905. void BfExprEvaluator::CheckLocalMethods(BfAstNode* targetSrc, BfTypeInstance* typeInstance, const StringImpl& methodName, BfMethodMatcher& methodMatcher, BfMethodType methodType)
  12906. {
  12907. auto _GetNodeId = [&]()
  12908. {
  12909. auto parser = targetSrc->GetSourceData()->ToParserData();
  12910. return ((int64)parser->mDataId << 32) + targetSrc->GetSrcStart();
  12911. };
  12912. BfMethodState* ctxMethodState = NULL;
  12913. BfClosureInstanceInfo* ctxClosureInstanceInfo = NULL;
  12914. if ((mModule->mCurMethodState != NULL) && (mModule->mCurMethodState->mClosureState != NULL))
  12915. {
  12916. ctxClosureInstanceInfo = mModule->mCurMethodState->mClosureState->mClosureInstanceInfo;
  12917. ctxMethodState = mModule->mCurMethodState;
  12918. }
  12919. bool atCtxMethodState = false;
  12920. auto checkMethodState = mModule->mCurMethodState;
  12921. auto rootMethodState = checkMethodState;
  12922. while (checkMethodState != NULL)
  12923. {
  12924. rootMethodState = checkMethodState;
  12925. if (checkMethodState == ctxMethodState)
  12926. atCtxMethodState = true;
  12927. if ((ctxClosureInstanceInfo != NULL) && (!ctxMethodState->mClosureState->mCapturing))
  12928. {
  12929. BfMethodDef* localMethodDef = NULL;
  12930. if (ctxClosureInstanceInfo->mLocalMethodBindings.TryGetValue(_GetNodeId(), &localMethodDef))
  12931. {
  12932. methodMatcher.CheckMethod(mModule->mCurTypeInstance, mModule->mCurTypeInstance, localMethodDef, true);
  12933. BF_ASSERT(methodMatcher.mBestMethodDef != NULL);
  12934. return;
  12935. }
  12936. }
  12937. else
  12938. {
  12939. BfLocalMethod* matchedLocalMethod = NULL;
  12940. BfLocalMethod* localMethod = NULL;
  12941. if (checkMethodState->mLocalMethodMap.TryGetValue(methodName, &localMethod))
  12942. {
  12943. auto typeInst = mModule->mCurTypeInstance;
  12944. if (checkMethodState->mMixinState != NULL)
  12945. typeInst = checkMethodState->mMixinState->mMixinMethodInstance->GetOwner();
  12946. while (localMethod != NULL)
  12947. {
  12948. auto methodDef = mModule->GetLocalMethodDef(localMethod);
  12949. if (methodDef->mMethodType == methodType)
  12950. {
  12951. methodMatcher.CheckMethod(mModule->mCurTypeInstance, typeInst, methodDef, true);
  12952. if (methodMatcher.mBestMethodDef == methodDef)
  12953. matchedLocalMethod = localMethod;
  12954. }
  12955. localMethod = localMethod->mNextWithSameName;
  12956. }
  12957. }
  12958. if (matchedLocalMethod != NULL)
  12959. {
  12960. if ((mModule->mCurMethodState != NULL) && (mModule->mCurMethodState->mClosureState != NULL) && (mModule->mCurMethodState->mClosureState->mCapturing))
  12961. {
  12962. BfModuleMethodInstance moduleMethodInstance = GetSelectedMethod(targetSrc, typeInstance, matchedLocalMethod->mMethodDef, methodMatcher);
  12963. if (moduleMethodInstance)
  12964. {
  12965. auto methodInstance = moduleMethodInstance.mMethodInstance;
  12966. if ((methodInstance->mMethodInfoEx != NULL) && (methodInstance->mMethodInfoEx->mClosureInstanceInfo->mCaptureClosureState != NULL))
  12967. {
  12968. // The called method is calling us from its mLocalMethodRefs set. Stretch our mCaptureStartAccessId back to incorporate its
  12969. // captures as well
  12970. if (methodInstance->mMethodInfoEx->mClosureInstanceInfo->mCaptureClosureState->mCaptureStartAccessId < mModule->mCurMethodState->mClosureState->mCaptureStartAccessId)
  12971. mModule->mCurMethodState->mClosureState->mCaptureStartAccessId = methodInstance->mMethodInfoEx->mClosureInstanceInfo->mCaptureClosureState->mCaptureStartAccessId;
  12972. }
  12973. else
  12974. {
  12975. if (methodInstance->mDisallowCalling) // We need to process the captures from this guy
  12976. {
  12977. if (mModule->mCurMethodState->mClosureState->mLocalMethodRefSet.Add(methodInstance))
  12978. mModule->mCurMethodState->mClosureState->mLocalMethodRefs.Add(methodInstance);
  12979. }
  12980. }
  12981. }
  12982. }
  12983. if (ctxClosureInstanceInfo != NULL)
  12984. {
  12985. BF_ASSERT(mModule->mCurMethodState->mClosureState->mCapturing);
  12986. ctxClosureInstanceInfo->mLocalMethodBindings[_GetNodeId()] = methodMatcher.mBestMethodDef;
  12987. }
  12988. break;
  12989. }
  12990. }
  12991. checkMethodState = checkMethodState->mPrevMethodState;
  12992. }
  12993. }
  12994. void BfExprEvaluator::InjectMixin(BfAstNode* targetSrc, BfTypedValue target, bool allowImplicitThis, const StringImpl& name, const BfSizedArray<BfExpression*>& arguments, BfSizedArray<ASTREF(BfTypeReference*)>* methodGenericArgs)
  12995. {
  12996. if (mModule->mCurMethodState == NULL)
  12997. return;
  12998. if (mDeferCallRef != NULL)
  12999. {
  13000. mModule->Fail("Mixins cannot be directly deferred. Consider wrapping in a block.", targetSrc);
  13001. }
  13002. BfAstNode* origTargetSrc = targetSrc;
  13003. BfScopedInvocationTarget* scopedInvocationTarget = NULL;
  13004. if (mModule->mParentNodeEntry != NULL)
  13005. {
  13006. if (auto invocationExpr = BfNodeDynCast<BfInvocationExpression>(mModule->mParentNodeEntry->mNode))
  13007. {
  13008. scopedInvocationTarget = BfNodeDynCast<BfScopedInvocationTarget>(invocationExpr->mTarget);
  13009. }
  13010. }
  13011. auto targetNameNode = targetSrc;
  13012. if (scopedInvocationTarget != NULL)
  13013. targetNameNode = scopedInvocationTarget->mTarget;
  13014. BfTypeInstance* mixinClass = NULL;
  13015. if (target.mType != NULL)
  13016. mixinClass = target.mType->ToTypeInstance();
  13017. int inLine = mModule->mCurFilePosition.mCurLine;
  13018. SizedArray<BfResolvedArg, 4> args;
  13019. SizedArray<BfExprEvaluator*, 8> argExprEvaluators;
  13020. defer
  13021. (
  13022. {
  13023. for (auto exprEvaluator : argExprEvaluators)
  13024. delete exprEvaluator;
  13025. }
  13026. );
  13027. auto _AddArg = [&](BfExpression* argExpr)
  13028. {
  13029. BfResolvedArg resolvedArg;
  13030. argExprEvaluators.push_back(new BfExprEvaluator(mModule));
  13031. BfExprEvaluator* exprEvaluator = argExprEvaluators.back();
  13032. exprEvaluator->mResolveGenericParam = false;
  13033. exprEvaluator->mBfEvalExprFlags = (BfEvalExprFlags)(exprEvaluator->mBfEvalExprFlags | BfEvalExprFlags_NoCast | BfEvalExprFlags_AllowRefExpr | BfEvalExprFlags_AllowOutExpr);
  13034. bool deferExpr = false;
  13035. if (auto variableDecl = BfNodeDynCast<BfVariableDeclaration>(argExpr))
  13036. {
  13037. deferExpr = true;
  13038. resolvedArg.mArgFlags = (BfArgFlags)(resolvedArg.mArgFlags | BfArgFlag_VariableDeclaration);
  13039. }
  13040. if (deferExpr)
  13041. {
  13042. //
  13043. }
  13044. else if (argExpr != NULL)
  13045. exprEvaluator->Evaluate(argExpr, false, false, true);
  13046. else
  13047. mModule->Fail("Missing argument", targetSrc);
  13048. auto argValue = exprEvaluator->mResult;
  13049. mModule->FixIntUnknown(argValue);
  13050. if (argValue)
  13051. {
  13052. if (argValue.mType->IsRef())
  13053. {
  13054. exprEvaluator->FinishExpressionResult();
  13055. }
  13056. }
  13057. resolvedArg.mTypedValue = argValue;
  13058. resolvedArg.mExpression = argExpr;
  13059. args.push_back(resolvedArg);
  13060. };
  13061. for (BfExpression* argExpr : arguments)
  13062. {
  13063. _AddArg(argExpr);
  13064. }
  13065. auto autoComplete = GetAutoComplete();
  13066. if ((autoComplete != NULL) && (autoComplete->mIsCapturingMethodMatchInfo) && (autoComplete->mMethodMatchInfo->mInstanceList.size() != 0))
  13067. autoComplete->mIsCapturingMethodMatchInfo = false;
  13068. BfMethodMatcher methodMatcher(targetSrc, mModule, name, args, methodGenericArgs);
  13069. methodMatcher.mMethodType = BfMethodType_Mixin;
  13070. methodMatcher.mSkipImplicitParams = true;
  13071. auto curTypeInst = mModule->mCurTypeInstance;
  13072. if (mixinClass != NULL)
  13073. curTypeInst = mixinClass;
  13074. if (target.mType == NULL)
  13075. {
  13076. CheckLocalMethods(targetSrc, curTypeInst, name, methodMatcher, BfMethodType_Mixin);
  13077. }
  13078. if (methodMatcher.mBestMethodDef == NULL)
  13079. methodMatcher.mBestMethodDef = methodMatcher.mBackupMethodDef;
  13080. if (methodMatcher.mBestMethodDef == NULL)
  13081. {
  13082. if (mixinClass != NULL)
  13083. methodMatcher.CheckType(mixinClass, BfTypedValue(), false);
  13084. else
  13085. methodMatcher.CheckType(mModule->mCurTypeInstance, BfTypedValue(), false);
  13086. }
  13087. if ((methodMatcher.mBestMethodDef == NULL) && (target.mType == NULL) && (mModule->mContext->mCurTypeState != NULL))
  13088. {
  13089. BF_ASSERT(mModule->mCurTypeInstance == mModule->mContext->mCurTypeState->mTypeInstance);
  13090. BfGlobalLookup globalLookup;
  13091. globalLookup.mKind = BfGlobalLookup::Kind_Method;
  13092. globalLookup.mName = name;
  13093. mModule->PopulateGlobalContainersList(globalLookup);
  13094. for (auto& globalContainer : mModule->mContext->mCurTypeState->mGlobalContainers)
  13095. {
  13096. if (globalContainer.mTypeInst == NULL)
  13097. continue;
  13098. methodMatcher.CheckType(globalContainer.mTypeInst, BfTypedValue(), false);
  13099. if (methodMatcher.mBestMethodDef != NULL)
  13100. break;
  13101. }
  13102. }
  13103. if (methodMatcher.mBestMethodDef == NULL)
  13104. {
  13105. mModule->Fail("Cannot find mixin", targetSrc);
  13106. return;
  13107. }
  13108. auto resolvePassData = mModule->mCompiler->mResolvePassData;
  13109. if ((autoComplete != NULL) && (autoComplete->IsAutocompleteNode(targetNameNode)) && (autoComplete->mDefType == NULL))
  13110. {
  13111. autoComplete->mInsertStartIdx = targetNameNode->GetSrcStart();
  13112. autoComplete->mInsertEndIdx = targetNameNode->GetSrcEnd();
  13113. autoComplete->mDefType = methodMatcher.mBestMethodTypeInstance->mTypeDef;
  13114. autoComplete->mDefMethod = methodMatcher.mBestMethodDef;
  13115. autoComplete->SetDefinitionLocation(methodMatcher.mBestMethodDef->GetMethodDeclaration()->mNameNode);
  13116. }
  13117. if ((mModule->mCompiler->mResolvePassData != NULL) && (mModule->mCompiler->mResolvePassData->mGetSymbolReferenceKind == BfGetSymbolReferenceKind_Method))
  13118. {
  13119. targetNameNode->SetSrcEnd(targetNameNode->GetSrcEnd() - 1);
  13120. mModule->mCompiler->mResolvePassData->HandleMethodReference(targetNameNode, methodMatcher.mBestMethodTypeInstance->mTypeDef, methodMatcher.mBestMethodDef);
  13121. targetNameNode->SetSrcEnd(targetNameNode->GetSrcEnd() + 1);
  13122. }
  13123. auto curMethodState = mModule->mCurMethodState;
  13124. //
  13125. {
  13126. bool hasCircularRef = false;
  13127. auto checkMethodState = curMethodState;
  13128. while (checkMethodState != NULL)
  13129. {
  13130. auto curMixinState = checkMethodState->mMixinState;
  13131. while (curMixinState != NULL)
  13132. {
  13133. if (curMixinState->mSource == targetSrc)
  13134. hasCircularRef = true;
  13135. curMixinState = curMixinState->mPrevMixinState;
  13136. }
  13137. if ((checkMethodState->mClosureState != NULL) && (checkMethodState->mClosureState->mActiveDeferredLocalMethod != NULL))
  13138. {
  13139. for (auto& mixinRecord : checkMethodState->mClosureState->mActiveDeferredLocalMethod->mMixinStateRecords)
  13140. {
  13141. if (mixinRecord.mSource == targetSrc)
  13142. hasCircularRef = true;
  13143. }
  13144. }
  13145. checkMethodState = checkMethodState->mPrevMethodState;
  13146. }
  13147. if (hasCircularRef)
  13148. {
  13149. mModule->Fail("Circular reference detected between mixins", targetSrc);
  13150. return;
  13151. }
  13152. }
  13153. auto moduleMethodInstance = GetSelectedMethod(targetSrc, methodMatcher.mBestMethodTypeInstance, methodMatcher.mBestMethodDef, methodMatcher);
  13154. if (!moduleMethodInstance)
  13155. {
  13156. if (methodMatcher.mHasVarArguments)
  13157. {
  13158. mResult = mModule->GetDefaultTypedValue(mModule->GetPrimitiveType(BfTypeCode_Var));
  13159. return;
  13160. }
  13161. mModule->Fail("Failed to get selected mixin", targetSrc);
  13162. return;
  13163. }
  13164. if (!mModule->CheckUseMethodInstance(moduleMethodInstance.mMethodInstance, targetSrc))
  13165. return;
  13166. auto methodInstance = moduleMethodInstance.mMethodInstance;
  13167. PerformCallChecks(methodInstance, targetSrc);
  13168. for (int checkGenericIdx = 0; checkGenericIdx < (int)methodMatcher.mBestMethodGenericArguments.size(); checkGenericIdx++)
  13169. {
  13170. auto& genericParams = methodInstance->mMethodInfoEx->mGenericParams;
  13171. auto genericArg = methodMatcher.mBestMethodGenericArguments[checkGenericIdx];
  13172. if (genericArg->IsVar())
  13173. continue;
  13174. BfAstNode* paramSrc;
  13175. if (methodMatcher.mBestMethodGenericArgumentSrcs.size() == 0)
  13176. paramSrc = targetSrc;
  13177. else
  13178. paramSrc = methodMatcher.mArguments[methodMatcher.mBestMethodGenericArgumentSrcs[checkGenericIdx]].mExpression;
  13179. // Note: don't pass methodMatcher.mBestMethodGenericArguments into here, this method is already specialized
  13180. BfError* error = NULL;
  13181. if (!mModule->CheckGenericConstraints(BfGenericParamSource(methodInstance), genericArg, paramSrc, genericParams[checkGenericIdx], NULL, &error))
  13182. {
  13183. if (methodInstance->mMethodDef->mMethodDeclaration != NULL)
  13184. {
  13185. if (error != NULL)
  13186. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("See method declaration"), methodInstance->mMethodDef->GetRefNode());
  13187. }
  13188. }
  13189. }
  13190. // Check circular ref based on methodInstance
  13191. {
  13192. bool hasCircularRef = false;
  13193. auto checkMethodState = curMethodState;
  13194. while (checkMethodState != NULL)
  13195. {
  13196. if (checkMethodState->mMethodInstance == methodInstance)
  13197. hasCircularRef = true;
  13198. auto curMixinState = checkMethodState->mMixinState;
  13199. while (curMixinState != NULL)
  13200. {
  13201. if (curMixinState->mMixinMethodInstance == methodInstance)
  13202. hasCircularRef = true;
  13203. curMixinState = curMixinState->mPrevMixinState;
  13204. }
  13205. checkMethodState = checkMethodState->mPrevMethodState;
  13206. }
  13207. if (hasCircularRef)
  13208. {
  13209. mModule->Fail("Circular reference detected between mixins", targetSrc);
  13210. return;
  13211. }
  13212. }
  13213. AddCallDependencies(methodInstance);
  13214. if (!methodMatcher.mBestMethodDef->mIsStatic)
  13215. {
  13216. if ((!target) && (allowImplicitThis))
  13217. target = mModule->GetThis();
  13218. if (!target)
  13219. {
  13220. BfError* error = mModule->Fail(StrFormat("An instance reference is required to invoke the non-static mixin '%s'",
  13221. mModule->MethodToString(methodInstance).c_str()), targetSrc);
  13222. if ((error != NULL) && (methodInstance->mMethodDef->GetRefNode() != NULL))
  13223. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("See method declaration"), methodInstance->mMethodDef->GetRefNode());
  13224. }
  13225. }
  13226. else
  13227. {
  13228. if (target)
  13229. {
  13230. BfError* error = mModule->Fail(StrFormat("Mixin '%s' cannot be accessed with an instance reference; qualify it with a type name instead",
  13231. mModule->MethodToString(methodInstance).c_str()), targetSrc);
  13232. if ((error != NULL) && (methodInstance->mMethodDef->GetRefNode() != NULL))
  13233. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("See method declaration"), methodInstance->mMethodDef->GetRefNode());
  13234. }
  13235. }
  13236. int methodParamCount = (int)methodInstance->GetParamCount();
  13237. // Implicit params are ignored for calling- they should be resolved at the injection site
  13238. int implicitParamCount = methodInstance->GetImplicitParamCount();
  13239. int explicitParamCount = methodParamCount - implicitParamCount;
  13240. while ((int)args.size() < explicitParamCount)
  13241. {
  13242. int argIdx = (int)args.size();
  13243. BfExpression* expr = methodInstance->GetParamInitializer(argIdx);
  13244. if (expr == NULL)
  13245. break;
  13246. _AddArg(expr);
  13247. }
  13248. if ((int)args.size() < explicitParamCount)
  13249. {
  13250. BfError* error = mModule->Fail(StrFormat("Not enough arguments specified, expected %d more.", explicitParamCount - (int)arguments.size()), targetSrc);
  13251. if ((error != NULL) && (methodInstance->mMethodDef->GetRefNode() != NULL))
  13252. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("See method declaration"), methodInstance->mMethodDef->GetRefNode());
  13253. return;
  13254. }
  13255. else if ((int)args.size() > explicitParamCount)
  13256. {
  13257. BfError* error = mModule->Fail(StrFormat("Too many arguments specified, expected %d fewer.", (int)arguments.size() - explicitParamCount), targetSrc);
  13258. if ((error != NULL) && (methodInstance->mMethodDef->GetRefNode() != NULL))
  13259. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("See method declaration"), methodInstance->mMethodDef->GetRefNode());
  13260. return;
  13261. }
  13262. int paramIdx = implicitParamCount;
  13263. auto argExprEvaluatorItr = argExprEvaluators.begin();
  13264. for (int argIdx = 0; argIdx < (int)args.size(); argIdx++)
  13265. {
  13266. auto exprEvaluator = *argExprEvaluatorItr;
  13267. //auto paramType = methodInstance->GetParamKind(paramIdx);
  13268. BfType* wantType = methodInstance->mParams[paramIdx].mResolvedType;
  13269. auto& arg = args[argIdx];
  13270. if ((arg.mArgFlags & BfArgFlag_VariableDeclaration) != 0)
  13271. {
  13272. arg.mTypedValue = ResolveArgValue(arg, wantType);
  13273. }
  13274. if (wantType->IsGenericParam())
  13275. {
  13276. //
  13277. }
  13278. else if (!wantType->IsVar())
  13279. {
  13280. if (arg.mTypedValue.mType == NULL)
  13281. {
  13282. mModule->AssertErrorState();
  13283. return;
  13284. }
  13285. if (arg.mTypedValue.mType != wantType)
  13286. {
  13287. exprEvaluator->FinishExpressionResult();
  13288. arg.mTypedValue = mModule->LoadValue(arg.mTypedValue);
  13289. arg.mTypedValue = mModule->Cast(arg.mExpression, arg.mTypedValue, wantType);
  13290. /*// Do this to generate default implicit cast error
  13291. mModule->Fail(StrFormat("Mixin argument type '%s' must match parameter type '%s'.",
  13292. mModule->TypeToString(arg.mTypedValue.mType).c_str(),
  13293. mModule->TypeToString(wantType).c_str()), arg.mExpression);
  13294. return;*/
  13295. }
  13296. }
  13297. paramIdx++;
  13298. argExprEvaluatorItr++;
  13299. }
  13300. mModule->AddDependency(methodInstance->GetOwner(), mModule->mCurTypeInstance, BfDependencyMap::DependencyFlag_InlinedCall);
  13301. auto startBlock = mModule->mBfIRBuilder->CreateBlock("mixinStart");
  13302. mModule->mBfIRBuilder->CreateBr(startBlock);
  13303. mModule->mBfIRBuilder->AddBlock(startBlock);
  13304. mModule->mBfIRBuilder->SetInsertPoint(startBlock);
  13305. //auto prevDebugLoc = mModule->mBfIRBuilder->getCurrentDebugLocation();
  13306. // This is so when we debug we can hit a steppoint on the inlined "call line"
  13307. mModule->EmitEnsureInstructionAt();
  13308. auto rootMethodState = mModule->mCurMethodState->GetRootMethodState();
  13309. BfMixinState* mixinState = rootMethodState->mMixinStates.Alloc();
  13310. mixinState->mInjectFilePosition = mModule->mCurFilePosition;
  13311. mixinState->mPrevMixinState = curMethodState->mMixinState;
  13312. mixinState->mLocalsStartIdx = (int)mModule->mCurMethodState->mLocals.size();
  13313. mixinState->mMixinMethodInstance = methodInstance;
  13314. mixinState->mSource = origTargetSrc;
  13315. mixinState->mCallerScope = mModule->mCurMethodState->mCurScope;
  13316. mixinState->mTargetScope = mixinState->mCallerScope;
  13317. mixinState->mResultExpr = NULL;
  13318. mixinState->mHasDeferredUsage = false;
  13319. mixinState->mUsedInvocationScope = false;
  13320. mixinState->mTarget = target;
  13321. auto checkNode = origTargetSrc;
  13322. if (scopedInvocationTarget != NULL)
  13323. {
  13324. auto targetScope = mModule->FindScope(scopedInvocationTarget->mScopeName, curMethodState->mMixinState);
  13325. if (targetScope != NULL)
  13326. {
  13327. mixinState->mTargetScope = targetScope;
  13328. if (autoComplete != NULL)
  13329. {
  13330. if (auto identifer = BfNodeDynCast<BfIdentifierNode>(scopedInvocationTarget->mScopeName))
  13331. autoComplete->CheckLabel(identifer, NULL, targetScope);
  13332. }
  13333. }
  13334. }
  13335. mModule->mBfIRBuilder->SaveDebugLocation();
  13336. SetAndRestoreValue<BfMixinState*> prevMixinState(curMethodState->mMixinState, mixinState);
  13337. BfGetSymbolReferenceKind prevSymbolRefKind = BfGetSymbolReferenceKind_None;
  13338. if (mModule->mCompiler->mResolvePassData != NULL)
  13339. {
  13340. prevSymbolRefKind = mModule->mCompiler->mResolvePassData->mGetSymbolReferenceKind;
  13341. mModule->mCompiler->mResolvePassData->mGetSymbolReferenceKind = BfGetSymbolReferenceKind_None;
  13342. }
  13343. defer
  13344. (
  13345. {
  13346. if (mModule->mCompiler->mResolvePassData != NULL)
  13347. mModule->mCompiler->mResolvePassData->mGetSymbolReferenceKind = prevSymbolRefKind;
  13348. }
  13349. );
  13350. auto methodDef = methodInstance->mMethodDef;
  13351. auto methodDeclaration = methodDef->GetMethodDeclaration();
  13352. BfScopeData scopeData;
  13353. scopeData.mCloseNode = methodDeclaration->mBody;
  13354. if (auto block = BfNodeDynCast<BfBlock>(methodDeclaration->mBody))
  13355. {
  13356. if (block->mCloseBrace != NULL)
  13357. scopeData.mCloseNode = block->mCloseBrace;
  13358. }
  13359. curMethodState->AddScope(&scopeData);
  13360. curMethodState->mCurScope->mMixinDepth++;
  13361. // We can't flush scope state because we extend params in as arbitrary values
  13362. mModule->NewScopeState(true, false);
  13363. bool wantsDIData = (mModule->mBfIRBuilder->DbgHasInfo()) && (mModule->mHasFullDebugInfo);
  13364. DISubprogram* diFunction = NULL;
  13365. int startLocalIdx = (int)mModule->mCurMethodState->mLocals.size();
  13366. int endLocalIdx = startLocalIdx;
  13367. if (wantsDIData)
  13368. {
  13369. BfIRMDNode diFuncType = mModule->mBfIRBuilder->DbgCreateSubroutineType(methodInstance);
  13370. //int defLine = mModule->mCurFilePosition.mCurLine;
  13371. int flags = 0;
  13372. curMethodState->mCurScope->mDIInlinedAt = mModule->mBfIRBuilder->DbgGetCurrentLocation();
  13373. // 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
  13374. // definitions, so we need to be consistent and use the actual line
  13375. mModule->UpdateSrcPos(methodDeclaration->mNameNode, BfSrcPosFlag_NoSetDebugLoc);
  13376. int defLine = mModule->mCurFilePosition.mCurLine;
  13377. auto diParentType = mModule->mBfIRBuilder->DbgGetTypeInst(methodInstance->GetOwner());
  13378. if (!mModule->mBfIRBuilder->mIgnoreWrites)
  13379. {
  13380. String methodName = methodDef->mName;
  13381. methodName += "!";
  13382. BfMangler::Mangle(methodName, mModule->mCompiler->GetMangleKind(), methodInstance);
  13383. curMethodState->mCurScope->mDIScope = mModule->mBfIRBuilder->DbgCreateFunction(diParentType, methodName, "", mModule->mCurFilePosition.mFileInstance->mDIFile,
  13384. defLine + 1, diFuncType, false, true, mModule->mCurFilePosition.mCurLine + 1, flags, false, BfIRValue());
  13385. scopeData.mAltDIFile = mModule->mCurFilePosition.mFileInstance->mDIFile;
  13386. }
  13387. }
  13388. if (methodDef->mBody != NULL)
  13389. mModule->UpdateSrcPos(methodDef->mBody);
  13390. mModule->SetIllegalSrcPos();
  13391. auto _AddLocalVariable = [&](BfLocalVariable* newLocalVar, BfExprEvaluator* exprEvaluator)
  13392. {
  13393. mModule->SetIllegalSrcPos();
  13394. bool hasConstValue = newLocalVar->mConstValue;
  13395. if (hasConstValue)
  13396. {
  13397. auto constant = mModule->mBfIRBuilder->GetConstant(newLocalVar->mConstValue);
  13398. hasConstValue = constant->mConstType < BfConstType_GlobalVar;
  13399. }
  13400. if ((exprEvaluator != NULL) && (exprEvaluator->mResultLocalVar != NULL) && (exprEvaluator->mResultLocalVarField == 0))
  13401. {
  13402. mModule->UpdateSrcPos(methodDeclaration->mNameNode);
  13403. mModule->AddLocalVariableDef(newLocalVar, hasConstValue);
  13404. auto inLocalVar = exprEvaluator->mResultLocalVar;
  13405. newLocalVar->mAssignedKind = inLocalVar->mAssignedKind;
  13406. newLocalVar->mUnassignedFieldFlags = inLocalVar->mUnassignedFieldFlags;
  13407. newLocalVar->mReadFromId = inLocalVar->mReadFromId;
  13408. newLocalVar->mIsReadOnly = inLocalVar->mIsReadOnly;
  13409. if ((newLocalVar->mAssignedKind == BfLocalVarAssignKind_None) && (mModule->mCurMethodState->mDeferredLocalAssignData != NULL))
  13410. {
  13411. for (auto deferredAssign : mModule->mCurMethodState->mDeferredLocalAssignData->mAssignedLocals)
  13412. {
  13413. if (deferredAssign.mLocalVar == inLocalVar)
  13414. newLocalVar->mAssignedKind = BfLocalVarAssignKind_Unconditional;
  13415. }
  13416. }
  13417. }
  13418. else
  13419. {
  13420. mModule->AddLocalVariableDef(newLocalVar, hasConstValue);
  13421. }
  13422. if ((wantsDIData) && (!mModule->mBfIRBuilder->mIgnoreWrites))
  13423. {
  13424. mModule->UpdateSrcPos(methodDeclaration->mNameNode);
  13425. if (hasConstValue)
  13426. {
  13427. // Already handled
  13428. }
  13429. else if (newLocalVar->mIsSplat)
  13430. {
  13431. bool found = false;
  13432. auto checkMethodState = mModule->mCurMethodState;
  13433. while ((checkMethodState != NULL) && (!found))
  13434. {
  13435. for (auto localVar : checkMethodState->mLocals)
  13436. {
  13437. if (localVar == newLocalVar)
  13438. continue;
  13439. if (!localVar->mIsSplat)
  13440. continue;
  13441. if (newLocalVar->mValue != localVar->mAddr)
  13442. continue;
  13443. String name = "$";
  13444. name += newLocalVar->mName;
  13445. name += "$alias$";
  13446. name += localVar->mName;
  13447. // auto fakeValue = mModule->mBfIRBuilder->CreateConst(BfTypeCode_Int32, 0);
  13448. // auto diType = mModule->mBfIRBuilder->DbgGetType(mModule->GetPrimitiveType(BfTypeCode_Int32));
  13449. // auto diVariable = mModule->mBfIRBuilder->DbgCreateAutoVariable(mModule->mCurMethodState->mCurScope->mDIScope,
  13450. // name, mModule->mCurFilePosition.mFileInstance->mDIFile, mModule->mCurFilePosition.mCurLine, diType);
  13451. // mModule->mBfIRBuilder->DbgInsertValueIntrinsic(fakeValue, diVariable);
  13452. auto diType = mModule->mBfIRBuilder->DbgGetType(mModule->GetPrimitiveType(BfTypeCode_NullPtr));
  13453. auto diVariable = mModule->mBfIRBuilder->DbgCreateAutoVariable(mModule->mCurMethodState->mCurScope->mDIScope,
  13454. name, mModule->mCurFilePosition.mFileInstance->mDIFile, mModule->mCurFilePosition.mCurLine, diType);
  13455. mModule->mBfIRBuilder->DbgInsertValueIntrinsic(mModule->mBfIRBuilder->CreateConstNull(), diVariable);
  13456. found = true;
  13457. break;
  13458. }
  13459. checkMethodState = checkMethodState->mPrevMethodState;
  13460. }
  13461. }
  13462. else if (mModule->IsTargetingBeefBackend())
  13463. {
  13464. mModule->UpdateSrcPos(methodDeclaration->mNameNode);
  13465. mModule->SetIllegalSrcPos();
  13466. // With the Beef backend we can assign two variables to the same value, but LLVM does not allow this
  13467. // so we have to create a ref to that variable
  13468. auto diType = mModule->mBfIRBuilder->DbgGetType(newLocalVar->mResolvedType);
  13469. auto diVariable = mModule->mBfIRBuilder->DbgCreateAutoVariable(mModule->mCurMethodState->mCurScope->mDIScope,
  13470. newLocalVar->mName, mModule->mCurFilePosition.mFileInstance->mDIFile, mModule->mCurFilePosition.mCurLine, diType);
  13471. if (newLocalVar->mIsSplat)
  13472. {
  13473. //TODO: Implement
  13474. }
  13475. else if (newLocalVar->mResolvedType->IsValuelessType())
  13476. {
  13477. // Do nothing
  13478. }
  13479. else
  13480. {
  13481. BfIRValue value = newLocalVar->mValue;
  13482. if (newLocalVar->mAddr)
  13483. value = newLocalVar->mAddr;
  13484. else if (newLocalVar->mConstValue)
  13485. value = newLocalVar->mConstValue;
  13486. auto aliasValue = mModule->mBfIRBuilder->CreateAliasValue(value);
  13487. if (mModule->WantsLifetimes())
  13488. scopeData.mDeferredLifetimeEnds.Add(aliasValue);
  13489. if (newLocalVar->mAddr)
  13490. mModule->mBfIRBuilder->DbgInsertDeclare(aliasValue, diVariable);
  13491. else
  13492. {
  13493. mModule->mBfIRBuilder->DbgInsertValueIntrinsic(aliasValue, diVariable);
  13494. //mModule->mBfIRBuilder->DbgInsertValueIntrinsic(newLocalVar->mValue, diVariable);
  13495. }
  13496. }
  13497. }
  13498. else if (newLocalVar->mAddr)
  13499. {
  13500. mModule->UpdateSrcPos(methodDeclaration->mNameNode);
  13501. mModule->SetIllegalSrcPos();
  13502. auto refType = mModule->CreateRefType(newLocalVar->mResolvedType);
  13503. auto allocaVal = mModule->CreateAlloca(refType);
  13504. mModule->mBfIRBuilder->CreateStore(newLocalVar->mAddr, allocaVal);
  13505. if (!mModule->mBfIRBuilder->mIgnoreWrites)
  13506. {
  13507. auto diType = mModule->mBfIRBuilder->DbgGetType(refType);
  13508. auto diVariable = mModule->mBfIRBuilder->DbgCreateAutoVariable(mModule->mCurMethodState->mCurScope->mDIScope,
  13509. newLocalVar->mName, mModule->mCurFilePosition.mFileInstance->mDIFile, mModule->mCurFilePosition.mCurLine, diType);
  13510. mModule->mBfIRBuilder->DbgInsertDeclare(allocaVal, diVariable);
  13511. }
  13512. }
  13513. else if (newLocalVar->mValue)
  13514. {
  13515. mModule->UpdateSrcPos(methodDeclaration->mNameNode);
  13516. mModule->SetIllegalSrcPos();
  13517. auto localVal = LoadLocal(newLocalVar);
  13518. localVal = mModule->LoadValue(localVal);
  13519. localVal = mModule->AggregateSplat(localVal);
  13520. BfType* allocType = localVal.mType;
  13521. auto allocaVal = mModule->CreateAlloca(allocType);
  13522. mModule->mBfIRBuilder->CreateStore(localVal.mValue, allocaVal);
  13523. if (!mModule->mBfIRBuilder->mIgnoreWrites)
  13524. {
  13525. if (newLocalVar->mIsSplat)
  13526. {
  13527. //TODO: Implement
  13528. }
  13529. else
  13530. {
  13531. auto diType = mModule->mBfIRBuilder->DbgGetType(allocType);
  13532. auto diVariable = mModule->mBfIRBuilder->DbgCreateAutoVariable(mModule->mCurMethodState->mCurScope->mDIScope,
  13533. newLocalVar->mName, mModule->mCurFilePosition.mFileInstance->mDIFile, mModule->mCurFilePosition.mCurLine, diType);
  13534. mModule->mBfIRBuilder->DbgInsertDeclare(allocaVal, diVariable);
  13535. }
  13536. }
  13537. }
  13538. }
  13539. newLocalVar->mParamIdx = -3;
  13540. };
  13541. argExprEvaluatorItr = argExprEvaluators.begin();
  13542. for (int argIdx = methodDef->mIsStatic ? 0 : -1; argIdx < (int)explicitParamCount; argIdx++)
  13543. {
  13544. int paramIdx = argIdx;
  13545. auto exprEvaluator = *argExprEvaluatorItr;
  13546. BfTypedValue argValue;
  13547. BfLocalVariable* localVar = new BfLocalVariable();
  13548. if (argIdx == -1)
  13549. {
  13550. argValue = target;
  13551. localVar->mName = "this";
  13552. localVar->mIsThis = true;
  13553. localVar->mAssignedKind = BfLocalVarAssignKind_Unconditional;
  13554. }
  13555. else
  13556. {
  13557. auto arg = &args[argIdx];
  13558. auto paramDef = methodDef->mParams[paramIdx];
  13559. localVar->mName = paramDef->mName;
  13560. if (!arg->mTypedValue)
  13561. {
  13562. auto wantType = methodInstance->GetParamType(paramIdx);
  13563. if (wantType->IsVar())
  13564. wantType = mModule->mContext->mBfObjectType;
  13565. arg->mTypedValue = mModule->GetDefaultTypedValue(wantType);
  13566. }
  13567. argValue = arg->mTypedValue;
  13568. }
  13569. if (!argValue)
  13570. continue;
  13571. localVar->mResolvedType = argValue.mType;
  13572. if (argValue.mType->IsRef())
  13573. {
  13574. auto refType = (BfRefType*)localVar->mResolvedType;
  13575. localVar->mAddr = mModule->LoadValue(argValue).mValue;
  13576. localVar->mResolvedType = argValue.mType->GetUnderlyingType();
  13577. localVar->mAssignedKind = (refType->mRefKind != BfRefType::RefKind_Out) ? BfLocalVarAssignKind_Unconditional : BfLocalVarAssignKind_None;
  13578. }
  13579. else if (argValue.IsAddr())
  13580. localVar->mAddr = argValue.mValue;
  13581. else
  13582. {
  13583. if (!argValue.mValue)
  13584. {
  13585. // Untyped value
  13586. }
  13587. else if (argValue.mValue.IsConst())
  13588. {
  13589. localVar->mConstValue = argValue.mValue;
  13590. }
  13591. else if (argValue.IsSplat())
  13592. {
  13593. localVar->mValue = argValue.mValue;
  13594. localVar->mIsSplat = true;
  13595. }
  13596. else
  13597. {
  13598. if (argValue.IsAddr())
  13599. localVar->mAddr = argValue.mValue;
  13600. else
  13601. localVar->mValue = argValue.mValue;
  13602. }
  13603. localVar->mIsReadOnly = argValue.IsReadOnly();
  13604. }
  13605. if (argValue.IsReadOnly())
  13606. localVar->mIsReadOnly = true;
  13607. if (argIdx == -1)
  13608. {
  13609. _AddLocalVariable(localVar, NULL);
  13610. }
  13611. else
  13612. {
  13613. _AddLocalVariable(localVar, exprEvaluator);
  13614. endLocalIdx++;
  13615. ++argExprEvaluatorItr;
  13616. }
  13617. }
  13618. if (auto blockBody = BfNodeDynCast<BfBlock>(methodDef->mBody))
  13619. mModule->VisitCodeBlock(blockBody);
  13620. if (mixinState->mResultExpr != NULL)
  13621. {
  13622. if (auto exprNode = BfNodeDynCast<BfExpression>(mixinState->mResultExpr))
  13623. {
  13624. if (!exprNode->IsA<BfBlock>())
  13625. {
  13626. // Mixin expression result
  13627. mModule->UpdateSrcPos(exprNode);
  13628. VisitChild(exprNode);
  13629. FinishExpressionResult();
  13630. ResolveGenericType();
  13631. //mResult = mModule->LoadValue(mResult);
  13632. }
  13633. }
  13634. }
  13635. GetResult();
  13636. if (!mResult)
  13637. {
  13638. // If we didn't have an expression body then just make the result "void"
  13639. mResult = BfTypedValue(BfIRValue(), mModule->GetPrimitiveType(BfTypeCode_None));
  13640. }
  13641. int localIdx = startLocalIdx;
  13642. argExprEvaluatorItr = argExprEvaluators.begin();
  13643. for (; localIdx < endLocalIdx; localIdx++)
  13644. {
  13645. auto exprEvaluator = *argExprEvaluatorItr;
  13646. BfLocalVariable* localVar = curMethodState->mLocals[localIdx];
  13647. //TODO: Merge unassigned flags together
  13648. if ((exprEvaluator != NULL) && (exprEvaluator->mResultLocalVar != NULL))
  13649. {
  13650. auto inLocalVar = exprEvaluator->mResultLocalVar;
  13651. if (localVar->mAssignedKind != BfLocalVarAssignKind_None)
  13652. inLocalVar->mAssignedKind = BfLocalVarAssignKind_Unconditional;
  13653. if (localVar->mReadFromId != -1)
  13654. inLocalVar->mReadFromId = mModule->mCurMethodState->GetRootMethodState()->mCurAccessId++;
  13655. }
  13656. ++argExprEvaluatorItr;
  13657. }
  13658. if (auto blockBody = BfNodeDynCast<BfBlock>(methodDef->mBody))
  13659. if (blockBody->mCloseBrace != NULL)
  13660. mModule->UpdateSrcPos(blockBody->mCloseBrace);
  13661. mModule->RestoreScopeState();
  13662. prevMixinState.Restore();
  13663. if ((scopedInvocationTarget != NULL) && (scopedInvocationTarget->mScopeName != NULL) && (!mixinState->mUsedInvocationScope))
  13664. {
  13665. mModule->Warn(0, "Scope specifier was not referenced in mixin", scopedInvocationTarget->mScopeName);
  13666. }
  13667. if (mixinState->mHasDeferredUsage)
  13668. {
  13669. // if (target)
  13670. // {
  13671. // if (target.mType->IsValuelessType())
  13672. // mixinState->mTarget = target;
  13673. // else
  13674. // {
  13675. // target = mModule->LoadValue(target);
  13676. // auto savedTarget = BfTypedValue(mModule->CreateAlloca(target.mType, false), target.mType, true);
  13677. // mModule->mBfIRBuilder->CreateStore(target.mValue, savedTarget.mValue);
  13678. // mixinState->mTarget = savedTarget;
  13679. // }
  13680. // }
  13681. mixinState->mTarget = BfTypedValue();
  13682. }
  13683. else
  13684. {
  13685. BF_ASSERT(rootMethodState->mMixinStates.back() == mixinState);
  13686. rootMethodState->mMixinStates.pop_back();
  13687. delete mixinState;
  13688. }
  13689. mModule->mBfIRBuilder->RestoreDebugLocation();
  13690. mModule->mBfIRBuilder->DupDebugLocation();
  13691. }
  13692. void BfExprEvaluator::SetMethodElementType(BfAstNode* target)
  13693. {
  13694. if (auto delegateBindExpr = BfNodeDynCast<BfDelegateBindExpression>(target))
  13695. {
  13696. SetMethodElementType(delegateBindExpr->mTarget);
  13697. return;
  13698. }
  13699. if (auto lambdaBindExpr = BfNodeDynCast<BfLambdaBindExpression>(target))
  13700. {
  13701. return;
  13702. }
  13703. if (auto attributedIdentifierNode = BfNodeDynCast<BfAttributedIdentifierNode>(target))
  13704. {
  13705. if (attributedIdentifierNode->mIdentifier != NULL)
  13706. mModule->SetElementType(attributedIdentifierNode->mIdentifier, BfSourceElementType_Method);
  13707. }
  13708. else if (auto memberReferenceExpr = BfNodeDynCast<BfMemberReferenceExpression>(target))
  13709. {
  13710. if (memberReferenceExpr->mMemberName != NULL)
  13711. SetMethodElementType(memberReferenceExpr->mMemberName);
  13712. }
  13713. else if (auto qualifiedNameNode = BfNodeDynCast<BfQualifiedNameNode>(target))
  13714. SetMethodElementType(qualifiedNameNode->mRight);
  13715. else
  13716. mModule->SetElementType(target, BfSourceElementType_Method);
  13717. }
  13718. void BfExprEvaluator::DoInvocation(BfAstNode* target, BfMethodBoundExpression* methodBoundExpr, const BfSizedArray<BfExpression*>& args, BfSizedArray<ASTREF(BfTypeReference*)>* methodGenericArguments, BfTypedValue* outCascadeValue)
  13719. {
  13720. // Just a check
  13721. mModule->mBfIRBuilder->GetInsertBlock();
  13722. bool wasCapturingMethodInfo = false;
  13723. auto autoComplete = GetAutoComplete();
  13724. if ((autoComplete != NULL) && (methodGenericArguments != NULL))
  13725. {
  13726. for (BfTypeReference* methodGenericArg : *methodGenericArguments)
  13727. autoComplete->CheckTypeRef(methodGenericArg, false, true);
  13728. }
  13729. if ((autoComplete != NULL) && (autoComplete->mIsCapturingMethodMatchInfo))
  13730. {
  13731. // We don't want to capture a call within the target node
  13732. wasCapturingMethodInfo = true;
  13733. autoComplete->mIsCapturingMethodMatchInfo = false;
  13734. }
  13735. bool allowImplicitThis = false;
  13736. BfAstNode* methodNodeSrc = target;
  13737. BfAttributeState attributeState;
  13738. attributeState.mTarget = (BfAttributeTargets)(BfAttributeTargets_Invocation | BfAttributeTargets_MemberAccess);
  13739. if (auto scopedTarget = BfNodeDynCast<BfScopedInvocationTarget>(target))
  13740. {
  13741. target = scopedTarget->mTarget;
  13742. if (autoComplete != NULL)
  13743. {
  13744. if (auto identifier = BfNodeDynCast<BfIdentifierNode>(scopedTarget->mScopeName))
  13745. autoComplete->CheckLabel(identifier, scopedTarget->mColonToken, NULL);
  13746. }
  13747. //mModule->FindScope(scopedTarget->mScopeName);
  13748. }
  13749. bool isCascade = false;
  13750. BfAstNode* cascadeOperatorToken = NULL;
  13751. bool bypassVirtual = false;
  13752. bool gaveUnqualifiedDotError = false;
  13753. String targetFunctionName;
  13754. BfTypedValue thisValue;
  13755. //TODO: This may just be a fully qualified static method name, so let's check that also
  13756. if (auto memberRefExpression = BfNodeDynCast<BfMemberReferenceExpression>(target))
  13757. {
  13758. if (autoComplete != NULL)
  13759. {
  13760. if (memberRefExpression->mTarget != NULL)
  13761. autoComplete->CheckMemberReference(memberRefExpression->mTarget, memberRefExpression->mDotToken, memberRefExpression->mMemberName, false, mExpectingType);
  13762. else if (mExpectingType != NULL)
  13763. {
  13764. String filter;
  13765. if ((autoComplete != NULL) && (autoComplete->InitAutocomplete(memberRefExpression->mDotToken, memberRefExpression->mMemberName, filter)))
  13766. {
  13767. auto typeInst = mExpectingType->ToTypeInstance();
  13768. if (typeInst != NULL)
  13769. {
  13770. String filter;
  13771. if ((memberRefExpression->mMemberName != NULL) && (autoComplete->IsAutocompleteNode(memberRefExpression->mMemberName)))
  13772. filter = autoComplete->GetFilter(memberRefExpression->mMemberName);
  13773. bool allowPrivate = typeInst == mModule->mCurTypeInstance;
  13774. autoComplete->AddEnumTypeMembers(typeInst, filter, false, allowPrivate);
  13775. autoComplete->AddSelfResultTypeMembers(typeInst, typeInst, filter, allowPrivate);
  13776. }
  13777. }
  13778. }
  13779. }
  13780. if ((memberRefExpression->mTarget == NULL) && (memberRefExpression->mMemberName == NULL))
  13781. {
  13782. auto expectingType = mExpectingType;
  13783. if ((expectingType != NULL) && (expectingType->IsNullable()))
  13784. {
  13785. auto underlyingType = expectingType->GetUnderlyingType();
  13786. expectingType = underlyingType;
  13787. }
  13788. if (expectingType != NULL)
  13789. {
  13790. if (expectingType->IsSizedArray())
  13791. {
  13792. if (mModule->mParentNodeEntry != NULL)
  13793. {
  13794. if (auto invocationExpr = BfNodeDynCast<BfInvocationExpression>(mModule->mParentNodeEntry->mNode))
  13795. {
  13796. InitializedSizedArray((BfSizedArrayType*)expectingType, invocationExpr->mOpenParen, invocationExpr->mArguments, invocationExpr->mCommas, invocationExpr->mCloseParen);
  13797. return;
  13798. }
  13799. }
  13800. }
  13801. else if (expectingType->IsStruct())
  13802. {
  13803. if ((wasCapturingMethodInfo) && (autoComplete->mMethodMatchInfo != NULL))
  13804. {
  13805. autoComplete->mIsCapturingMethodMatchInfo = true;
  13806. BF_ASSERT(autoComplete->mMethodMatchInfo != NULL);
  13807. }
  13808. if (mModule->mParentNodeEntry != NULL)
  13809. {
  13810. if (auto invocationExpr = BfNodeDynCast<BfInvocationExpression>(mModule->mParentNodeEntry->mNode))
  13811. {
  13812. BfResolvedArgs argValues(invocationExpr->mOpenParen, &invocationExpr->mArguments, &invocationExpr->mCommas, invocationExpr->mCloseParen);
  13813. BfResolveArgsFlags resolveArgsFlags = BfResolveArgsFlag_DeferParamEval;
  13814. ResolveArgValues(argValues, resolveArgsFlags);
  13815. if ((mReceivingValue != NULL) && (mReceivingValue->mType == expectingType) && (mReceivingValue->IsAddr()))
  13816. {
  13817. mResult = *mReceivingValue;
  13818. mReceivingValue = NULL;
  13819. }
  13820. else
  13821. mResult = BfTypedValue(mModule->CreateAlloca(expectingType), expectingType, BfTypedValueKind_TempAddr);
  13822. auto ctorResult = MatchConstructor(target, methodBoundExpr, mResult, expectingType->ToTypeInstance(), argValues, false, false);
  13823. if ((ctorResult) && (!ctorResult.mType->IsVoid()))
  13824. mResult = ctorResult;
  13825. mModule->ValidateAllocation(expectingType, invocationExpr->mTarget);
  13826. return;
  13827. }
  13828. }
  13829. }
  13830. else if (expectingType->IsGenericParam())
  13831. {
  13832. if (mModule->mParentNodeEntry != NULL)
  13833. {
  13834. if (auto invocationExpr = BfNodeDynCast<BfInvocationExpression>(mModule->mParentNodeEntry->mNode))
  13835. {
  13836. BfResolvedArgs argValues(invocationExpr->mOpenParen, &invocationExpr->mArguments, &invocationExpr->mCommas, invocationExpr->mCloseParen);
  13837. BfResolveArgsFlags resolveArgsFlags = BfResolveArgsFlag_None;
  13838. ResolveArgValues(argValues, resolveArgsFlags);
  13839. CheckGenericCtor((BfGenericParamType*)expectingType, argValues, invocationExpr->mTarget);
  13840. mResult = mModule->GetDefaultTypedValue(expectingType);
  13841. return;
  13842. }
  13843. }
  13844. }
  13845. else if (expectingType->IsVar())
  13846. {
  13847. // Silently allow
  13848. gaveUnqualifiedDotError = true;
  13849. }
  13850. else
  13851. {
  13852. gaveUnqualifiedDotError = true;
  13853. mModule->Fail(StrFormat("Cannot use inferred constructor on type '%s'", mModule->TypeToString(expectingType).c_str()), memberRefExpression->mDotToken);
  13854. }
  13855. }
  13856. }
  13857. if (memberRefExpression->IsA<BfBaseExpression>())
  13858. bypassVirtual = true;
  13859. if (memberRefExpression->mMemberName != NULL)
  13860. methodNodeSrc = memberRefExpression->mMemberName;
  13861. if (auto attrIdentifier = BfNodeDynCast<BfAttributedIdentifierNode>(memberRefExpression->mMemberName))
  13862. {
  13863. if (attrIdentifier->mIdentifier != NULL)
  13864. methodNodeSrc = attrIdentifier->mIdentifier;
  13865. attributeState.mSrc = attrIdentifier->mAttributes;
  13866. attributeState.mCustomAttributes = mModule->GetCustomAttributes(attrIdentifier->mAttributes, attributeState.mTarget);
  13867. if (attrIdentifier->mIdentifier != NULL)
  13868. targetFunctionName = attrIdentifier->mIdentifier->ToString();
  13869. }
  13870. else if (memberRefExpression->mMemberName != NULL)
  13871. targetFunctionName = memberRefExpression->mMemberName->ToString();
  13872. if (memberRefExpression->mTarget == NULL)
  13873. {
  13874. if (mExpectingType)
  13875. {
  13876. if (mExpectingType->IsVar())
  13877. {
  13878. }
  13879. mResult = BfTypedValue(mExpectingType);
  13880. }
  13881. else if (!gaveUnqualifiedDotError)
  13882. mModule->Fail("Unqualified dot syntax can only be used when the result type can be inferred", memberRefExpression->mDotToken);
  13883. }
  13884. else if (auto typeRef = BfNodeDynCast<BfTypeReference>(memberRefExpression->mTarget))
  13885. {
  13886. // Static method
  13887. mResult = BfTypedValue(ResolveTypeRef(typeRef));
  13888. }
  13889. if (auto leftIdentifier = BfNodeDynCast<BfIdentifierNode>(memberRefExpression->mTarget))
  13890. {
  13891. bool hadError = false;
  13892. thisValue = LookupIdentifier(leftIdentifier, true, &hadError);
  13893. CheckResultForReading(thisValue);
  13894. if (mPropDef != NULL)
  13895. thisValue = GetResult(true);
  13896. if (hadError)
  13897. {
  13898. mModule->AssertErrorState();
  13899. thisValue = mModule->GetDefaultTypedValue(mModule->mContext->mBfObjectType);
  13900. }
  13901. if ((!thisValue) && (mPropDef == NULL))
  13902. {
  13903. // Identifier not found. Static method? Just check speculatively don't throw error
  13904. BfType* type;
  13905. {
  13906. SetAndRestoreValue<bool> prevIgnoreErrors(mModule->mIgnoreErrors, true);
  13907. type = mModule->ResolveTypeRef(leftIdentifier, NULL, BfPopulateType_DataAndMethods, BfResolveTypeRefFlag_NoResolveGenericParam);
  13908. }
  13909. if (type != NULL)
  13910. thisValue = BfTypedValue(type);
  13911. else if (auto qualifiedLeft = BfNodeDynCast<BfQualifiedNameNode>(leftIdentifier))
  13912. {
  13913. LookupQualifiedStaticField(qualifiedLeft, true);
  13914. thisValue = mResult;
  13915. mResult = BfTypedValue();
  13916. }
  13917. }
  13918. if (mPropDef != NULL)
  13919. thisValue = GetResult(true);
  13920. if (!thisValue.mType)
  13921. {
  13922. mModule->Fail("Identifier not found", leftIdentifier);
  13923. mModule->CheckTypeRefFixit(leftIdentifier);
  13924. thisValue = mModule->GetDefaultTypedValue(mModule->mContext->mBfObjectType);
  13925. }
  13926. if (mResult)
  13927. CheckResultForReading(mResult);
  13928. mResult = thisValue;
  13929. }
  13930. else if (auto expr = BfNodeDynCast<BfExpression>(memberRefExpression->mTarget))
  13931. {
  13932. BfType* expectingTargetType = NULL;
  13933. if (memberRefExpression->mDotToken->mToken == BfToken_DotDot)
  13934. expectingTargetType = mExpectingType;
  13935. bool handled = false;
  13936. if (auto subMemberRefExpr = BfNodeDynCast<BfMemberReferenceExpression>(expr))
  13937. {
  13938. String findName;
  13939. if (subMemberRefExpr->mMemberName != NULL)
  13940. findName = subMemberRefExpr->mMemberName->ToString();
  13941. if (findName == "base") // Generic IFace<T>.base
  13942. {
  13943. thisValue = mModule->GetThis();
  13944. if (thisValue)
  13945. {
  13946. VisitChild(subMemberRefExpr->mTarget);
  13947. if (mResult.HasType())
  13948. {
  13949. if (mResult.mValue)
  13950. {
  13951. mModule->Fail("Type name expected", subMemberRefExpr->mTarget);
  13952. }
  13953. else
  13954. {
  13955. auto type = mResult.mType;
  13956. if (type != NULL)
  13957. {
  13958. if ((thisValue.mType == type) || (!mModule->TypeIsSubTypeOf(thisValue.mType->ToTypeInstance(), type->ToTypeInstance())))
  13959. {
  13960. mModule->Fail(StrFormat("Type '%s' is not a base type of '%s'",
  13961. mModule->TypeToString(type).c_str(),
  13962. mModule->TypeToString(thisValue.mType).c_str()), subMemberRefExpr->mTarget);
  13963. }
  13964. else
  13965. {
  13966. if (type->IsInterface())
  13967. {
  13968. thisValue.mType = type;
  13969. }
  13970. else
  13971. {
  13972. auto castedThis = mModule->Cast(subMemberRefExpr->mMemberName, thisValue, type, BfCastFlags_Explicit);
  13973. if (castedThis)
  13974. thisValue = castedThis;
  13975. //mModule->Fail("Explicit base types can only be used for specifying default interface members", qualifiedLeft->mLeft);
  13976. }
  13977. }
  13978. handled = true;
  13979. }
  13980. bypassVirtual = true;
  13981. }
  13982. }
  13983. }
  13984. }
  13985. }
  13986. if (!handled)
  13987. {
  13988. SetAndRestoreValue<BfAttributeState*> prevAttributeState(mModule->mAttributeState, &attributeState);
  13989. auto flags = (BfEvalExprFlags)(BfEvalExprFlags_PropogateNullConditional | BfEvalExprFlags_NoCast);
  13990. if (mFunctionBindResult != NULL)
  13991. {
  13992. if (auto paranExpr = BfNodeDynCast<BfParenthesizedExpression>(expr))
  13993. {
  13994. // Allow 'ref' on binding, to indicate we want to capture 'this' by reference
  13995. flags = (BfEvalExprFlags)(flags | BfEvalExprFlags_AllowRefExpr);
  13996. expr = paranExpr->mExpression;
  13997. }
  13998. }
  13999. if (expr != NULL)
  14000. mResult = mModule->CreateValueFromExpression(expr, expectingTargetType, flags);
  14001. }
  14002. }
  14003. isCascade = (memberRefExpression->mDotToken != NULL) && (memberRefExpression->mDotToken->GetToken() == BfToken_DotDot);
  14004. if (isCascade)
  14005. cascadeOperatorToken = memberRefExpression->mDotToken;
  14006. bool isNullCondLookup = (memberRefExpression->mDotToken != NULL) && (memberRefExpression->mDotToken->GetToken() == BfToken_QuestionDot);
  14007. if (isNullCondLookup)
  14008. mResult = SetupNullConditional(mResult, memberRefExpression->mDotToken);
  14009. if ((mResult.mType == NULL) && (memberRefExpression->mTarget != NULL))
  14010. {
  14011. mModule->AssertErrorState();
  14012. mResult = mModule->GetDefaultTypedValue(mModule->mContext->mBfObjectType);
  14013. }
  14014. thisValue = mResult;
  14015. mResult = BfTypedValue();
  14016. }
  14017. else if (auto qualifiedName = BfNodeDynCast<BfQualifiedNameNode>(target))
  14018. {
  14019. if (GetAutoComplete() != NULL)
  14020. GetAutoComplete()->CheckMemberReference(qualifiedName->mLeft, qualifiedName->mDot, qualifiedName->mRight);
  14021. if (qualifiedName->mLeft->GetSrcLength() == 4)
  14022. {
  14023. if (CheckIsBase(qualifiedName->mLeft))
  14024. bypassVirtual = true;
  14025. }
  14026. if (qualifiedName->mRight != NULL)
  14027. methodNodeSrc = qualifiedName->mRight;
  14028. if (auto attrIdentifier = BfNodeDynCast<BfAttributedIdentifierNode>(qualifiedName->mRight))
  14029. {
  14030. if (attrIdentifier->mIdentifier != NULL)
  14031. methodNodeSrc = attrIdentifier->mIdentifier;
  14032. attributeState.mSrc = attrIdentifier->mAttributes;
  14033. attributeState.mCustomAttributes = mModule->GetCustomAttributes(attrIdentifier->mAttributes, attributeState.mTarget);
  14034. targetFunctionName = attrIdentifier->mIdentifier->ToString();
  14035. }
  14036. else
  14037. targetFunctionName = qualifiedName->mRight->ToString();
  14038. bool hadError = false;
  14039. thisValue = LookupIdentifier(qualifiedName->mLeft, true, &hadError);
  14040. CheckResultForReading(thisValue);
  14041. if (mPropDef != NULL)
  14042. thisValue = GetResult(true);
  14043. if (hadError)
  14044. {
  14045. mModule->AssertErrorState();
  14046. thisValue = mModule->GetDefaultTypedValue(mModule->mContext->mBfObjectType);
  14047. }
  14048. if ((!thisValue) && (mPropDef == NULL))
  14049. {
  14050. // Identifier not found. Static method? Just check speculatively don't throw error
  14051. BfType* type;
  14052. {
  14053. //SetAndRestoreValue<bool> prevIgnoreErrors(mModule->mIgnoreErrors, true);
  14054. type = mModule->ResolveTypeRef(qualifiedName->mLeft, NULL, BfPopulateType_DataAndMethods, (BfResolveTypeRefFlags)(BfResolveTypeRefFlag_NoResolveGenericParam | BfResolveTypeRefFlag_IgnoreLookupError));
  14055. }
  14056. if (type == NULL)
  14057. {
  14058. //SetAndRestoreValue<bool> prevIgnoreErrors(mModule->mIgnoreErrors, true);
  14059. type = mModule->ResolveTypeRef(qualifiedName, methodGenericArguments, BfPopulateType_DataAndMethods, (BfResolveTypeRefFlags)(BfResolveTypeRefFlag_NoResolveGenericParam | BfResolveTypeRefFlag_IgnoreLookupError));
  14060. if (type != NULL)
  14061. {
  14062. // This is a CTOR call, treat it as such
  14063. targetFunctionName.clear();
  14064. }
  14065. }
  14066. if (type != NULL)
  14067. thisValue = BfTypedValue(type);
  14068. else if (auto qualifiedLeft = BfNodeDynCast<BfQualifiedNameNode>(qualifiedName->mLeft))
  14069. {
  14070. String findName = qualifiedLeft->mRight->ToString();
  14071. bool handled = false;
  14072. if (findName == "base")
  14073. {
  14074. auto type = mModule->ResolveTypeRef(qualifiedLeft->mLeft, NULL, BfPopulateType_Data, BfResolveTypeRefFlag_AllowRef);
  14075. mModule->CheckTypeRefFixit(qualifiedLeft->mLeft);
  14076. thisValue = mModule->GetThis();
  14077. if (type != NULL)
  14078. {
  14079. if ((thisValue.mType == type) || (!mModule->TypeIsSubTypeOf(thisValue.mType->ToTypeInstance(), type->ToTypeInstance())))
  14080. {
  14081. mModule->Fail(StrFormat("Type '%s' is not a base type of '%s'",
  14082. mModule->TypeToString(type).c_str(),
  14083. mModule->TypeToString(thisValue.mType).c_str()), qualifiedLeft->mLeft);
  14084. }
  14085. else
  14086. {
  14087. if (type->IsInterface())
  14088. {
  14089. thisValue.mType = type;
  14090. }
  14091. else
  14092. {
  14093. auto castedThis = mModule->Cast(qualifiedLeft->mRight, thisValue, type, BfCastFlags_Explicit);
  14094. if (castedThis)
  14095. thisValue = castedThis;
  14096. //mModule->Fail("Explicit base types can only be used for specifying default interface members", qualifiedLeft->mLeft);
  14097. }
  14098. }
  14099. handled = true;
  14100. }
  14101. bypassVirtual = true;
  14102. }
  14103. if (!handled)
  14104. {
  14105. LookupQualifiedStaticField(qualifiedLeft, true);
  14106. thisValue = mResult;
  14107. mResult = BfTypedValue();
  14108. }
  14109. }
  14110. }
  14111. if (mPropDef != NULL)
  14112. thisValue = GetResult(true);
  14113. if (!thisValue.mType)
  14114. {
  14115. mModule->Fail("Identifier not found", qualifiedName->mLeft);
  14116. mModule->CheckTypeRefFixit(qualifiedName->mLeft);
  14117. mModule->CheckIdentifierFixit(qualifiedName->mLeft);
  14118. thisValue = mModule->GetDefaultTypedValue(mModule->GetPrimitiveType(BfTypeCode_Var));
  14119. }
  14120. if (mResult)
  14121. CheckResultForReading(mResult);
  14122. mResult = BfTypedValue();
  14123. }
  14124. else if (auto identiferExpr = BfNodeDynCast<BfIdentifierNode>(target))
  14125. {
  14126. if (auto attrIdentifier = BfNodeDynCast<BfAttributedIdentifierNode>(target))
  14127. {
  14128. if (attrIdentifier->mIdentifier != NULL)
  14129. methodNodeSrc = attrIdentifier->mIdentifier;
  14130. attributeState.mSrc = attrIdentifier->mAttributes;
  14131. attributeState.mCustomAttributes = mModule->GetCustomAttributes(attrIdentifier->mAttributes, attributeState.mTarget);
  14132. }
  14133. allowImplicitThis = true;
  14134. if (autoComplete != NULL)
  14135. autoComplete->CheckIdentifier(identiferExpr);
  14136. targetFunctionName = target->ToString();
  14137. if (targetFunctionName == "PrintF") // Just directly call that one
  14138. {
  14139. BfType* charType = mModule->GetPrimitiveType(BfTypeCode_Char8);
  14140. BfType* charPtrType = mModule->CreatePointerType(charType);
  14141. auto func = mModule->GetBuiltInFunc(BfBuiltInFuncType_PrintF);
  14142. SizedArray<BfIRValue, 4> irArgs;
  14143. for (BfExpression* arg : args)
  14144. {
  14145. BfTypedValue value;
  14146. if (arg != NULL)
  14147. value = mModule->CreateValueFromExpression(arg);
  14148. if (!value)
  14149. return;
  14150. auto typeInst = value.mType->ToTypeInstance();
  14151. if ((typeInst != NULL) && (typeInst->mTypeDef == mModule->mCompiler->mStringTypeDef))
  14152. value = mModule->Cast(arg, value, charPtrType);
  14153. if ((value.mType->IsFloat()) && (value.mType->mSize != 8)) // Always cast float to double
  14154. value = mModule->Cast(arg, value, mModule->GetPrimitiveType(BfTypeCode_Double));
  14155. irArgs.push_back(value.mValue);
  14156. }
  14157. if ((targetFunctionName != "PrintF") || (irArgs.size() > 0))
  14158. {
  14159. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateCall(func, irArgs/*, targetFunctionName*/),
  14160. mModule->ResolveTypeDef(mModule->mSystem->mTypeInt32));
  14161. }
  14162. return;
  14163. }
  14164. }
  14165. else if (auto expr = BfNodeDynCast<BfExpression>(target))
  14166. {
  14167. auto innerInvocationResult = mModule->CreateValueFromExpression(expr);
  14168. if (!innerInvocationResult)
  14169. {
  14170. mModule->AssertErrorState();
  14171. innerInvocationResult = mModule->GetDefaultTypedValue(mModule->mContext->mBfObjectType);
  14172. }
  14173. if (innerInvocationResult.mType->IsVar())
  14174. {
  14175. mResult = innerInvocationResult;
  14176. return;
  14177. }
  14178. targetFunctionName = "Invoke";
  14179. if (innerInvocationResult.mType->IsTypeInstance())
  14180. {
  14181. auto invocationTypeInst = innerInvocationResult.mType->ToTypeInstance();
  14182. if (invocationTypeInst->mTypeDef->mIsDelegate)
  14183. {
  14184. thisValue = innerInvocationResult;
  14185. }
  14186. }
  14187. if (!thisValue)
  14188. {
  14189. mModule->Fail(StrFormat("Cannot perform invocation on type '%s'", mModule->TypeToString(innerInvocationResult.mType).c_str()), expr);
  14190. thisValue = mModule->GetDefaultTypedValue(mModule->mContext->mBfObjectType);
  14191. }
  14192. }
  14193. else
  14194. {
  14195. mModule->Fail("Invalid invocation target", target);
  14196. thisValue = mModule->GetDefaultTypedValue(mModule->mContext->mBfObjectType);
  14197. }
  14198. if ((wasCapturingMethodInfo) && (autoComplete->mMethodMatchInfo != NULL))
  14199. {
  14200. autoComplete->mIsCapturingMethodMatchInfo = true;
  14201. BF_ASSERT(autoComplete->mMethodMatchInfo != NULL);
  14202. }
  14203. SetAndRestoreValue<BfAttributeState*> prevAttributeState;
  14204. if (attributeState.mCustomAttributes != NULL)
  14205. prevAttributeState.Init(mModule->mAttributeState, &attributeState);
  14206. if ((targetFunctionName != "") && (targetFunctionName[targetFunctionName.length() - 1] == '!'))
  14207. {
  14208. targetFunctionName = targetFunctionName.Substring(0, targetFunctionName.length() - 1);
  14209. InjectMixin(methodNodeSrc, thisValue, allowImplicitThis, targetFunctionName, args, methodGenericArguments);
  14210. return;
  14211. }
  14212. //TODO: We removed this... Messed up with PrimStruct 'this' non-mut errors
  14213. // 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
  14214. /*if (thisValue)
  14215. {
  14216. if ((!thisValue.mType->IsGenericParam()) && (!thisValue.IsSplat()) && (!thisValue.mType->IsVar()))
  14217. thisValue = MakeCallableTarget(target, thisValue);
  14218. }*/
  14219. int methodCount = 0;
  14220. bool mayBeSkipCall = false;
  14221. bool mayBeComptimeCall = false;
  14222. if (thisValue.mType != NULL)
  14223. {
  14224. if (thisValue.mType->IsAllocType())
  14225. thisValue.mType = thisValue.mType->GetUnderlyingType();
  14226. auto checkTypeInst = thisValue.mType->ToTypeInstance();
  14227. while (checkTypeInst != NULL)
  14228. {
  14229. checkTypeInst->mTypeDef->PopulateMemberSets();
  14230. BfMemberSetEntry* memberSetEntry;
  14231. if (checkTypeInst->mTypeDef->mMethodSet.TryGetWith(targetFunctionName, &memberSetEntry))
  14232. {
  14233. BfMethodDef* methodDef = (BfMethodDef*)memberSetEntry->mMemberDef;
  14234. while (methodDef != NULL)
  14235. {
  14236. if (methodDef->mIsSkipCall)
  14237. mayBeSkipCall = true;
  14238. if (methodDef->mHasComptime)
  14239. mayBeComptimeCall = true;
  14240. methodDef = methodDef->mNextWithSameName;
  14241. }
  14242. }
  14243. checkTypeInst = checkTypeInst->mBaseType;
  14244. }
  14245. }
  14246. SizedArray<BfExpression*, 8> copiedArgs;
  14247. for (BfExpression* arg : args)
  14248. copiedArgs.push_back(arg);
  14249. BfSizedArray<BfExpression*> sizedCopiedArgs(copiedArgs);
  14250. BfResolvedArgs argValues(&sizedCopiedArgs);
  14251. if (mModule->mParentNodeEntry != NULL)
  14252. {
  14253. if (auto invocationExpr = BfNodeDynCast<BfInvocationExpression>(mModule->mParentNodeEntry->mNode))
  14254. {
  14255. argValues.mOpenToken = invocationExpr->mOpenParen;
  14256. argValues.mCommas = &invocationExpr->mCommas;
  14257. argValues.mCloseToken = invocationExpr->mCloseParen;
  14258. }
  14259. }
  14260. BfResolveArgsFlags resolveArgsFlags = (BfResolveArgsFlags)(BfResolveArgsFlag_DeferFixits | BfResolveArgsFlag_AllowUnresolvedTypes);
  14261. resolveArgsFlags = (BfResolveArgsFlags)(resolveArgsFlags | BfResolveArgsFlag_DeferParamEval);
  14262. if ((mayBeSkipCall) || (mayBeComptimeCall))
  14263. resolveArgsFlags = (BfResolveArgsFlags)(resolveArgsFlags | BfResolveArgsFlag_DeferParamValues);
  14264. static int sCallIdx = 0;
  14265. sCallIdx++;
  14266. int callIdx = sCallIdx;
  14267. if (callIdx == 1557)
  14268. {
  14269. NOP;
  14270. }
  14271. BfCheckedKind checkedKind = BfCheckedKind_NotSet;
  14272. if ((mModule->mAttributeState != NULL) && (mModule->mAttributeState->mCustomAttributes != NULL))
  14273. {
  14274. if (mModule->mAttributeState->mCustomAttributes->Contains(mModule->mCompiler->mCheckedAttributeTypeDef))
  14275. {
  14276. checkedKind = BfCheckedKind_Checked;
  14277. mModule->mAttributeState->mUsed = true;
  14278. }
  14279. if (mModule->mAttributeState->mCustomAttributes->Contains(mModule->mCompiler->mUncheckedAttributeTypeDef))
  14280. {
  14281. checkedKind = BfCheckedKind_Unchecked;
  14282. mModule->mAttributeState->mUsed = true;
  14283. }
  14284. }
  14285. if ((isCascade) && (cascadeOperatorToken != NULL) && ((mBfEvalExprFlags & BfEvalExprFlags_Comptime) != 0))
  14286. mModule->Fail("Cascade operator cannot be used in const evaluation", cascadeOperatorToken);
  14287. SetAndRestoreValue<bool> prevUsedAsStatement(mUsedAsStatement, mUsedAsStatement || isCascade);
  14288. SetAndRestoreValue<BfEvalExprFlags> prevEvalExprFlags(mBfEvalExprFlags);
  14289. if (isCascade)
  14290. mBfEvalExprFlags = (BfEvalExprFlags)(mBfEvalExprFlags | BfEvalExprFlags_InCascade);
  14291. ResolveArgValues(argValues, resolveArgsFlags);
  14292. mResult = MatchMethod(methodNodeSrc, methodBoundExpr, thisValue, allowImplicitThis, bypassVirtual, targetFunctionName, argValues, methodGenericArguments, checkedKind);
  14293. argValues.HandleFixits(mModule);
  14294. if (mModule->mAttributeState == &attributeState)
  14295. mModule->FinishAttributeState(&attributeState);
  14296. if (isCascade)
  14297. {
  14298. if ((outCascadeValue != NULL) && (thisValue.mValue))
  14299. {
  14300. *outCascadeValue = thisValue;
  14301. }
  14302. else
  14303. {
  14304. mModule->Fail("Invalid use of cascade operator", cascadeOperatorToken);
  14305. }
  14306. }
  14307. }
  14308. void BfExprEvaluator::Visit(BfInvocationExpression* invocationExpr)
  14309. {
  14310. BfAutoParentNodeEntry autoParentNodeEntry(mModule, invocationExpr);
  14311. // We need to check for sized array constructor like "uint8[2](1, 2)"
  14312. if (BfNodeDynCastExact<BfIndexerExpression>(invocationExpr->mTarget) != NULL)
  14313. {
  14314. auto checkTarget = invocationExpr->mTarget;
  14315. while (auto indexerExpr = BfNodeDynCastExact<BfIndexerExpression>(checkTarget))
  14316. {
  14317. checkTarget = indexerExpr->mTarget;
  14318. }
  14319. SetAndRestoreValue<bool> prevIgnoreError(mModule->mIgnoreErrors, true);
  14320. auto resolvedType = mModule->ResolveTypeRef(checkTarget, NULL, BfPopulateType_Identity);
  14321. prevIgnoreError.Restore();
  14322. if (resolvedType != NULL)
  14323. {
  14324. BfType* curType = resolvedType;
  14325. auto checkTarget = invocationExpr->mTarget;
  14326. while (auto indexerExpr = BfNodeDynCastExact<BfIndexerExpression>(checkTarget))
  14327. {
  14328. checkTarget = indexerExpr->mTarget;
  14329. if (indexerExpr->mCommas.size() != 0)
  14330. 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]);
  14331. int arrSize = 0;
  14332. BfTypeState typeState;
  14333. typeState.mArrayInitializerSize = (int)invocationExpr->mArguments.size();
  14334. SetAndRestoreValue<BfTypeState*> prevTypeState(mModule->mContext->mCurTypeState, &typeState);
  14335. if (indexerExpr->mArguments.size() != 0)
  14336. {
  14337. BfConstResolver constResolver(mModule);
  14338. auto arg = indexerExpr->mArguments[0];
  14339. constResolver.mExpectingType = mModule->GetPrimitiveType(BfTypeCode_IntPtr);
  14340. if (arg != NULL)
  14341. constResolver.Resolve(arg, NULL, BfConstResolveFlag_ArrayInitSize);
  14342. if (constResolver.mResult.mValue.IsConst())
  14343. {
  14344. auto constant = mModule->mBfIRBuilder->GetConstant(constResolver.mResult.mValue);
  14345. if ((mModule->mBfIRBuilder->IsInt(constant->mTypeCode)) && (constant->mInt64 >= 0))
  14346. {
  14347. arrSize = constant->mInt32;
  14348. }
  14349. else
  14350. mModule->Fail("Non-negative integer expected", indexerExpr->mArguments[0]);
  14351. }
  14352. }
  14353. else
  14354. arrSize = invocationExpr->mArguments.size();
  14355. curType = mModule->CreateSizedArrayType(curType, arrSize);
  14356. }
  14357. InitializedSizedArray((BfSizedArrayType*)curType, invocationExpr->mOpenParen, invocationExpr->mArguments, invocationExpr->mCommas, invocationExpr->mCloseParen, NULL);
  14358. return;
  14359. }
  14360. }
  14361. auto autoComplete = GetAutoComplete();
  14362. auto wasCapturingMethodInfo = (autoComplete != NULL) && (autoComplete->mIsCapturingMethodMatchInfo);
  14363. if (autoComplete != NULL)
  14364. autoComplete->CheckInvocation(invocationExpr, invocationExpr->mOpenParen, invocationExpr->mCloseParen, invocationExpr->mCommas);
  14365. mModule->UpdateExprSrcPos(invocationExpr);
  14366. BfSizedArray<ASTREF(BfTypeReference*)>* methodGenericArguments = NULL;
  14367. if (invocationExpr->mGenericArgs != NULL)
  14368. methodGenericArguments = &invocationExpr->mGenericArgs->mGenericArgs;
  14369. SizedArray<BfExpression*, 8> copiedArgs;
  14370. for (BfExpression* arg : invocationExpr->mArguments)
  14371. copiedArgs.push_back(arg);
  14372. BfTypedValue cascadeValue;
  14373. DoInvocation(invocationExpr->mTarget, invocationExpr, copiedArgs, methodGenericArguments, &cascadeValue);
  14374. if (autoComplete != NULL)
  14375. {
  14376. if ((wasCapturingMethodInfo) && (!autoComplete->mIsCapturingMethodMatchInfo))
  14377. {
  14378. if (autoComplete->mMethodMatchInfo != NULL)
  14379. autoComplete->mIsCapturingMethodMatchInfo = true;
  14380. else
  14381. autoComplete->mIsCapturingMethodMatchInfo = false;
  14382. //BF_ASSERT(autoComplete->mMethodMatchInfo != NULL);
  14383. }
  14384. else
  14385. autoComplete->mIsCapturingMethodMatchInfo = false;
  14386. }
  14387. /// Previous check for discard
  14388. if (cascadeValue)
  14389. mResult = cascadeValue;
  14390. }
  14391. BfMethodDef* BfExprEvaluator::GetPropertyMethodDef(BfPropertyDef* propDef, BfMethodType methodType, BfCheckedKind checkedKind, BfTypedValue propTarget)
  14392. {
  14393. bool allowMut = true;
  14394. if ((propTarget) && (propTarget.mType->IsValueType()))
  14395. {
  14396. if (propTarget.IsReadOnly())
  14397. {
  14398. allowMut = false;
  14399. }
  14400. else if (!propTarget.IsAddr())
  14401. {
  14402. mModule->PopulateType(propTarget.mType);
  14403. if (!propTarget.IsValuelessType())
  14404. allowMut = false;
  14405. }
  14406. }
  14407. int bestPri = -1000;
  14408. BfMethodDef* matchedMethod = NULL;
  14409. for (auto methodDef : propDef->mMethods)
  14410. {
  14411. if (methodDef->mMethodType != methodType)
  14412. continue;
  14413. int curPri = 0;
  14414. if (methodDef->mCheckedKind == checkedKind)
  14415. {
  14416. curPri = 5;
  14417. }
  14418. else if ((checkedKind == BfCheckedKind_NotSet) && (methodDef->mCheckedKind == mModule->GetDefaultCheckedKind()))
  14419. curPri = 3;
  14420. else
  14421. curPri = 1;
  14422. if (methodDef->mIsMutating)
  14423. {
  14424. if (allowMut)
  14425. curPri++;
  14426. else
  14427. curPri -= 10;
  14428. }
  14429. if (curPri > bestPri)
  14430. {
  14431. bestPri = curPri;
  14432. matchedMethod = methodDef;
  14433. }
  14434. }
  14435. return matchedMethod;
  14436. /*BfMethodDef* matchedMethod = NULL;
  14437. BfMethodDef* backupMethod = NULL;
  14438. for (auto methodDef : propDef->mMethods)
  14439. {
  14440. if (methodDef->mMethodType != methodType)
  14441. continue;
  14442. if (methodDef->mCheckedKind == checkedKind)
  14443. {
  14444. matchedMethod = methodDef;
  14445. break;
  14446. }
  14447. if ((checkedKind == BfCheckedKind_NotSet) && (methodDef->mCheckedKind == mModule->GetDefaultCheckedKind()))
  14448. matchedMethod = methodDef;
  14449. else
  14450. backupMethod = methodDef;
  14451. }
  14452. if (matchedMethod == NULL)
  14453. matchedMethod = backupMethod;
  14454. return matchedMethod;*/
  14455. }
  14456. BfModuleMethodInstance BfExprEvaluator::GetPropertyMethodInstance(BfMethodDef* methodDef)
  14457. {
  14458. if (mPropDefBypassVirtual)
  14459. {
  14460. if (mPropTarget.mType->IsInterface())
  14461. {
  14462. auto curTypeInst = mPropTarget.mType->ToTypeInstance();
  14463. if (mModule->TypeIsSubTypeOf(mModule->mCurTypeInstance, curTypeInst))
  14464. {
  14465. if (methodDef->mBody != NULL)
  14466. {
  14467. // This is an explicit call to a default static interface method. We pull the methodDef into our own concrete type.
  14468. mPropTarget = mModule->GetThis();
  14469. return mModule->GetMethodInstance(mModule->mCurTypeInstance, methodDef, BfTypeVector(), BfGetMethodInstanceFlag_ForeignMethodDef, curTypeInst);
  14470. }
  14471. }
  14472. else
  14473. {
  14474. mModule->Fail("Property is not implemented by this type", mPropSrc);
  14475. return BfModuleMethodInstance();
  14476. }
  14477. }
  14478. else
  14479. {
  14480. auto propTypeInst = mPropTarget.mType->ToTypeInstance();
  14481. mModule->PopulateType(propTypeInst, BfPopulateType_DataAndMethods);
  14482. auto rawMethodInstance = mModule->GetRawMethodInstance(propTypeInst, methodDef);
  14483. if (rawMethodInstance->mVirtualTableIdx == -1)
  14484. {
  14485. if (!mModule->mCompiler->mIsResolveOnly)
  14486. {
  14487. // ResolveOnly does not force methods to slot
  14488. BF_ASSERT(rawMethodInstance->mVirtualTableIdx != -1);
  14489. mModule->Fail(StrFormat("Failed to devirtualize %s", mModule->MethodToString(rawMethodInstance).c_str()));
  14490. }
  14491. }
  14492. else
  14493. {
  14494. auto useTypeInst = mOrigPropTarget.mType->ToTypeInstance();
  14495. auto virtualMethod = (BfMethodInstance*)useTypeInst->mVirtualMethodTable[rawMethodInstance->mVirtualTableIdx].mImplementingMethod;
  14496. return mModule->ReferenceExternalMethodInstance(virtualMethod);
  14497. }
  14498. }
  14499. }
  14500. if ((mOrigPropTarget) && (mOrigPropTarget.mType != mPropTarget.mType) &&
  14501. ((!mOrigPropTarget.mType->IsGenericParam()) && (mPropTarget.mType->IsInterface())))
  14502. {
  14503. auto checkType = mOrigPropTarget.mType;
  14504. if (checkType->IsPointer())
  14505. checkType = ((BfPointerType*)checkType)->mElementType;
  14506. if (checkType->IsWrappableType())
  14507. checkType = mModule->GetWrappedStructType(checkType);
  14508. if ((checkType != NULL) && (checkType->IsTypeInstance()))
  14509. {
  14510. auto activeTypeDef = mModule->GetActiveTypeDef();
  14511. BfTypeInterfaceEntry* bestIFaceEntry = NULL;
  14512. bool checkedUnderlying = false;
  14513. auto checkTypeInst = checkType->ToTypeInstance();
  14514. while (checkTypeInst != NULL)
  14515. {
  14516. mModule->PopulateType(checkTypeInst, BfPopulateType_DataAndMethods);
  14517. BF_ASSERT((checkTypeInst->mDefineState >= BfTypeDefineState_DefinedAndMethodsSlotted) || (mModule->mCompiler->IsAutocomplete()));
  14518. if (checkTypeInst->mDefineState != BfTypeDefineState_DefinedAndMethodsSlotted)
  14519. break;
  14520. for (auto& iface : checkTypeInst->mInterfaces)
  14521. {
  14522. if (!mModule->IsInSpecializedSection())
  14523. {
  14524. if (!checkTypeInst->IsTypeMemberAccessible(iface.mDeclaringType, activeTypeDef))
  14525. continue;
  14526. }
  14527. if (iface.mInterfaceType == mPropTarget.mType)
  14528. {
  14529. if (bestIFaceEntry == NULL)
  14530. {
  14531. bestIFaceEntry = &iface;
  14532. continue;
  14533. }
  14534. bool isBetter;
  14535. bool isWorse;
  14536. mModule->CompareDeclTypes(iface.mDeclaringType, bestIFaceEntry->mDeclaringType, isBetter, isWorse);
  14537. if (isBetter == isWorse)
  14538. {
  14539. // Failed
  14540. }
  14541. else
  14542. {
  14543. if (isBetter)
  14544. bestIFaceEntry = &iface;
  14545. }
  14546. }
  14547. }
  14548. if (bestIFaceEntry != NULL)
  14549. break;
  14550. checkTypeInst = checkTypeInst->mBaseType;
  14551. if (checkTypeInst == NULL)
  14552. {
  14553. if (!checkedUnderlying)
  14554. {
  14555. checkedUnderlying = true;
  14556. if (checkType->HasWrappedRepresentation())
  14557. {
  14558. auto underlyingType = checkType->GetUnderlyingType();
  14559. if (underlyingType != NULL)
  14560. checkTypeInst = mModule->GetWrappedStructType(underlyingType);
  14561. }
  14562. }
  14563. }
  14564. }
  14565. if (bestIFaceEntry != NULL)
  14566. {
  14567. auto ifaceMethodEntry = checkTypeInst->mInterfaceMethodTable[bestIFaceEntry->mStartInterfaceTableIdx + methodDef->mIdx];
  14568. BfMethodInstance* bestMethodInstance = ifaceMethodEntry.mMethodRef;
  14569. if (bestMethodInstance != NULL)
  14570. {
  14571. mPropTarget = mOrigPropTarget;
  14572. //mPropTarget.mType = checkTypeInst;
  14573. //mPropTarget = mModule->Cast( mOrigPropTarget, checkTypeInst);
  14574. return mModule->GetMethodInstanceAtIdx(ifaceMethodEntry.mMethodRef.mTypeInstance, ifaceMethodEntry.mMethodRef.mMethodNum);
  14575. }
  14576. }
  14577. }
  14578. mModule->AssertErrorState();
  14579. return BfModuleMethodInstance();
  14580. }
  14581. auto propTypeInst = mPropTarget.mType->ToTypeInstance();
  14582. if (propTypeInst == NULL)
  14583. {
  14584. propTypeInst = mModule->GetWrappedStructType(mPropTarget.mType);
  14585. }
  14586. if (propTypeInst == NULL)
  14587. {
  14588. mModule->Fail("INTERNAL ERROR: Invalid property target", mPropSrc);
  14589. return BfModuleMethodInstance();
  14590. }
  14591. return mModule->GetMethodInstance(propTypeInst, methodDef, BfTypeVector(), mPropGetMethodFlags);
  14592. }
  14593. void BfExprEvaluator::CheckPropFail(BfMethodDef* propMethodDef, BfMethodInstance* methodInstance, bool checkProt)
  14594. {
  14595. auto propTypeInst = mPropTarget.mType->ToTypeInstance();
  14596. // If mExplicitInterface is null then we are implicitly calling through an interface
  14597. if ((checkProt) && (propTypeInst != NULL) && (methodInstance->GetExplicitInterface() == NULL) &&
  14598. (!mModule->CheckAccessMemberProtection(propMethodDef->mProtection, propTypeInst)))
  14599. mModule->Fail(StrFormat("'%s' is inaccessible due to its protection level", mModule->MethodToString(methodInstance).c_str()), mPropSrc);
  14600. else if (mPropCheckedKind != methodInstance->mMethodDef->mCheckedKind)
  14601. {
  14602. bool passes = true;
  14603. if (mPropCheckedKind != BfCheckedKind_NotSet)
  14604. {
  14605. passes = false;
  14606. }
  14607. else
  14608. {
  14609. auto defaultCheckedKind = mModule->GetDefaultCheckedKind();
  14610. if (defaultCheckedKind != methodInstance->mMethodDef->mCheckedKind)
  14611. passes = false;
  14612. }
  14613. if (!passes)
  14614. {
  14615. 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);
  14616. if (error != NULL)
  14617. {
  14618. if ((error != NULL) && (methodInstance->mMethodDef->mMethodDeclaration != NULL))
  14619. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("See method declaration"), methodInstance->mMethodDef->GetRefNode());
  14620. }
  14621. }
  14622. }
  14623. }
  14624. bool BfExprEvaluator::HasResult()
  14625. {
  14626. return (mResult) || (mPropDef != NULL);
  14627. }
  14628. BfTypedValue BfExprEvaluator::GetResult(bool clearResult, bool resolveGenericType)
  14629. {
  14630. if ((!mResult) && (mPropDef != NULL))
  14631. {
  14632. bool handled = false;
  14633. if (mPropTarget.mType->IsGenericTypeInstance())
  14634. {
  14635. auto genericTypeInst = (BfTypeInstance*)mPropTarget.mType;
  14636. if (genericTypeInst->mTypeDef == mModule->mCompiler->mSizedArrayTypeDef)
  14637. {
  14638. if (mPropDef->mName == "Count")
  14639. {
  14640. auto sizedType = genericTypeInst->mGenericTypeInfo->mTypeGenericArguments[1];
  14641. if (sizedType->IsConstExprValue())
  14642. {
  14643. auto constExprType = (BfConstExprValueType*)sizedType;
  14644. mResult = BfTypedValue(mModule->GetConstValue(constExprType->mValue.mInt64), mModule->GetPrimitiveType(BfTypeCode_IntPtr));
  14645. handled = true;
  14646. }
  14647. else
  14648. {
  14649. BF_ASSERT(mModule->mCurMethodInstance->mIsUnspecialized);
  14650. mResult = BfTypedValue(mModule->mBfIRBuilder->GetUndefConstValue(mModule->mBfIRBuilder->GetPrimitiveType(BfTypeCode_IntPtr)), mModule->GetPrimitiveType(BfTypeCode_IntPtr));
  14651. handled = true;
  14652. }
  14653. }
  14654. }
  14655. }
  14656. if (!handled)
  14657. {
  14658. SetAndRestoreValue<BfFunctionBindResult*> prevFunctionBindResult(mFunctionBindResult, NULL);
  14659. SetAndRestoreValue<BfAstNode*> prevDeferCallRef(mDeferCallRef, NULL);
  14660. BfMethodDef* matchedMethod = GetPropertyMethodDef(mPropDef, BfMethodType_PropertyGetter, mPropCheckedKind, mPropTarget);
  14661. if (matchedMethod == NULL)
  14662. {
  14663. mModule->Fail("Property has no getter", mPropSrc);
  14664. return mResult;
  14665. }
  14666. auto methodInstance = GetPropertyMethodInstance(matchedMethod);
  14667. if (methodInstance.mMethodInstance == NULL)
  14668. return mResult;
  14669. BF_ASSERT(methodInstance.mMethodInstance->mMethodDef->mName == matchedMethod->mName);
  14670. if (!mModule->mBfIRBuilder->mIgnoreWrites)
  14671. {
  14672. BF_ASSERT(!methodInstance.mFunc.IsFake());
  14673. }
  14674. if (mPropSrc != NULL)
  14675. mModule->UpdateExprSrcPos(mPropSrc);
  14676. auto autoComplete = GetAutoComplete();
  14677. if ((autoComplete != NULL) && (autoComplete->IsAutocompleteNode(mPropSrc)) && (autoComplete->mResolveType == BfResolveType_GetResultString))
  14678. {
  14679. autoComplete->mResultString = ":";
  14680. autoComplete->mResultString += mModule->TypeToString(methodInstance.mMethodInstance->mReturnType);
  14681. autoComplete->mResultString += " ";
  14682. autoComplete->mResultString += mModule->TypeToString(methodInstance.mMethodInstance->GetOwner());
  14683. autoComplete->mResultString += ".";
  14684. autoComplete->mResultString += mPropDef->mName;
  14685. }
  14686. CheckPropFail(matchedMethod, methodInstance.mMethodInstance, (mPropGetMethodFlags & BfGetMethodInstanceFlag_Friend) == 0);
  14687. PerformCallChecks(methodInstance.mMethodInstance, mPropSrc);
  14688. if (methodInstance.mMethodInstance->IsSkipCall())
  14689. {
  14690. mResult = mModule->GetDefaultTypedValue(methodInstance.mMethodInstance->mReturnType);
  14691. }
  14692. else
  14693. {
  14694. SizedArray<BfIRValue, 4> args;
  14695. if (!matchedMethod->mIsStatic)
  14696. {
  14697. auto owner = methodInstance.mMethodInstance->GetOwner();
  14698. bool isTypeMatch = mPropTarget.mType == owner;
  14699. if (owner->IsTypedPrimitive())
  14700. isTypeMatch |= mPropTarget.mType == owner->GetUnderlyingType();
  14701. if ((!isTypeMatch) ||
  14702. ((mPropTarget.mValue.IsFake()) && (!mOrigPropTarget.mValue.IsFake())))
  14703. {
  14704. auto prevPropTarget = mPropTarget;
  14705. mPropTarget = mModule->Cast(mPropSrc, mOrigPropTarget, owner);
  14706. if (!mPropTarget)
  14707. {
  14708. mModule->Fail("Internal property error", mPropSrc);
  14709. return BfTypedValue();
  14710. }
  14711. }
  14712. if ((mPropGetMethodFlags & BfGetMethodInstanceFlag_DisableObjectAccessChecks) == 0)
  14713. mModule->EmitObjectAccessCheck(mPropTarget);
  14714. PushThis(mPropSrc, mPropTarget, methodInstance.mMethodInstance, args);
  14715. }
  14716. bool failed = false;
  14717. for (int paramIdx = 0; paramIdx < (int)mIndexerValues.size(); paramIdx++)
  14718. {
  14719. auto refNode = mIndexerValues[paramIdx].mExpression;
  14720. auto wantType = methodInstance.mMethodInstance->GetParamType(paramIdx);
  14721. auto argValue = ResolveArgValue(mIndexerValues[paramIdx], wantType);
  14722. if (refNode == NULL)
  14723. refNode = mPropSrc;
  14724. BfTypedValue val;
  14725. if (argValue)
  14726. val = mModule->Cast(refNode, argValue, wantType);
  14727. if (!val)
  14728. failed = true;
  14729. else
  14730. PushArg(val, args);
  14731. }
  14732. if (mPropDefBypassVirtual)
  14733. {
  14734. auto methodDef = methodInstance.mMethodInstance->mMethodDef;
  14735. if ((methodDef->mIsAbstract) && (mPropDefBypassVirtual))
  14736. {
  14737. mModule->Fail(StrFormat("Abstract base property method '%s' cannot be invoked", mModule->MethodToString(methodInstance.mMethodInstance).c_str()), mPropSrc);
  14738. }
  14739. }
  14740. if (failed)
  14741. {
  14742. auto returnType = methodInstance.mMethodInstance->mReturnType;
  14743. auto methodDef = methodInstance.mMethodInstance->mMethodDef;
  14744. if (returnType->IsRef())
  14745. {
  14746. auto result = mModule->GetDefaultTypedValue(returnType->GetUnderlyingType(), true, BfDefaultValueKind_Addr);
  14747. if (methodDef->mIsReadOnly)
  14748. result.mKind = BfTypedValueKind_ReadOnlyAddr;
  14749. return result;
  14750. }
  14751. else
  14752. {
  14753. auto val = mModule->GetDefaultTypedValue(returnType, true, (GetStructRetIdx(methodInstance.mMethodInstance) != -1) ? BfDefaultValueKind_Addr : BfDefaultValueKind_Value);
  14754. if (val.mKind == BfTypedValueKind_Addr)
  14755. val.mKind = BfTypedValueKind_TempAddr;
  14756. return val;
  14757. }
  14758. }
  14759. else
  14760. mResult = CreateCall(mPropSrc, methodInstance.mMethodInstance, methodInstance.mFunc, mPropDefBypassVirtual, args);
  14761. if (mResult.mType != NULL)
  14762. {
  14763. if ((mResult.mType->IsVar()) && (mModule->mCompiler->mIsResolveOnly))
  14764. mModule->Fail("Property type reference failed to resolve", mPropSrc);
  14765. BF_ASSERT(!mResult.mType->IsRef());
  14766. }
  14767. }
  14768. }
  14769. mPropDef = NULL;
  14770. mPropDefBypassVirtual = false;
  14771. mIndexerValues.clear();
  14772. mResultLocalVar = NULL;
  14773. mResultFieldInstance = NULL;
  14774. }
  14775. if (resolveGenericType)
  14776. ResolveGenericType();
  14777. BfTypedValue result = mResult;
  14778. if (clearResult)
  14779. mResult = BfTypedValue();
  14780. return result;
  14781. }
  14782. void BfExprEvaluator::CheckResultForReading(BfTypedValue& typedValue)
  14783. {
  14784. if (mModule->mCurMethodState == NULL)
  14785. return;
  14786. if ((mModule->mCurMethodState->mTempKind != BfMethodState::TempKind_None) || (mModule->mCurMethodState->mAllowUinitReads))
  14787. return;
  14788. if ((mModule->mCurTypeInstance->mResolvingVarField) || (mModule->mCurTypeInstance->mResolvingConstField))
  14789. return;
  14790. if ((typedValue) && (typedValue.IsAddr()))
  14791. {
  14792. if ((mResultLocalVar != NULL) && (mResultLocalVarRefNode != NULL))
  14793. {
  14794. SetAndRestoreValue<bool> prevIgnoreError(mModule->mIgnoreErrors);
  14795. if ((mModule->mCurMethodState->mClosureState != NULL) && (mModule->mCurMethodState->mClosureState->mCapturing))
  14796. {
  14797. // These errors can only be detected during capture time, so we don't ignore them on this pass
  14798. mModule->mIgnoreErrors = false;
  14799. }
  14800. int fieldIdx = mResultLocalVarField - 1;
  14801. auto localVar = mResultLocalVar;
  14802. if (localVar->mCompositeCount > 0)
  14803. {
  14804. mModule->Fail(StrFormat("Cannot read from composite '%s', it can only be used in an argument list", localVar->mName.c_str()), mResultLocalVarRefNode);
  14805. typedValue = BfTypedValue();
  14806. return;
  14807. }
  14808. if (localVar->mAssignedKind == BfLocalVarAssignKind_None)
  14809. {
  14810. mModule->TryLocalVariableInit(localVar);
  14811. }
  14812. if (localVar->mAssignedKind == BfLocalVarAssignKind_None)
  14813. {
  14814. auto methodStateForLocal = mModule->mCurMethodState->GetMethodStateForLocal(localVar);
  14815. bool isAssigned = false;
  14816. int64 undefinedFieldFlags = localVar->mUnassignedFieldFlags;
  14817. auto deferredLocalAssignData = methodStateForLocal->mDeferredLocalAssignData;
  14818. while ((deferredLocalAssignData != NULL) && (deferredLocalAssignData->mIsChained))
  14819. deferredLocalAssignData = deferredLocalAssignData->mChainedAssignData;
  14820. if (deferredLocalAssignData != NULL)
  14821. {
  14822. for (auto& assignedVar : deferredLocalAssignData->mAssignedLocals)
  14823. {
  14824. auto assignedLocal = assignedVar.mLocalVar;
  14825. if (assignedLocal == localVar)
  14826. {
  14827. int assignedFieldIdx = assignedVar.mLocalVarField;
  14828. if (assignedFieldIdx >= 0)
  14829. undefinedFieldFlags &= ~((int64)1 << assignedFieldIdx);
  14830. else
  14831. undefinedFieldFlags = 0;
  14832. }
  14833. }
  14834. }
  14835. if (fieldIdx == -1)
  14836. {
  14837. if (undefinedFieldFlags == 0)
  14838. isAssigned = true;
  14839. }
  14840. else
  14841. {
  14842. isAssigned = true;
  14843. for (int i = 0; i < mResultLocalVarFieldCount; i++)
  14844. if ((undefinedFieldFlags & (1LL << (fieldIdx + i))) != 0)
  14845. isAssigned = false;
  14846. }
  14847. if (!isAssigned)
  14848. {
  14849. if ((localVar->mIsThis) && (fieldIdx != -1))
  14850. {
  14851. // When we have initializers for fields, they won't all be processed in the autocomplte case
  14852. if (!mModule->mCompiler->IsAutocomplete())
  14853. {
  14854. auto bfError = mModule->Fail(StrFormat("Use of possibly unassigned field '%s'", mResultLocalVarRefNode->ToString().c_str()), mResultLocalVarRefNode, true);
  14855. }
  14856. }
  14857. else
  14858. {
  14859. mModule->Fail(StrFormat("Use of unassigned local variable '%s'", localVar->mName.c_str()), mResultLocalVarRefNode);
  14860. }
  14861. }
  14862. }
  14863. localVar->mReadFromId = mModule->mCurMethodState->GetRootMethodState()->mCurAccessId++;
  14864. }
  14865. }
  14866. }
  14867. void BfExprEvaluator::FinishExpressionResult()
  14868. {
  14869. CheckResultForReading(mResult);
  14870. mResultLocalVar = NULL;
  14871. mResultFieldInstance = NULL;
  14872. }
  14873. bool BfExprEvaluator::CheckAllowValue(const BfTypedValue& typedValue, BfAstNode* refNode)
  14874. {
  14875. return true;
  14876. }
  14877. void BfExprEvaluator::MarkResultUsed()
  14878. {
  14879. if (mResultLocalVar != NULL)
  14880. {
  14881. mResultLocalVar->mReadFromId = mModule->mCurMethodState->GetRootMethodState()->mCurAccessId++;
  14882. }
  14883. }
  14884. void BfExprEvaluator::MarkResultAssigned()
  14885. {
  14886. if (mResultLocalVar != NULL)
  14887. {
  14888. //int localIdx = mResultLocalVarIdx;
  14889. //if (localIdx == 0x7FFF)
  14890. //return;
  14891. auto localVar = mResultLocalVar;
  14892. int fieldIdx = mResultLocalVarField - 1;
  14893. int count = mResultLocalVarFieldCount;
  14894. if (fieldIdx == -1)
  14895. count = 1;
  14896. for (int i = 0; i < count; i++)
  14897. mModule->mCurMethodState->GetMethodStateForLocal(localVar)->LocalDefined(localVar, fieldIdx + i);
  14898. //if (localIdx != 0x7FFF)
  14899. {
  14900. if (localVar->mCompositeCount > 0)
  14901. {
  14902. mModule->Fail(StrFormat("Cannot write to composite '%s', it can only be used in an argument list", localVar->mName.c_str()), mResultLocalVarRefNode);
  14903. }
  14904. }
  14905. }
  14906. }
  14907. void BfExprEvaluator::MakeResultAsValue()
  14908. {
  14909. // Expressions like parens will turn a variable reference into a simple value
  14910. mResultLocalVar = NULL;
  14911. mResultFieldInstance = NULL;
  14912. }
  14913. bool BfExprEvaluator::CheckIsBase(BfAstNode* checkNode)
  14914. {
  14915. if (checkNode == NULL)
  14916. return false;
  14917. if (!checkNode->Equals("base"))
  14918. return false;
  14919. auto autoComplete = GetAutoComplete();
  14920. if ((autoComplete != NULL) && (autoComplete->IsAutocompleteNode(checkNode)))
  14921. {
  14922. if ((mModule->mCurTypeInstance != NULL) && (mModule->mCurTypeInstance->mBaseType != NULL))
  14923. autoComplete->SetDefinitionLocation(mModule->mCurTypeInstance->mBaseType->mTypeDef->GetRefNode());
  14924. }
  14925. return true;
  14926. }
  14927. bool BfExprEvaluator::CheckModifyResult(BfTypedValue typedVal, BfAstNode* refNode, const char* modifyType, bool onlyNeedsMut, bool emitWarning, bool skipCopyOnMutate)
  14928. {
  14929. if ((!skipCopyOnMutate) && (typedVal.IsCopyOnMutate()))
  14930. typedVal = mModule->CopyValue(typedVal);
  14931. BfLocalVariable* localVar = NULL;
  14932. bool isCapturedLocal = false;
  14933. if (mResultLocalVar != NULL)
  14934. {
  14935. localVar = mResultLocalVar;
  14936. localVar->mWrittenToId = mModule->mCurMethodState->GetRootMethodState()->mCurAccessId++;
  14937. }
  14938. else if (typedVal.IsThis())
  14939. {
  14940. localVar = mModule->GetThisVariable();
  14941. }
  14942. else if (typedVal.IsSplat())
  14943. {
  14944. for (auto checkLocal : mModule->mCurMethodState->mLocals)
  14945. {
  14946. if (checkLocal->mAddr == typedVal.mValue)
  14947. {
  14948. localVar = checkLocal;
  14949. break;
  14950. }
  14951. }
  14952. }
  14953. else if (typedVal.mValue.IsArg())
  14954. {
  14955. auto methodState = mModule->mCurMethodState->GetNonCaptureState();
  14956. localVar = methodState->mLocals[typedVal.mValue.mId];
  14957. }
  14958. if ((typedVal.mKind == BfTypedValueKind_MutableValue) && (onlyNeedsMut))
  14959. {
  14960. return true;
  14961. }
  14962. bool canModify = typedVal.CanModify();
  14963. auto _Fail = [&](const StringImpl& error, BfAstNode* refNode)
  14964. {
  14965. if (emitWarning)
  14966. return mModule->Warn(BfWarning_BF4204_AddressOfReadOnly, error, refNode);
  14967. else
  14968. return mModule->Fail(error, refNode);
  14969. };
  14970. if (localVar != NULL)
  14971. {
  14972. if (!canModify)
  14973. {
  14974. BfError* error = NULL;
  14975. if (localVar->mIsThis)
  14976. {
  14977. bool isClosure = false;
  14978. BfTypeInstance* checkTypeInst = localVar->mResolvedType->ToTypeInstance();
  14979. int fieldIdx = mResultLocalVarField - 1;
  14980. if ((!isCapturedLocal) && (mModule->mCurMethodState != NULL) && (mModule->mCurMethodState->mClosureState != NULL) && (mModule->mCurMethodState->mClosureState->mClosureType != NULL))
  14981. {
  14982. isClosure = true;
  14983. auto closureThis = mModule->mCurMethodState->mClosureState->mClosureType;
  14984. closureThis = checkTypeInst->mFieldInstances[0].mResolvedType->ToTypeInstance();
  14985. if (fieldIdx >= -1)
  14986. {
  14987. checkTypeInst = closureThis;
  14988. }
  14989. else
  14990. {
  14991. fieldIdx = -fieldIdx - 2;
  14992. isCapturedLocal = true;
  14993. }
  14994. }
  14995. if (fieldIdx < 0)
  14996. {
  14997. if (isClosure)
  14998. {
  14999. if (!mModule->mCurMethodState->mClosureState->mDeclaringMethodIsMutating)
  15000. error = _Fail(StrFormat("Cannot %s 'this' within struct lambda. Consider adding 'mut' specifier to this method.", modifyType), refNode);
  15001. else
  15002. error = _Fail(StrFormat("Cannot %s 'this' within struct lambda. Consider adding by-reference capture specifier [&] to lambda.", modifyType), refNode);
  15003. }
  15004. else if (localVar->mResolvedType->IsValueType())
  15005. {
  15006. error = _Fail(StrFormat("Cannot %s 'this' within struct method '%s'. Consider adding 'mut' specifier to this method.", modifyType,
  15007. mModule->MethodToString(mModule->mCurMethodInstance).c_str()), refNode);
  15008. }
  15009. else
  15010. {
  15011. error = _Fail(StrFormat("Cannot %s 'this' because '%s' is a reference type.", modifyType,
  15012. mModule->TypeToString(localVar->mResolvedType).c_str()), refNode);
  15013. }
  15014. return false;
  15015. }
  15016. else if (mResultFieldInstance != NULL)
  15017. {
  15018. if (isCapturedLocal)
  15019. {
  15020. 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,
  15021. mResultFieldInstance->GetFieldDef()->mName.c_str()), refNode);
  15022. }
  15023. else if (isClosure)
  15024. {
  15025. if (!mModule->mCurMethodState->mClosureState->mDeclaringMethodIsMutating)
  15026. error = _Fail(StrFormat("Cannot %s field '%s.%s' within struct lambda. Consider adding 'mut' specifier to this method.", modifyType,
  15027. mModule->TypeToString(mResultFieldInstance->mOwner).c_str(), mResultFieldInstance->GetFieldDef()->mName.c_str()), refNode);
  15028. else
  15029. error = _Fail(StrFormat("Cannot %s field '%s.%s' within struct lambda. Consider adding by-reference capture specifier [&] to lambda.", modifyType,
  15030. mModule->TypeToString(mResultFieldInstance->mOwner).c_str(), mResultFieldInstance->GetFieldDef()->mName.c_str()), refNode);
  15031. }
  15032. else if (mResultFieldInstance->GetFieldDef()->mIsReadOnly)
  15033. {
  15034. error = _Fail(StrFormat("Cannot %s readonly field '%s.%s' within method '%s'", modifyType,
  15035. mModule->TypeToString(mResultFieldInstance->mOwner).c_str(), mResultFieldInstance->GetFieldDef()->mName.c_str(),
  15036. mModule->MethodToString(mModule->mCurMethodInstance).c_str()), refNode);
  15037. }
  15038. else if (auto propertyDeclaration = BfNodeDynCast<BfPropertyDeclaration>(mResultFieldInstance->GetFieldDef()->mFieldDeclaration))
  15039. {
  15040. String propNam;
  15041. if (propertyDeclaration->mNameNode != NULL)
  15042. propertyDeclaration->mNameNode->ToString(propNam);
  15043. error = _Fail(StrFormat("Cannot %s auto-implemented property '%s.%s' without set accessor", modifyType,
  15044. mModule->TypeToString(mResultFieldInstance->mOwner).c_str(), propNam.c_str()), refNode);
  15045. }
  15046. else
  15047. {
  15048. error = _Fail(StrFormat("Cannot %s field '%s.%s' within struct method '%s'. Consider adding 'mut' specifier to this method.", modifyType,
  15049. mModule->TypeToString(mResultFieldInstance->mOwner).c_str(), mResultFieldInstance->GetFieldDef()->mName.c_str(),
  15050. mModule->MethodToString(mModule->mCurMethodInstance).c_str()), refNode);
  15051. }
  15052. return false;
  15053. }
  15054. }
  15055. else if (localVar->IsParam())
  15056. {
  15057. if (!mModule->mCurMethodInstance->IsMixin())
  15058. {
  15059. if (mModule->mCurMethodState->mMixinState != NULL)
  15060. error = _Fail(StrFormat("Cannot %s mixin parameter '%s'", modifyType,
  15061. localVar->mName.c_str(), mModule->MethodToString(mModule->mCurMethodInstance).c_str()), refNode);
  15062. else if ((localVar->mResolvedType->IsGenericParam()) && (onlyNeedsMut))
  15063. error = _Fail(StrFormat("Cannot %s parameter '%s'. Consider adding 'mut' or 'ref' specifier to parameter or copying to a local variable.", modifyType,
  15064. localVar->mName.c_str(), mModule->MethodToString(mModule->mCurMethodInstance).c_str()), refNode);
  15065. else
  15066. error = _Fail(StrFormat("Cannot %s parameter '%s'. Consider adding 'ref' specifier to parameter or copying to a local variable.", modifyType,
  15067. localVar->mName.c_str(), mModule->MethodToString(mModule->mCurMethodInstance).c_str()), refNode);
  15068. return false;
  15069. }
  15070. }
  15071. else
  15072. {
  15073. if ((mResultLocalVarField != 0) && (!localVar->mIsReadOnly))
  15074. {
  15075. auto typeInst = localVar->mResolvedType->ToTypeInstance();
  15076. int dataIdx = mResultLocalVarField - 1;
  15077. if (typeInst != NULL)
  15078. {
  15079. for (auto& field : typeInst->mFieldInstances)
  15080. {
  15081. if (field.mDataIdx == dataIdx)
  15082. {
  15083. error = _Fail(StrFormat("Cannot %s readonly field '%s.%s'.", modifyType,
  15084. mModule->TypeToString(typeInst).c_str(),
  15085. field.GetFieldDef()->mName.c_str()), refNode);
  15086. break;
  15087. }
  15088. }
  15089. }
  15090. }
  15091. if (error == NULL)
  15092. {
  15093. error = _Fail(StrFormat("Cannot %s read-only local variable '%s'.", modifyType,
  15094. localVar->mName.c_str()), refNode);
  15095. }
  15096. return false;
  15097. }
  15098. }
  15099. else
  15100. {
  15101. // When we are capturing, we need to note that we require capturing by reference here
  15102. localVar->mWrittenToId = mModule->mCurMethodState->GetRootMethodState()->mCurAccessId++;
  15103. }
  15104. }
  15105. if ((mResultFieldInstance != NULL) && (mResultFieldInstance->GetFieldDef()->mIsReadOnly) && (!canModify))
  15106. {
  15107. auto error = _Fail(StrFormat("Cannot %s static readonly field '%s.%s' within method '%s'", modifyType,
  15108. mModule->TypeToString(mResultFieldInstance->mOwner).c_str(), mResultFieldInstance->GetFieldDef()->mName.c_str(),
  15109. mModule->MethodToString(mModule->mCurMethodInstance).c_str()), refNode);
  15110. return false;
  15111. }
  15112. return mModule->CheckModifyValue(typedVal, refNode, modifyType);
  15113. }
  15114. void BfExprEvaluator::Visit(BfConditionalExpression* condExpr)
  15115. {
  15116. static int sCallCount = 0;
  15117. sCallCount++;
  15118. auto condResult = mModule->CreateValueFromExpression(condExpr->mConditionExpression, mModule->GetPrimitiveType(BfTypeCode_Boolean), (BfEvalExprFlags)(mBfEvalExprFlags & BfEvalExprFlags_InheritFlags));
  15119. if (!condResult)
  15120. return;
  15121. if (condExpr->mTrueExpression == NULL)
  15122. {
  15123. mModule->AssertErrorState();
  15124. return;
  15125. }
  15126. if (condExpr->mFalseExpression == NULL)
  15127. {
  15128. mModule->CreateValueFromExpression(condExpr->mTrueExpression, mExpectingType, BfEvalExprFlags_NoCast);
  15129. mModule->AssertErrorState();
  15130. return;
  15131. }
  15132. bool isConstBranch = false;
  15133. bool constResult = false;
  15134. bool constResultUndef = false;
  15135. if (condResult.mValue.IsConst())
  15136. {
  15137. auto constValue = mModule->mBfIRBuilder->GetConstant(condResult.mValue);
  15138. if (constValue->mTypeCode == BfTypeCode_Boolean)
  15139. {
  15140. isConstBranch = true;
  15141. constResult = constValue->mBool;
  15142. }
  15143. else if (constValue->mConstType == BfConstType_Undef)
  15144. {
  15145. isConstBranch = true;
  15146. constResultUndef = true;
  15147. }
  15148. }
  15149. if (isConstBranch)
  15150. {
  15151. BfExpression* actualExpr = (constResult) ? condExpr->mTrueExpression : condExpr->mFalseExpression;
  15152. BfExpression* ignoredExpr = (constResult) ? condExpr->mFalseExpression : condExpr->mTrueExpression;
  15153. BfTypedValue actualValue = mModule->CreateValueFromExpression(actualExpr, mExpectingType, (BfEvalExprFlags)((mBfEvalExprFlags & BfEvalExprFlags_InheritFlags) | BfEvalExprFlags_NoCast));
  15154. BfTypedValue ignoredValue;
  15155. //
  15156. {
  15157. auto curBlock = mModule->mBfIRBuilder->GetInsertBlock();
  15158. SetAndRestoreValue<bool> ignoreWrites(mModule->mBfIRBuilder->mIgnoreWrites, true);
  15159. ignoredValue = mModule->CreateValueFromExpression(ignoredExpr, mExpectingType, (BfEvalExprFlags)((mBfEvalExprFlags & BfEvalExprFlags_InheritFlags) | BfEvalExprFlags_NoCast));
  15160. mModule->mBfIRBuilder->SetInsertPoint(curBlock);
  15161. }
  15162. if (!actualValue)
  15163. return;
  15164. if ((ignoredValue) && (ignoredValue.mType != actualValue.mType))
  15165. {
  15166. // Cast to more specific 'ignored' type if applicable
  15167. if (mModule->CanCast(actualValue, ignoredValue.mType))
  15168. {
  15169. actualValue = mModule->Cast(actualExpr, actualValue, ignoredValue.mType);
  15170. }
  15171. else if (!mModule->CanCast(ignoredValue, actualValue.mType))
  15172. {
  15173. mModule->Fail(StrFormat("Type of conditional expression cannot be determined because there is no implicit conversion between '%s' and '%s'",
  15174. mModule->TypeToString(actualValue.mType).c_str(), mModule->TypeToString(ignoredValue.mType).c_str()), condExpr);
  15175. }
  15176. }
  15177. mResult = actualValue;
  15178. if (constResultUndef)
  15179. mResult = mModule->GetDefaultTypedValue(mResult.mType, false, BfDefaultValueKind_Undef);
  15180. return;
  15181. }
  15182. auto trueBB = mModule->mBfIRBuilder->CreateBlock("cond.then");
  15183. auto falseBB = mModule->mBfIRBuilder->CreateBlock("cond.else");
  15184. auto endBB = mModule->mBfIRBuilder->CreateBlock("cond.end");
  15185. auto contBB = mModule->mBfIRBuilder->CreateBlock("cond.cont");
  15186. mModule->mBfIRBuilder->CreateCondBr(condResult.mValue, trueBB, falseBB);
  15187. SetAndRestoreValue<bool> prevInCondBlock(mModule->mCurMethodState->mCurScope->mInnerIsConditional, true);
  15188. mModule->AddBasicBlock(trueBB);
  15189. auto trueValue = mModule->CreateValueFromExpression(condExpr->mTrueExpression, mExpectingType, (BfEvalExprFlags)((mBfEvalExprFlags & BfEvalExprFlags_InheritFlags) | BfEvalExprFlags_NoCast | BfEvalExprFlags_CreateConditionalScope));
  15190. if ((mExpectingType != NULL) && (trueValue) && (trueValue.mType != mExpectingType))
  15191. {
  15192. // In some cases like typed primitives - we CAN individually cast each value which it's a constant still, but not after the merging
  15193. // IE: Color c = isOver ? 0xFF000000 : 0xFFFFFFFF;
  15194. // Otherwise the resulting value would just be 'int' which cannot implicitly convert to Color, but each of those ints can be
  15195. // a uint32 if converted separately
  15196. auto checkTrueValue = mModule->Cast(condExpr->mTrueExpression, trueValue, mExpectingType, BfCastFlags_SilentFail);
  15197. if (checkTrueValue)
  15198. trueValue = checkTrueValue;
  15199. mModule->FixIntUnknown(trueValue);
  15200. }
  15201. auto trueBlockPos = mModule->mBfIRBuilder->GetInsertBlock();
  15202. mModule->AddBasicBlock(falseBB);
  15203. auto falseValue = mModule->CreateValueFromExpression(condExpr->mFalseExpression, mExpectingType, (BfEvalExprFlags)((mBfEvalExprFlags & BfEvalExprFlags_InheritFlags) | BfEvalExprFlags_NoCast | BfEvalExprFlags_CreateConditionalScope));
  15204. auto falseBlockPos = mModule->mBfIRBuilder->GetInsertBlock();
  15205. if ((mExpectingType != NULL) && (falseValue) && (falseValue.mType != mExpectingType))
  15206. {
  15207. auto checkFalseValue = mModule->Cast(condExpr->mFalseExpression, falseValue, mExpectingType, BfCastFlags_SilentFail);
  15208. if (checkFalseValue)
  15209. falseValue = checkFalseValue;
  15210. mModule->FixIntUnknown(falseValue);
  15211. }
  15212. prevInCondBlock.Restore();
  15213. bool isValid = trueValue && falseValue;
  15214. if (isValid)
  15215. {
  15216. BfTypedValue falseToTrue;
  15217. {
  15218. SetAndRestoreValue<bool> prevIgnoreError(mModule->mIgnoreErrors, true);
  15219. mModule->mBfIRBuilder->SetInsertPoint(falseBlockPos);
  15220. falseToTrue = mModule->Cast(condExpr->mFalseExpression, falseValue, trueValue.mType);
  15221. }
  15222. if (falseToTrue)
  15223. {
  15224. falseValue = falseToTrue;
  15225. }
  15226. else
  15227. {
  15228. BfTypedValue trueToFalse;
  15229. {
  15230. SetAndRestoreValue<bool> prevIgnoreError(mModule->mIgnoreErrors, true);
  15231. mModule->mBfIRBuilder->SetInsertPoint(trueBlockPos);
  15232. trueToFalse = mModule->Cast(condExpr->mTrueExpression, trueValue, falseValue.mType);
  15233. }
  15234. if (!trueToFalse)
  15235. {
  15236. mModule->Fail(StrFormat("Type of conditional expression cannot be determined because there is no implicit conversion between '%s' and '%s'",
  15237. mModule->TypeToString(trueValue.mType).c_str(), mModule->TypeToString(falseValue.mType).c_str()), condExpr);
  15238. //return;
  15239. isValid = false;
  15240. }
  15241. else
  15242. trueValue = trueToFalse;
  15243. }
  15244. }
  15245. mModule->mBfIRBuilder->SetInsertPoint(trueBlockPos);
  15246. if (isValid)
  15247. trueValue = mModule->LoadValue(trueValue);
  15248. mModule->mBfIRBuilder->CreateBr(endBB);
  15249. mModule->mBfIRBuilder->SetInsertPoint(falseBlockPos);
  15250. if (isValid)
  15251. falseValue = mModule->LoadValue(falseValue);
  15252. mModule->mBfIRBuilder->CreateBr(endBB);
  15253. mModule->AddBasicBlock(endBB, false);
  15254. if (!isValid)
  15255. return;
  15256. mModule->mBfIRBuilder->SetInsertPoint(endBB);
  15257. BfIRValue phi;
  15258. if (!trueValue.mType->IsValuelessType())
  15259. {
  15260. if (trueValue.mType->IsVar())
  15261. {
  15262. phi = mModule->mBfIRBuilder->GetFakeVal();
  15263. }
  15264. else
  15265. {
  15266. phi = mModule->mBfIRBuilder->CreatePhi(mModule->mBfIRBuilder->MapType(trueValue.mType), 2);
  15267. mModule->mBfIRBuilder->AddPhiIncoming(phi, trueValue.mValue, trueBlockPos);
  15268. mModule->mBfIRBuilder->AddPhiIncoming(phi, falseValue.mValue, falseBlockPos);
  15269. }
  15270. }
  15271. mModule->mBfIRBuilder->CreateBr(contBB);
  15272. mModule->AddBasicBlock(contBB);
  15273. mResult = BfTypedValue(phi, trueValue.mType);
  15274. }
  15275. void BfExprEvaluator::PopulateDeferrredTupleAssignData(BfTupleExpression* tupleExpr, DeferredTupleAssignData& deferredTupleAssignData)
  15276. {
  15277. BfTypeVector fieldTypes;
  15278. Array<String> fieldNames;
  15279. // We need to evaluate each LHS tuple component in a separate BfExprEvaluator because each one
  15280. // could be a property and the 'mPropDef' target info is tied to a single evaluator
  15281. for (int valueIdx = 0; valueIdx < (int)tupleExpr->mValues.size(); valueIdx++)
  15282. {
  15283. DeferredTupleAssignData::Entry entry;
  15284. entry.mExprEvaluator = NULL;
  15285. entry.mInnerTuple = NULL;
  15286. BfExpression* valueExpr = tupleExpr->mValues[valueIdx];
  15287. entry.mExpr = valueExpr;
  15288. BfType* fieldType = NULL;
  15289. BfType* resultType = NULL;
  15290. if (auto innerTupleExpr = BfNodeDynCast<BfTupleExpression>(valueExpr))
  15291. {
  15292. entry.mInnerTuple = new DeferredTupleAssignData();
  15293. PopulateDeferrredTupleAssignData(innerTupleExpr, *entry.mInnerTuple);
  15294. resultType = entry.mInnerTuple->mTupleType;
  15295. }
  15296. else
  15297. {
  15298. BfExprEvaluator* exprEvaluator = new BfExprEvaluator(mModule);
  15299. entry.mExprEvaluator = exprEvaluator;
  15300. if (valueExpr->IsA<BfUninitializedExpression>())
  15301. {
  15302. resultType = mModule->GetPrimitiveType(BfTypeCode_None);
  15303. }
  15304. if (auto varDecl = BfNodeDynCast<BfVariableDeclaration>(valueExpr))
  15305. {
  15306. if ((varDecl->mTypeRef->IsA<BfLetTypeReference>()) || (varDecl->mTypeRef->IsA<BfVarTypeReference>()))
  15307. {
  15308. resultType = mModule->GetPrimitiveType(BfTypeCode_Var);
  15309. }
  15310. else
  15311. {
  15312. resultType = ResolveTypeRef(varDecl->mTypeRef);
  15313. if (resultType == NULL)
  15314. resultType = mModule->GetPrimitiveType(BfTypeCode_Var);
  15315. }
  15316. }
  15317. if (resultType == NULL)
  15318. {
  15319. exprEvaluator->VisitChild(valueExpr);
  15320. if ((!exprEvaluator->mResult) && (exprEvaluator->mPropDef == NULL))
  15321. exprEvaluator->mResult = mModule->GetDefaultTypedValue(mModule->GetPrimitiveType(BfTypeCode_None));
  15322. resultType = exprEvaluator->mResult.mType;
  15323. }
  15324. if ((resultType == NULL) && (exprEvaluator->mPropDef != NULL) && (exprEvaluator->mPropTarget.mType != NULL))
  15325. {
  15326. auto propTypeInst = exprEvaluator->mPropTarget.mType->ToTypeInstance();
  15327. if ((propTypeInst == NULL) && (exprEvaluator->mPropTarget.mType->IsPointer()))
  15328. {
  15329. BfPointerType* pointerType = (BfPointerType*)exprEvaluator->mPropTarget.mType;
  15330. propTypeInst = pointerType->mElementType->ToTypeInstance();
  15331. }
  15332. auto setMethod = GetPropertyMethodDef(exprEvaluator->mPropDef, BfMethodType_PropertySetter, mPropCheckedKind, mPropTarget);
  15333. if (setMethod != NULL)
  15334. {
  15335. auto methodInstance = mModule->GetMethodInstance(propTypeInst, setMethod, BfTypeVector());
  15336. resultType = methodInstance.mMethodInstance->GetParamType(0);
  15337. }
  15338. else
  15339. {
  15340. auto getMethod = GetPropertyMethodDef(exprEvaluator->mPropDef, BfMethodType_PropertyGetter, mPropCheckedKind, mPropTarget);
  15341. if (getMethod != NULL)
  15342. {
  15343. auto methodInstance = mModule->GetMethodInstance(propTypeInst, getMethod, BfTypeVector());
  15344. auto retType = methodInstance.mMethodInstance->mReturnType;
  15345. if (retType->IsRef())
  15346. resultType = retType->GetUnderlyingType();
  15347. }
  15348. }
  15349. }
  15350. }
  15351. if (resultType == NULL)
  15352. resultType = mModule->GetPrimitiveType(BfTypeCode_None);
  15353. deferredTupleAssignData.mChildren.push_back(entry);
  15354. fieldTypes.push_back(resultType);
  15355. }
  15356. for (BfTupleNameNode* requestedName : tupleExpr->mNames)
  15357. {
  15358. if (requestedName == NULL)
  15359. fieldNames.push_back("");
  15360. else
  15361. fieldNames.push_back(requestedName->mNameNode->ToString());
  15362. }
  15363. BfTypeInstance* tupleType = mModule->CreateTupleType(fieldTypes, fieldNames, true);
  15364. deferredTupleAssignData.mTupleType = tupleType;
  15365. }
  15366. void BfExprEvaluator::AssignDeferrredTupleAssignData(BfAssignmentExpression* assignExpr, DeferredTupleAssignData& deferredTupleAssignData, BfTypedValue rightValue)
  15367. {
  15368. BF_ASSERT(rightValue.mType->IsTuple());
  15369. auto tupleType = (BfTypeInstance*)rightValue.mType;
  15370. for (int valueIdx = 0; valueIdx < (int)deferredTupleAssignData.mChildren.size(); valueIdx++)
  15371. {
  15372. auto& child = deferredTupleAssignData.mChildren[valueIdx];
  15373. BfFieldInstance* fieldInstance = &tupleType->mFieldInstances[valueIdx];
  15374. BfTypedValue elementValue;
  15375. if (fieldInstance->mDataIdx >= 0)
  15376. {
  15377. auto extractedValue = mModule->mBfIRBuilder->CreateExtractValue(rightValue.mValue, fieldInstance->mDataIdx);
  15378. elementValue = BfTypedValue(extractedValue, fieldInstance->GetResolvedType());
  15379. if (child.mInnerTuple != NULL)
  15380. {
  15381. AssignDeferrredTupleAssignData(assignExpr, *child.mInnerTuple, elementValue);
  15382. delete child.mInnerTuple;
  15383. child.mInnerTuple = NULL;
  15384. }
  15385. else
  15386. {
  15387. if (child.mExprEvaluator->HasResult())
  15388. {
  15389. child.mExprEvaluator->mBfEvalExprFlags = (BfEvalExprFlags)(child.mExprEvaluator->mBfEvalExprFlags | BfEvalExprFlags_NoAutoComplete);
  15390. child.mExprEvaluator->PerformAssignment(assignExpr, true, elementValue);
  15391. }
  15392. }
  15393. }
  15394. if (auto varDecl = BfNodeDynCast<BfVariableDeclaration>(child.mExpr))
  15395. {
  15396. if (!elementValue)
  15397. elementValue = mModule->GetDefaultTypedValue(fieldInstance->GetResolvedType());
  15398. mModule->HandleVariableDeclaration(varDecl, elementValue);
  15399. }
  15400. }
  15401. }
  15402. void BfExprEvaluator::DoTupleAssignment(BfAssignmentExpression* assignExpr)
  15403. {
  15404. auto tupleExpr = BfNodeDynCast<BfTupleExpression>(assignExpr->mLeft);
  15405. DeferredTupleAssignData deferredTupleAssignData;
  15406. PopulateDeferrredTupleAssignData(tupleExpr, deferredTupleAssignData);
  15407. BfTypeInstance* tupleType = deferredTupleAssignData.mTupleType;
  15408. BfTypedValue rightValue;
  15409. if (assignExpr->mRight != NULL)
  15410. {
  15411. rightValue = mModule->CreateValueFromExpression(assignExpr->mRight, tupleType);
  15412. }
  15413. if (!rightValue)
  15414. {
  15415. tupleType = mModule->SantizeTupleType(tupleType);
  15416. rightValue = mModule->GetDefaultTypedValue(tupleType);
  15417. }
  15418. rightValue = mModule->LoadValue(rightValue);
  15419. AssignDeferrredTupleAssignData(assignExpr, deferredTupleAssignData, rightValue);
  15420. mResult = rightValue;
  15421. }
  15422. void BfExprEvaluator::PerformAssignment(BfAssignmentExpression* assignExpr, bool evaluatedLeft, BfTypedValue rightValue, BfTypedValue* outCascadeValue)
  15423. {
  15424. auto binaryOp = BfAssignOpToBinaryOp(assignExpr->mOp);
  15425. BfExpression* targetNode = assignExpr->mLeft;
  15426. if ((BfNodeIsA<BfMixinExpression>(targetNode)) && (!mModule->mCurMethodInstance->mIsUnspecialized))
  15427. {
  15428. // If we have a "mixin = <X>" but there's no mixin target then ignore the assignment
  15429. int mixinVar = GetMixinVariable();
  15430. if (mixinVar == -1)
  15431. {
  15432. mResult = mModule->GetDefaultTypedValue(mModule->GetPrimitiveType(BfTypeCode_None));
  15433. return;
  15434. }
  15435. }
  15436. BfAutoComplete* autoComplete = GetAutoComplete();
  15437. bool deferredFixits = false;
  15438. if ((autoComplete != NULL) && (autoComplete->mResolveType == BfResolveType_GetFixits))
  15439. {
  15440. SetAndRestoreValue<bool> ignoreFixits(autoComplete->mIgnoreFixits, true);
  15441. VisitChild(targetNode);
  15442. deferredFixits = true;
  15443. }
  15444. else if (!evaluatedLeft)
  15445. {
  15446. if (auto memberReferenceExpr = BfNodeDynCast<BfMemberReferenceExpression>(targetNode))
  15447. {
  15448. DoMemberReference(memberReferenceExpr, outCascadeValue);
  15449. }
  15450. else
  15451. VisitChild(targetNode);
  15452. }
  15453. if ((!mResult) && (mPropDef == NULL))
  15454. {
  15455. if (assignExpr->mRight != NULL)
  15456. {
  15457. auto result = mModule->CreateValueFromExpression(assignExpr->mRight);
  15458. if (deferredFixits)
  15459. {
  15460. SetAndRestoreValue<bool> ignoreErrors(mModule->mIgnoreErrors, true);
  15461. mExpectingType = result.mType;
  15462. VisitChild(targetNode);
  15463. mResult = BfTypedValue();
  15464. }
  15465. }
  15466. return;
  15467. }
  15468. ResolveGenericType();
  15469. auto ptr = mResult;
  15470. mResult = BfTypedValue();
  15471. if (mPropDef == NULL)
  15472. {
  15473. if (!CheckModifyResult(ptr, assignExpr->mOpToken, "assign to", false, false, true))
  15474. {
  15475. if (assignExpr->mRight != NULL)
  15476. mModule->CreateValueFromExpression(assignExpr->mRight, ptr.mType, BfEvalExprFlags_NoCast);
  15477. return;
  15478. }
  15479. }
  15480. if (mPropDef != NULL)
  15481. {
  15482. bool hasLeftVal = false;
  15483. auto propDef = mPropDef;
  15484. auto propTarget = mPropTarget;
  15485. auto setMethod = GetPropertyMethodDef(mPropDef, BfMethodType_PropertySetter, mPropCheckedKind, mPropTarget);
  15486. if (setMethod == NULL)
  15487. {
  15488. // Allow for a ref return on the getter to be used if a setter is not available
  15489. GetResult();
  15490. if ((mResult) && (mResult.mKind == BfTypedValueKind_Addr))
  15491. {
  15492. ptr = mResult;
  15493. mResult = BfTypedValue();
  15494. hasLeftVal = true;
  15495. }
  15496. else
  15497. {
  15498. mModule->Fail("Property has no setter", mPropSrc);
  15499. if (assignExpr->mRight != NULL)
  15500. mModule->CreateValueFromExpression(assignExpr->mRight, ptr.mType, BfEvalExprFlags_NoCast);
  15501. return;
  15502. }
  15503. }
  15504. if (!hasLeftVal)
  15505. {
  15506. auto methodInstance = GetPropertyMethodInstance(setMethod);
  15507. if (methodInstance.mMethodInstance == NULL)
  15508. return;
  15509. //BF_ASSERT(methodInstance.mMethodInstance->mMethodDef == setMethod);
  15510. CheckPropFail(setMethod, methodInstance.mMethodInstance, (mPropGetMethodFlags & BfGetMethodInstanceFlag_Friend) == 0);
  15511. auto autoComplete = GetAutoComplete();
  15512. if ((autoComplete != NULL) && (autoComplete->IsAutocompleteNode(mPropSrc)) && (autoComplete->mResolveType == BfResolveType_GetResultString))
  15513. {
  15514. autoComplete->mResultString = ":";
  15515. autoComplete->mResultString += mModule->TypeToString(methodInstance.mMethodInstance->GetParamType(0));
  15516. autoComplete->mResultString += " ";
  15517. autoComplete->mResultString += mModule->TypeToString(methodInstance.mMethodInstance->GetOwner());
  15518. autoComplete->mResultString += ".";
  15519. autoComplete->mResultString += mPropDef->mName;
  15520. }
  15521. BfTypedValue convVal;
  15522. if (binaryOp != BfBinaryOp_None)
  15523. {
  15524. PerformBinaryOperation(assignExpr->mLeft, assignExpr->mRight, binaryOp, assignExpr->mOpToken, BfBinOpFlag_ForceLeftType);
  15525. if (!mResult)
  15526. return;
  15527. convVal = mResult;
  15528. mResult = BfTypedValue();
  15529. if (!convVal)
  15530. return;
  15531. }
  15532. else
  15533. {
  15534. auto wantType = methodInstance.mMethodInstance->GetParamType(methodInstance.mMethodInstance->GetParamCount() - 1);
  15535. if (rightValue)
  15536. {
  15537. convVal = mModule->Cast(assignExpr->mRight, rightValue, wantType);
  15538. }
  15539. else
  15540. {
  15541. if (assignExpr->mRight == NULL)
  15542. {
  15543. mModule->AssertErrorState();
  15544. return;
  15545. }
  15546. convVal = mModule->CreateValueFromExpression(assignExpr->mRight, wantType, (BfEvalExprFlags)(BfEvalExprFlags_AllowSplat | BfEvalExprFlags_PendingPropSet));
  15547. }
  15548. if (!convVal)
  15549. {
  15550. mPropDef = NULL;
  15551. return;
  15552. }
  15553. }
  15554. if (mPropSrc != NULL)
  15555. mModule->UpdateExprSrcPos(mPropSrc);
  15556. SizedArray<BfIRValue, 4> args;
  15557. if (!setMethod->mIsStatic)
  15558. {
  15559. auto owner = methodInstance.mMethodInstance->GetOwner();
  15560. if ((mPropTarget.mType != owner) ||
  15561. ((mPropTarget.mValue.IsFake()) && (!mOrigPropTarget.mValue.IsFake())))
  15562. {
  15563. if ((mPropDefBypassVirtual) || (!mPropTarget.mType->IsInterface()))
  15564. {
  15565. mPropTarget = mModule->Cast(mPropSrc, mOrigPropTarget, owner);
  15566. if (!mPropTarget)
  15567. {
  15568. mModule->Fail("Internal property error", mPropSrc);
  15569. return;
  15570. }
  15571. }
  15572. }
  15573. mModule->EmitObjectAccessCheck(mPropTarget);
  15574. PushThis(mPropSrc, mPropTarget, methodInstance.mMethodInstance, args);
  15575. }
  15576. for (int paramIdx = 0; paramIdx < (int)mIndexerValues.size(); paramIdx++)
  15577. {
  15578. auto refNode = mIndexerValues[paramIdx].mExpression;
  15579. auto wantType = methodInstance.mMethodInstance->GetParamType(paramIdx);
  15580. auto argValue = ResolveArgValue(mIndexerValues[paramIdx], wantType);
  15581. if (refNode == NULL)
  15582. refNode = mPropSrc;
  15583. auto val = mModule->Cast(refNode, argValue, wantType);
  15584. if (!val)
  15585. {
  15586. mPropDef = NULL;
  15587. return;
  15588. }
  15589. PushArg(val, args);
  15590. }
  15591. PushArg(convVal, args);
  15592. if (methodInstance)
  15593. CreateCall(assignExpr, methodInstance.mMethodInstance, methodInstance.mFunc, mPropDefBypassVirtual, args);
  15594. mPropDef = NULL;
  15595. mResult = convVal;
  15596. return;
  15597. }
  15598. }
  15599. auto toType = ptr.mType;
  15600. if (toType->IsRef())
  15601. {
  15602. auto refType = (BfRefType*)toType;
  15603. toType = refType->mElementType;
  15604. }
  15605. if ((autoComplete != NULL) && (assignExpr->mOpToken != NULL) && (toType != NULL))
  15606. autoComplete->CheckEmptyStart(assignExpr->mOpToken, toType);
  15607. BfExpression* rightExpr = assignExpr->mRight;
  15608. if (rightExpr == NULL)
  15609. {
  15610. mModule->AssertErrorState();
  15611. return;
  15612. }
  15613. bool alreadyWritten = false;
  15614. BfTypedValue convVal;
  15615. if (binaryOp != BfBinaryOp_None)
  15616. {
  15617. CheckResultForReading(ptr);
  15618. BfTypedValue leftValue = ptr;
  15619. bool deferBinop = false;
  15620. BfDeferEvalChecker deferEvalChecker;
  15621. deferEvalChecker.mDeferLiterals = false;
  15622. assignExpr->mRight->Accept(&deferEvalChecker);
  15623. if (deferEvalChecker.mNeedsDeferEval)
  15624. deferBinop = true;
  15625. if (!deferBinop)
  15626. {
  15627. auto expectedType = ptr.mType;
  15628. if ((binaryOp == BfBinaryOp_LeftShift) || (binaryOp == BfBinaryOp_RightShift))
  15629. expectedType = mModule->GetPrimitiveType(BfTypeCode_IntPtr);
  15630. if ((!rightValue) && (assignExpr->mRight != NULL))
  15631. {
  15632. rightValue = mModule->CreateValueFromExpression(assignExpr->mRight, expectedType, (BfEvalExprFlags)(BfEvalExprFlags_AllowSplat | BfEvalExprFlags_NoCast));
  15633. }
  15634. }
  15635. bool handled = false;
  15636. BfResolvedArgs argValues;
  15637. if ((rightValue) || (deferBinop))
  15638. {
  15639. auto checkTypeInst = leftValue.mType->ToTypeInstance();
  15640. while (checkTypeInst != NULL)
  15641. {
  15642. for (auto operatorDef : checkTypeInst->mTypeDef->mOperators)
  15643. {
  15644. if (operatorDef->mOperatorDeclaration->mAssignOp != assignExpr->mOp)
  15645. continue;
  15646. auto methodInst = mModule->GetRawMethodInstanceAtIdx(checkTypeInst, operatorDef->mIdx);
  15647. if (methodInst->GetParamCount() != 1)
  15648. continue;
  15649. auto paramType = methodInst->GetParamType(0);
  15650. if (deferBinop)
  15651. {
  15652. if (argValues.mArguments == NULL)
  15653. {
  15654. SizedArray<BfExpression*, 2> argExprs;
  15655. argExprs.push_back(assignExpr->mRight);
  15656. BfSizedArray<BfExpression*> sizedArgExprs(argExprs);
  15657. argValues.Init(&sizedArgExprs);
  15658. ResolveArgValues(argValues, BfResolveArgsFlag_DeferParamEval);
  15659. }
  15660. rightValue = ResolveArgValue(argValues.mResolvedArgs[0], paramType);
  15661. if (!rightValue)
  15662. continue;
  15663. }
  15664. else
  15665. {
  15666. if (!mModule->CanCast(rightValue, paramType))
  15667. continue;
  15668. }
  15669. mModule->SetElementType(assignExpr->mOpToken, BfSourceElementType_Method);
  15670. if ((autoComplete != NULL) && (autoComplete->IsAutocompleteNode(assignExpr->mOpToken)))
  15671. {
  15672. if (operatorDef->mOperatorDeclaration != NULL)
  15673. autoComplete->SetDefinitionLocation(operatorDef->mOperatorDeclaration->mOpTypeToken);
  15674. }
  15675. auto moduleMethodInstance = mModule->GetMethodInstance(checkTypeInst, operatorDef, BfTypeVector());
  15676. BfExprEvaluator exprEvaluator(mModule);
  15677. SizedArray<BfIRValue, 1> args;
  15678. exprEvaluator.PushThis(assignExpr->mLeft, leftValue, moduleMethodInstance.mMethodInstance, args);
  15679. exprEvaluator.PushArg(rightValue, args);
  15680. exprEvaluator.CreateCall(assignExpr, moduleMethodInstance.mMethodInstance, moduleMethodInstance.mFunc, false, args);
  15681. convVal = leftValue;
  15682. handled = true;
  15683. break;
  15684. }
  15685. if (handled)
  15686. break;
  15687. checkTypeInst = mModule->GetBaseType(checkTypeInst);
  15688. }
  15689. if (!handled)
  15690. {
  15691. auto flags = BfBinOpFlag_ForceLeftType;
  15692. if (deferBinop)
  15693. flags = (BfBinOpFlags)(flags | BfBinOpFlag_DeferRight);
  15694. leftValue = mModule->LoadValue(leftValue);
  15695. PerformBinaryOperation(assignExpr->mLeft, assignExpr->mRight, binaryOp, assignExpr->mOpToken, flags, leftValue, rightValue);
  15696. }
  15697. }
  15698. if (!handled)
  15699. {
  15700. convVal = mResult;
  15701. mResult = BfTypedValue();
  15702. }
  15703. if (!convVal)
  15704. return;
  15705. }
  15706. else
  15707. {
  15708. convVal = rightValue;
  15709. if (!convVal)
  15710. {
  15711. if (auto uninitExpr = BfNodeDynCast<BfUninitializedExpression>(rightExpr))
  15712. {
  15713. if (mResultLocalVar != NULL)
  15714. {
  15715. MarkResultAssigned();
  15716. return;
  15717. }
  15718. }
  15719. // In the cases like "structVal = GetVal()", the allowDirectStructRetWrite optimization allows us to pass the
  15720. // address of structVal into the sret. We only allow that if structVal is a local, because if it's globally
  15721. // visible then we could see the results of a partially-modified structVal
  15722. //bool allowDirectStructRetWrite = mResultLocalVarIdx != -1;
  15723. // ALTHOUGH- we can only allow this optimization if we can be sure the local value is not aliased- we could
  15724. // have the backend ensure that this local value never gets its address taken.
  15725. bool allowDirectStructWrite = false;
  15726. BfExprEvaluator exprEvaluator(mModule);
  15727. exprEvaluator.mExpectingType = toType;
  15728. if (allowDirectStructWrite)
  15729. exprEvaluator.mReceivingValue = &ptr;
  15730. exprEvaluator.Evaluate(rightExpr, false, false, true);
  15731. exprEvaluator.CheckResultForReading(exprEvaluator.mResult);
  15732. convVal = exprEvaluator.GetResult();
  15733. mModule->FixIntUnknown(convVal);
  15734. alreadyWritten = (allowDirectStructWrite) && (exprEvaluator.mReceivingValue == NULL);
  15735. if (!convVal)
  15736. convVal = mModule->GetDefaultTypedValue(toType);
  15737. // Did we use mReceivingValue as a mixin result?
  15738. if ((convVal.mValue) && (convVal.mValue == ptr.mValue))
  15739. {
  15740. mResult = convVal;
  15741. return;
  15742. }
  15743. }
  15744. }
  15745. BF_ASSERT(convVal);
  15746. if ((convVal) && (convVal.mType->IsNull()) && (ptr.mType->IsNullable()))
  15747. {
  15748. // Allow this to pass through so we can catch it in the memset later in this function
  15749. }
  15750. else
  15751. {
  15752. if (!convVal.mType->IsComposite())
  15753. convVal = mModule->LoadValue(convVal);
  15754. convVal = mModule->Cast(rightExpr, convVal, toType);
  15755. if (!convVal)
  15756. return;
  15757. convVal = mModule->LoadValue(convVal);
  15758. }
  15759. if (ptr.mType->IsVar())
  15760. {
  15761. mResult = ptr;
  15762. return;
  15763. }
  15764. if (convVal.mValue)
  15765. {
  15766. if ((ptr.mType->IsStruct()) && (!ptr.mType->IsValuelessType()) && (convVal.mValue.IsConst()))
  15767. {
  15768. auto constant = mModule->mBfIRBuilder->GetConstant(convVal.mValue);
  15769. if ((constant->mTypeCode == BfTypeCode_NullPtr) || (constant->mConstType == BfConstType_AggZero))
  15770. {
  15771. auto type = ptr.mType;
  15772. mModule->mBfIRBuilder->CreateMemSet(ptr.mValue, mModule->GetConstValue(0, mModule->GetPrimitiveType(BfTypeCode_Int8)),
  15773. mModule->GetConstValue(type->mSize), type->mAlign);
  15774. mResult = ptr;
  15775. MarkResultAssigned();
  15776. return;
  15777. }
  15778. }
  15779. // if (ptr.mType->IsMethodRef())
  15780. // {
  15781. // auto methodRefType = (BfMethodRefType*)ptr.mType;
  15782. // auto methodInstance = methodRefType->mMethodInstance;
  15783. // int implicitParamCount = methodInstance->GetImplicitParamCount();
  15784. // for (int implicitParamIdx = methodInstance->HasThis() ? - 1 : 0; implicitParamIdx < implicitParamCount; implicitParamIdx++)
  15785. // {
  15786. // bool failed = false;
  15787. // auto destPtr = DoImplicitArgCapture(assignExpr, methodRefType->mMethodInstance, implicitParamIdx, failed, BfImplicitParamKind_GenericTypeMember_Addr);
  15788. // auto srcVal = DoImplicitArgCapture(assignExpr, methodRefType->mMethodInstance, implicitParamIdx, failed, BfImplicitParamKind_GenericMethodMember);
  15789. // if ((destPtr) && (srcVal))
  15790. // {
  15791. // srcVal = mModule->AggregateSplat(srcVal);
  15792. // mModule->mBfIRBuilder->CreateStore(srcVal.mValue, destPtr.mValue);
  15793. // }
  15794. // }
  15795. // }
  15796. // else
  15797. {
  15798. mModule->mBfIRBuilder->PopulateType(ptr.mType);
  15799. if (convVal.IsSplat())
  15800. {
  15801. //convVal = mModule->AggregateSplat(convVal);
  15802. mModule->AggregateSplatIntoAddr(convVal, ptr.mValue);
  15803. }
  15804. else
  15805. {
  15806. if (ptr.mType->IsValuelessType())
  15807. {
  15808. mModule->EmitEnsureInstructionAt();
  15809. }
  15810. else if (!alreadyWritten)
  15811. {
  15812. //ptr = mModule->LoadValue(ptr);
  15813. BF_ASSERT(ptr.IsAddr());
  15814. convVal = mModule->LoadValue(convVal);
  15815. auto storeInst = mModule->mBfIRBuilder->CreateAlignedStore(convVal.mValue, ptr.mValue, ptr.mType->mAlign, mIsVolatileReference);
  15816. }
  15817. }
  15818. }
  15819. }
  15820. else
  15821. {
  15822. BF_ASSERT(convVal.mType->IsValuelessType());
  15823. }
  15824. mResult = convVal;
  15825. MarkResultAssigned();
  15826. }
  15827. void BfExprEvaluator::Visit(BfAssignmentExpression* assignExpr)
  15828. {
  15829. if (assignExpr->mLeft->IsA<BfTupleExpression>())
  15830. {
  15831. DoTupleAssignment(assignExpr);
  15832. return;
  15833. }
  15834. BfAutoParentNodeEntry autoParentNodeEntry(mModule, assignExpr);
  15835. BfTypedValue cascadeValue;
  15836. PerformAssignment(assignExpr, false, BfTypedValue(), &cascadeValue);
  15837. if (cascadeValue)
  15838. mResult = cascadeValue;
  15839. }
  15840. void BfExprEvaluator::Visit(BfParenthesizedExpression* parenExpr)
  15841. {
  15842. VisitChild(parenExpr->mExpression);
  15843. MakeResultAsValue();
  15844. }
  15845. void BfExprEvaluator::InitializedSizedArray(BfSizedArrayType* arrayType, BfTokenNode* openToken, const BfSizedArray<BfExpression*>& valueExprs, const BfSizedArray<BfTokenNode*>& commas, BfTokenNode* closeToken, BfTypedValue* receivingValue)
  15846. {
  15847. struct InitValue
  15848. {
  15849. BfTypedValue mValue;
  15850. bool mIsUninitialized;
  15851. bool mIsDefaultInitializer;
  15852. bool mIsDeferred;
  15853. InitValue()
  15854. {
  15855. mIsUninitialized = false;
  15856. mIsDefaultInitializer = false;
  15857. mIsDeferred = false;
  15858. }
  15859. };
  15860. SizedArray<InitValue, 8> values;
  15861. {
  15862. //bool hasFailed = false;
  15863. HashSet<int> failedAt;
  15864. bool isAllConst = true;
  15865. //bool endUninitialzied = false;
  15866. int depth = 0;
  15867. std::function<void(BfSizedArrayType*, BfTokenNode* openToken, const BfSizedArray<BfExpression*>&, const BfSizedArray<BfTokenNode*>&, BfTokenNode*, bool)>
  15868. _GetValues = [&](BfSizedArrayType* checkArrayType, BfTokenNode* openToken, const BfSizedArray<BfExpression*>& valueExprs, const BfSizedArray<BfTokenNode*>& commas, BfTokenNode* closeToken, bool ignore)
  15869. {
  15870. int64 initCountDiff = (int)valueExprs.size() - checkArrayType->mElementCount;
  15871. if ((initCountDiff != 0) && (!valueExprs.IsEmpty()) && (!failedAt.Contains(depth)))
  15872. {
  15873. if (checkArrayType->mElementCount == -1)
  15874. {
  15875. // mModule->Fail("Initializers not supported for unknown-sized arrays", valueExprs[0]);
  15876. // failedAt.Add(depth);
  15877. }
  15878. else if (initCountDiff > 0)
  15879. {
  15880. mModule->Fail(StrFormat("Too many initializers, expected %d fewer", initCountDiff), valueExprs[BF_MAX((int)checkArrayType->mElementCount, 0)]);
  15881. failedAt.Add(depth);
  15882. }
  15883. else
  15884. {
  15885. // If it ends with ", ?) or ",)" then allow unsized
  15886. if (((valueExprs.size() == 0) || (BfNodeDynCast<BfUninitializedExpression>(valueExprs.back()) == NULL)) &&
  15887. ((commas.size() < valueExprs.size()) || (valueExprs.size() == 0)))
  15888. {
  15889. BfAstNode* refNode = closeToken;
  15890. if ((refNode == NULL) && (mModule->mParentNodeEntry != NULL))
  15891. refNode = mModule->mParentNodeEntry->mNode;
  15892. BF_ASSERT(refNode != NULL);
  15893. mModule->Fail(StrFormat("Too few initializer, expected %d more", -initCountDiff), refNode);
  15894. failedAt.Add(depth);
  15895. }
  15896. }
  15897. }
  15898. for (int idx = 0; idx < BF_MAX(checkArrayType->mElementCount, valueExprs.size()); idx++)
  15899. {
  15900. BfTypedValue elementValue;
  15901. bool deferredValue = false;
  15902. BfExpression* expr = NULL;
  15903. if (idx < (int)valueExprs.size())
  15904. {
  15905. expr = valueExprs[idx];
  15906. if (expr == NULL)
  15907. {
  15908. if (idx == 0)
  15909. mModule->FailAfter("Expression expected", openToken);
  15910. else
  15911. mModule->FailAfter("Expression expected", commas[idx - 1]);
  15912. }
  15913. if ((BfNodeDynCastExact<BfUninitializedExpression>(expr) != NULL) && (idx == (int)commas.size()))
  15914. {
  15915. isAllConst = false;
  15916. break;
  15917. }
  15918. if (checkArrayType->mElementType->IsSizedArray())
  15919. {
  15920. if (auto arrayInitExpr = BfNodeDynCast<BfTupleExpression>(expr))
  15921. {
  15922. depth++;
  15923. _GetValues((BfSizedArrayType*)checkArrayType->mElementType, arrayInitExpr->mOpenParen, arrayInitExpr->mValues, arrayInitExpr->mCommas, arrayInitExpr->mCloseParen, ignore);
  15924. depth--;
  15925. continue;
  15926. }
  15927. else if (auto arrayInitExpr = BfNodeDynCast<BfCollectionInitializerExpression>(expr))
  15928. {
  15929. depth++;
  15930. _GetValues((BfSizedArrayType*)checkArrayType->mElementType, arrayInitExpr->mOpenBrace, arrayInitExpr->mValues, arrayInitExpr->mCommas, arrayInitExpr->mCloseBrace, ignore);
  15931. depth--;
  15932. continue;
  15933. }
  15934. else if (auto parenExpr = BfNodeDynCast<BfParenthesizedExpression>(expr))
  15935. {
  15936. depth++;
  15937. SizedArray<BfExpression*, 1> values;
  15938. values.Add(parenExpr->mExpression);
  15939. SizedArray<BfTokenNode*, 1> commas;
  15940. _GetValues((BfSizedArrayType*)checkArrayType->mElementType, parenExpr->mOpenParen, values, commas, parenExpr->mCloseParen, ignore);
  15941. depth--;
  15942. continue;
  15943. }
  15944. }
  15945. if (expr != NULL)
  15946. {
  15947. auto evalFlags = (BfEvalExprFlags)(mBfEvalExprFlags & BfEvalExprFlags_InheritFlags);
  15948. bool tryDefer = false;
  15949. if ((checkArrayType->IsComposite()) &&
  15950. ((expr->IsA<BfInvocationExpression>()) || (expr->IsExact<BfTupleExpression>())))
  15951. {
  15952. // We evaluate with a new scope because this expression may create variables that we don't want to be visible to other
  15953. // non-deferred evaluations (since the value may actually be a FakeVal)
  15954. SetAndRestoreValue<bool> prevIgnoreWrites(mModule->mBfIRBuilder->mIgnoreWrites, true);
  15955. elementValue = mModule->CreateValueFromExpression(expr, checkArrayType->mElementType, (BfEvalExprFlags)(evalFlags | BfEvalExprFlags_CreateConditionalScope));
  15956. deferredValue = !prevIgnoreWrites.mPrevVal && elementValue.mValue.IsFake();
  15957. }
  15958. else
  15959. {
  15960. elementValue = mModule->CreateValueFromExpression(expr, checkArrayType->mElementType, evalFlags);
  15961. }
  15962. if (!elementValue)
  15963. elementValue = mModule->GetDefaultTypedValue(checkArrayType->mElementType);
  15964. if ((!elementValue) || (!CheckAllowValue(elementValue, expr)))
  15965. elementValue = mModule->GetDefaultTypedValue(checkArrayType->mElementType);
  15966. // For now, we can't properly create const-valued non-size-aligned composites
  15967. // if (checkArrayType->mElementType->NeedsExplicitAlignment())
  15968. // isAllConst = false;
  15969. if (!elementValue.mValue.IsConst())
  15970. isAllConst = false;
  15971. if (elementValue.IsAddr())
  15972. isAllConst = false;
  15973. InitValue initValue;
  15974. initValue.mValue = elementValue;
  15975. initValue.mIsDeferred = deferredValue;
  15976. values.push_back(initValue);
  15977. }
  15978. }
  15979. }
  15980. };
  15981. int valueIdx = 0;
  15982. std::function<void(BfTypedValue, BfTokenNode* openToken, const BfSizedArray<BfExpression*>&, const BfSizedArray<BfTokenNode*>&, BfTokenNode*)>
  15983. _CreateMemArray = [&](BfTypedValue arrayValue, BfTokenNode* openToken, const BfSizedArray<BfExpression*>& valueExprs, const BfSizedArray<BfTokenNode*>& commas, BfTokenNode* closeToken)
  15984. {
  15985. BF_ASSERT(arrayValue.mType->IsSizedArray());
  15986. auto checkArrayType = (BfSizedArrayType*)arrayValue.mType;
  15987. int valIdx = 0;
  15988. bool hasUninit = false;
  15989. for (int idx = 0; idx < checkArrayType->mElementCount; idx++)
  15990. {
  15991. BfExpression* expr = NULL;
  15992. BfTypedValue elementValue;
  15993. if (idx >= (int)valueExprs.size())
  15994. break;
  15995. expr = valueExprs[idx];
  15996. if ((BfNodeDynCastExact<BfUninitializedExpression>(expr) != NULL) && (idx == (int)commas.size()))
  15997. {
  15998. hasUninit = true;
  15999. break;
  16000. }
  16001. BfIRValue elemPtrValue = mModule->CreateIndexedValue(checkArrayType->mElementType, arrayValue.mValue, valIdx, true);
  16002. valIdx++;
  16003. if (checkArrayType->mElementType->IsSizedArray())
  16004. {
  16005. if (auto arrayInitExpr = BfNodeDynCast<BfTupleExpression>(expr))
  16006. {
  16007. _CreateMemArray(BfTypedValue(elemPtrValue, checkArrayType->mElementType, true), arrayInitExpr->mOpenParen, arrayInitExpr->mValues, arrayInitExpr->mCommas, arrayInitExpr->mCloseParen);
  16008. continue;
  16009. }
  16010. else if (auto arrayInitExpr = BfNodeDynCast<BfCollectionInitializerExpression>(expr))
  16011. {
  16012. _CreateMemArray(BfTypedValue(elemPtrValue, checkArrayType->mElementType, true), arrayInitExpr->mOpenBrace, arrayInitExpr->mValues, arrayInitExpr->mCommas, arrayInitExpr->mCloseBrace);
  16013. continue;
  16014. }
  16015. else if (auto parenExpr = BfNodeDynCast<BfParenthesizedExpression>(expr))
  16016. {
  16017. depth++;
  16018. SizedArray<BfExpression*, 1> values;
  16019. values.Add(parenExpr->mExpression);
  16020. SizedArray<BfTokenNode*, 1> commas;
  16021. _CreateMemArray(BfTypedValue(elemPtrValue, checkArrayType->mElementType, true), parenExpr->mOpenParen, values, commas, parenExpr->mCloseParen);
  16022. depth--;
  16023. continue;
  16024. }
  16025. }
  16026. if (expr != NULL)
  16027. {
  16028. InitValue initValue = values[valueIdx++];
  16029. elementValue = initValue.mValue;
  16030. if (initValue.mIsDeferred)
  16031. {
  16032. BfTypedValue elemePtrTypedVal = BfTypedValue(elemPtrValue, checkArrayType->mElementType, BfTypedValueKind_Addr);
  16033. BfExprEvaluator exprEvaluator(mModule);
  16034. exprEvaluator.mExpectingType = checkArrayType->mElementType;
  16035. exprEvaluator.mReceivingValue = &elemePtrTypedVal;
  16036. exprEvaluator.Evaluate(expr);
  16037. exprEvaluator.GetResult();
  16038. if (exprEvaluator.mReceivingValue == NULL)
  16039. {
  16040. // We wrote directly to the array in-place, we're done with this element
  16041. continue;
  16042. }
  16043. elementValue = exprEvaluator.mResult;
  16044. elementValue = mModule->Cast(expr, elementValue, checkArrayType->mElementType);
  16045. if (!elementValue)
  16046. {
  16047. mModule->AssertErrorState();
  16048. continue;
  16049. }
  16050. }
  16051. elementValue = mModule->LoadValue(elementValue);
  16052. mModule->mBfIRBuilder->CreateAlignedStore(elementValue.mValue, elemPtrValue, checkArrayType->mElementType->mAlign);
  16053. }
  16054. }
  16055. int fillCount = (int)(checkArrayType->mElementCount - valIdx);
  16056. if (fillCount > 0)
  16057. {
  16058. BfIRValue elemPtrValue = mModule->CreateIndexedValue(checkArrayType->mElementType, arrayValue.mValue, valIdx, true);
  16059. if (hasUninit)
  16060. {
  16061. if (!mModule->IsOptimized())
  16062. {
  16063. int setSize = std::min(checkArrayType->mElementType->mSize, 128); // Keep it to a reasonable number of bytes to trash
  16064. mModule->mBfIRBuilder->CreateMemSet(elemPtrValue, mModule->mBfIRBuilder->CreateConst(BfTypeCode_Int8, 0xCC),
  16065. mModule->GetConstValue(setSize), checkArrayType->mElementType->mAlign);
  16066. }
  16067. }
  16068. else
  16069. {
  16070. int setSize = (int)((checkArrayType->mElementType->GetStride() * (fillCount - 1)) + checkArrayType->mElementType->mSize);
  16071. if (setSize >= 0)
  16072. {
  16073. mModule->mBfIRBuilder->CreateMemSet(elemPtrValue, mModule->mBfIRBuilder->CreateConst(BfTypeCode_Int8, 0),
  16074. mModule->GetConstValue(setSize), checkArrayType->mElementType->mAlign);
  16075. }
  16076. }
  16077. }
  16078. };
  16079. std::function<BfIRValue(BfTypedValue, BfTokenNode*, const BfSizedArray<BfExpression*>&, const BfSizedArray<BfTokenNode*>&, BfTokenNode*)>
  16080. _CreateConstArray = [&](BfTypedValue arrayValue, BfTokenNode* openToken, const BfSizedArray<BfExpression*>& valueExprs, const BfSizedArray<BfTokenNode*>& commas, BfTokenNode* closeToken)
  16081. {
  16082. SizedArray<BfIRValue, 8> members;
  16083. BF_ASSERT(arrayValue.mType->IsSizedArray());
  16084. auto checkArrayType = (BfSizedArrayType*)arrayValue.mType;
  16085. int valIdx = 0;
  16086. for (int idx = 0; idx < checkArrayType->mElementCount; idx++)
  16087. {
  16088. BfTypedValue elementValue;
  16089. if (idx >= (int)valueExprs.size())
  16090. break;
  16091. auto expr = valueExprs[idx];
  16092. if (expr == NULL)
  16093. continue;
  16094. valIdx++;
  16095. if (checkArrayType->mElementType->IsSizedArray())
  16096. {
  16097. if (auto arrayInitExpr = BfNodeDynCast<BfTupleExpression>(expr))
  16098. {
  16099. members.push_back(_CreateConstArray(checkArrayType->mElementType, arrayInitExpr->mOpenParen, arrayInitExpr->mValues, arrayInitExpr->mCommas, arrayInitExpr->mCloseParen));
  16100. continue;
  16101. }
  16102. else if (auto arrayInitExpr = BfNodeDynCast<BfCollectionInitializerExpression>(expr))
  16103. {
  16104. members.push_back(_CreateConstArray(checkArrayType->mElementType, arrayInitExpr->mOpenBrace, arrayInitExpr->mValues, arrayInitExpr->mCommas, arrayInitExpr->mCloseBrace));
  16105. continue;
  16106. }
  16107. else if (auto parenExpr = BfNodeDynCast<BfParenthesizedExpression>(expr))
  16108. {
  16109. depth++;
  16110. SizedArray<BfExpression*, 1> values;
  16111. values.Add(parenExpr->mExpression);
  16112. SizedArray<BfTokenNode*, 1> commas;
  16113. members.push_back(_CreateConstArray(checkArrayType->mElementType, parenExpr->mOpenParen, values, commas, parenExpr->mCloseParen));
  16114. depth--;
  16115. continue;
  16116. }
  16117. }
  16118. InitValue initValue = values[valueIdx++];
  16119. BF_ASSERT(!initValue.mIsUninitialized);
  16120. elementValue = initValue.mValue;
  16121. members.push_back(elementValue.mValue);
  16122. }
  16123. int fillCount = (int)(checkArrayType->mElementCount - valIdx);
  16124. if (fillCount > 0)
  16125. {
  16126. // We just need to insert one default value, it will be duplicated as needed into the backend
  16127. auto defaultVal = mModule->GetDefaultTypedValue(checkArrayType->GetUnderlyingType());
  16128. BF_ASSERT(defaultVal.mValue.IsConst());
  16129. members.push_back(defaultVal.mValue);
  16130. }
  16131. auto allocArrayType = checkArrayType;
  16132. if (checkArrayType->IsUndefSizedArray())
  16133. allocArrayType = mModule->CreateSizedArrayType(checkArrayType->GetUnderlyingType(), (int)members.size());
  16134. return mModule->mBfIRBuilder->CreateConstAgg(mModule->mBfIRBuilder->MapType(checkArrayType), members);
  16135. };
  16136. _GetValues(arrayType, openToken, valueExprs, commas, closeToken, false);
  16137. if (!failedAt.IsEmpty())
  16138. {
  16139. mResult = mModule->GetDefaultTypedValue(arrayType, false, BfDefaultValueKind_Addr);
  16140. return;
  16141. }
  16142. if (receivingValue != NULL)
  16143. {
  16144. BF_ASSERT(receivingValue->mType == arrayType);
  16145. BF_ASSERT(receivingValue->IsAddr());
  16146. mResult = *receivingValue;
  16147. _CreateMemArray(mResult, openToken, valueExprs, commas, closeToken);
  16148. }
  16149. else if (isAllConst)
  16150. {
  16151. mResult = BfTypedValue(_CreateConstArray(arrayType, openToken, valueExprs, commas, closeToken), arrayType, BfTypedValueKind_Value);
  16152. }
  16153. else
  16154. {
  16155. if ((mReceivingValue != NULL) && (mReceivingValue->mType == arrayType) && (mReceivingValue->IsAddr()))
  16156. {
  16157. mResult = *mReceivingValue;
  16158. mReceivingValue = NULL;
  16159. }
  16160. else
  16161. {
  16162. auto arrayValue = mModule->CreateAlloca(arrayType);
  16163. mResult = BfTypedValue(arrayValue, arrayType, BfTypedValueKind_TempAddr);
  16164. }
  16165. if (!arrayType->IsValuelessType())
  16166. _CreateMemArray(mResult, openToken, valueExprs, commas, closeToken);
  16167. }
  16168. }
  16169. }
  16170. void BfExprEvaluator::Visit(BfTupleExpression* tupleExpr)
  16171. {
  16172. BfTypeInstance* tupleType = NULL;
  16173. bool hadFullMatch = false;
  16174. if ((mExpectingType != NULL) && (mExpectingType->IsTuple()))
  16175. {
  16176. tupleType = (BfTypeInstance*)mExpectingType;
  16177. hadFullMatch = tupleType->mFieldInstances.size() == tupleExpr->mValues.size();
  16178. }
  16179. struct InitValue
  16180. {
  16181. BfTypedValue mValue;
  16182. bool mIsUninitialized;
  16183. bool mIsDefaultInitializer;
  16184. bool mIsDeferred;
  16185. InitValue()
  16186. {
  16187. mIsUninitialized = false;
  16188. mIsDefaultInitializer = false;
  16189. mIsDeferred = false;
  16190. }
  16191. };
  16192. SizedArray<BfTypedValue, 2> typedValues;
  16193. if ((tupleExpr->mCommas.size() != 0) && (tupleExpr->mCommas.size() >= tupleExpr->mValues.size()))
  16194. {
  16195. // We would normally give this error during syntax parsing, but a TupleExpression can be an array initializer
  16196. mModule->FailAfter("Expression expected", tupleExpr->mCommas.back());
  16197. }
  16198. for (int valueIdx = 0; valueIdx < (int)tupleExpr->mValues.size(); valueIdx++)
  16199. {
  16200. BfExpression* valueExpr = tupleExpr->mValues[valueIdx];
  16201. BfType* fieldType = NULL;
  16202. BfFieldInstance* fieldInstance = NULL;
  16203. if (tupleType != NULL)
  16204. {
  16205. if (valueIdx < (int)tupleType->mFieldInstances.size())
  16206. {
  16207. fieldInstance = (BfFieldInstance*)&tupleType->mFieldInstances[valueIdx];
  16208. fieldType = fieldInstance->GetResolvedType();
  16209. if (fieldType->IsVoid())
  16210. {
  16211. typedValues.push_back(BfTypedValue());
  16212. continue;
  16213. }
  16214. if (fieldType->IsVar())
  16215. {
  16216. hadFullMatch = false;
  16217. fieldType = NULL;
  16218. }
  16219. }
  16220. }
  16221. bool tryDefer = false;
  16222. if (((fieldType == NULL) || (fieldType->IsComposite())) &&
  16223. ((valueExpr->IsA<BfInvocationExpression>()) || (valueExpr->IsExact<BfTupleExpression>())))
  16224. {
  16225. tryDefer = true;
  16226. }
  16227. SetAndRestoreValue<bool> prevIgnoreWrites(mModule->mBfIRBuilder->mIgnoreWrites, mModule->mBfIRBuilder->mIgnoreWrites || tryDefer);
  16228. BfTypedValue value = mModule->CreateValueFromExpression(valueExpr, fieldType);
  16229. if (!value)
  16230. {
  16231. if (fieldType != NULL)
  16232. value = mModule->GetDefaultTypedValue(fieldType);
  16233. else
  16234. value = mModule->GetDefaultTypedValue(mModule->mContext->mBfObjectType);
  16235. }
  16236. if ((fieldInstance != NULL) && (!fieldInstance->GetFieldDef()->IsUnnamedTupleField()) && (valueIdx < (int)tupleExpr->mNames.size()))
  16237. {
  16238. auto checkName = tupleExpr->mNames[valueIdx];
  16239. if (checkName != NULL)
  16240. {
  16241. if (checkName->ToString() != fieldInstance->GetFieldDef()->mName)
  16242. hadFullMatch = false;
  16243. }
  16244. }
  16245. value = mModule->LoadValue(value);
  16246. typedValues.push_back(value);
  16247. }
  16248. if (!hadFullMatch)
  16249. {
  16250. BfTypeVector fieldTypes;
  16251. Array<String> fieldNames;
  16252. HashSet<String> fieldNameSet;
  16253. for (auto typedVal : typedValues)
  16254. {
  16255. auto type = typedVal.mType;
  16256. if (type != NULL)
  16257. fieldTypes.push_back(type);
  16258. else
  16259. fieldTypes.push_back(mModule->mContext->mBfObjectType);
  16260. }
  16261. for (BfTupleNameNode* requestedName : tupleExpr->mNames)
  16262. {
  16263. if (requestedName == NULL)
  16264. fieldNames.push_back("");
  16265. else
  16266. {
  16267. auto fieldName = requestedName->mNameNode->ToString();
  16268. if (!fieldNameSet.TryAdd(fieldName, NULL))
  16269. {
  16270. mModule->Fail(StrFormat("A field named '%s' has already been declared", fieldName.c_str()), requestedName->mNameNode);
  16271. }
  16272. fieldNames.push_back(fieldName);
  16273. }
  16274. }
  16275. tupleType = mModule->CreateTupleType(fieldTypes, fieldNames);
  16276. }
  16277. mModule->mBfIRBuilder->PopulateType(tupleType);
  16278. BfIRValue curTupleValue;
  16279. if ((mReceivingValue != NULL) && (mReceivingValue->mType == tupleType) && (mReceivingValue->IsAddr()))
  16280. {
  16281. mResult = *mReceivingValue;
  16282. mReceivingValue = NULL;
  16283. curTupleValue = mResult.mValue;
  16284. }
  16285. else
  16286. {
  16287. int valueIdx = -1;
  16288. bool isExactConst = true;
  16289. for (int fieldIdx = 0; fieldIdx < (int)tupleType->mFieldInstances.size(); fieldIdx++)
  16290. {
  16291. BfFieldInstance* fieldInstance = &tupleType->mFieldInstances[fieldIdx];
  16292. if (fieldInstance->mDataIdx < 0)
  16293. continue;
  16294. ++valueIdx;
  16295. auto typedValue = typedValues[valueIdx];
  16296. if (typedValue.mType != fieldInstance->mResolvedType)
  16297. {
  16298. isExactConst = false;
  16299. break;
  16300. }
  16301. if (!typedValue.mValue.IsConst())
  16302. {
  16303. isExactConst = false;
  16304. break;
  16305. }
  16306. }
  16307. if (isExactConst)
  16308. {
  16309. mModule->PopulateType(tupleType);
  16310. Array<BfIRValue> irValues;
  16311. irValues.Resize(typedValues.mSize + 1);
  16312. irValues[0] = mModule->mBfIRBuilder->CreateConstAggZero(mModule->mBfIRBuilder->MapType(tupleType->mBaseType));
  16313. for (int fieldIdx = 0; fieldIdx < (int)tupleType->mFieldInstances.size(); fieldIdx++)
  16314. {
  16315. BfFieldInstance* fieldInstance = &tupleType->mFieldInstances[fieldIdx];
  16316. if (fieldInstance->mDataIdx < 0)
  16317. continue;
  16318. irValues[fieldInstance->mDataIdx] = typedValues[fieldIdx].mValue;
  16319. }
  16320. for (auto& val : irValues)
  16321. {
  16322. if (!val)
  16323. val = mModule->mBfIRBuilder->CreateConstArrayZero(0);
  16324. }
  16325. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConstAgg(mModule->mBfIRBuilder->MapType(tupleType), irValues), tupleType);
  16326. return;
  16327. }
  16328. curTupleValue = mModule->CreateAlloca(tupleType);
  16329. mResultIsTempComposite = true;
  16330. mResult = BfTypedValue(curTupleValue, tupleType, BfTypedValueKind_TempAddr);
  16331. }
  16332. int valueIdx = -1;
  16333. for (int fieldIdx = 0; fieldIdx < (int)tupleType->mFieldInstances.size(); fieldIdx++)
  16334. {
  16335. BfFieldInstance* fieldInstance = &tupleType->mFieldInstances[fieldIdx];
  16336. ++valueIdx;
  16337. if (fieldInstance->mResolvedType->IsValuelessType())
  16338. continue;
  16339. auto typedVal = typedValues[valueIdx];
  16340. if (!typedVal)
  16341. {
  16342. mModule->AssertErrorState();
  16343. continue;
  16344. }
  16345. if (fieldInstance->mDataIdx >= 0)
  16346. {
  16347. auto memberVal = mModule->mBfIRBuilder->CreateInBoundsGEP(curTupleValue, 0, fieldInstance->mDataIdx);
  16348. if ((!mModule->mBfIRBuilder->mIgnoreWrites) && (typedVal.mValue.IsFake()))
  16349. {
  16350. // Value was deferred. Allow us to try to init in place
  16351. BfExpression* valueExpr = tupleExpr->mValues[valueIdx];
  16352. BfTypedValue memberPtrTypedVal = BfTypedValue(memberVal, fieldInstance->mResolvedType, BfTypedValueKind_Addr);
  16353. BfExprEvaluator exprEvaluator(mModule);
  16354. exprEvaluator.mExpectingType = fieldInstance->mResolvedType;
  16355. exprEvaluator.mReceivingValue = &memberPtrTypedVal;
  16356. exprEvaluator.Evaluate(valueExpr);
  16357. exprEvaluator.GetResult();
  16358. if (exprEvaluator.mReceivingValue == NULL)
  16359. {
  16360. // We wrote directly to the array in-place, we're done with this element
  16361. continue;
  16362. }
  16363. typedVal = exprEvaluator.mResult;
  16364. typedVal = mModule->Cast(valueExpr, typedVal, fieldInstance->mResolvedType);
  16365. if (!typedVal)
  16366. {
  16367. mModule->AssertErrorState();
  16368. continue;
  16369. }
  16370. typedVal = mModule->LoadValue(typedVal);
  16371. }
  16372. if (typedVal.mType->IsVar())
  16373. {
  16374. // Do nothing
  16375. }
  16376. else if (typedVal.IsSplat())
  16377. mModule->AggregateSplatIntoAddr(typedVal, memberVal);
  16378. else
  16379. mModule->mBfIRBuilder->CreateStore(typedVal.mValue, memberVal);
  16380. }
  16381. }
  16382. }
  16383. BfTypedValue BfExprEvaluator::SetupNullConditional(BfTypedValue thisValue, BfTokenNode* dotToken)
  16384. {
  16385. bool isStaticLookup = (!thisValue) ||
  16386. ((!thisValue.mType->IsValuelessType()) && (!thisValue.mValue));
  16387. if (isStaticLookup)
  16388. {
  16389. mModule->Fail("Null conditional reference not valid for static field references", dotToken);
  16390. return thisValue;
  16391. }
  16392. auto opResult = PerformUnaryOperation_TryOperator(thisValue, NULL, BfUnaryOp_NullConditional, dotToken, BfUnaryOpFlag_None);
  16393. if (opResult)
  16394. thisValue = opResult;
  16395. //TODO: But make null conditional work for Nullable types
  16396. if (thisValue.mType->IsNullable())
  16397. {
  16398. // Success
  16399. }
  16400. else if ((thisValue.mType->IsPointer()) || (thisValue.mType->IsObjectOrInterface()))
  16401. {
  16402. // Also good
  16403. }
  16404. else
  16405. {
  16406. mModule->Warn(0, StrFormat("Null conditional reference is unnecessary since value type '%s' can never be null", mModule->TypeToString(thisValue.mType).c_str()), dotToken);
  16407. return thisValue;
  16408. }
  16409. thisValue = mModule->LoadValue(thisValue);
  16410. BfPendingNullConditional* pendingNullCond = mModule->mCurMethodState->mPendingNullConditional;
  16411. if (pendingNullCond == NULL)
  16412. {
  16413. pendingNullCond = new BfPendingNullConditional();
  16414. mModule->mCurMethodState->mPendingNullConditional = pendingNullCond;
  16415. }
  16416. if (!pendingNullCond->mPrevBB)
  16417. pendingNullCond->mPrevBB = mModule->mBfIRBuilder->GetInsertBlock();
  16418. if (!pendingNullCond->mDoneBB)
  16419. pendingNullCond->mDoneBB = mModule->mBfIRBuilder->CreateBlock("nullCond.done");
  16420. // We will in the br to checkBB later
  16421. if (!pendingNullCond->mCheckBB)
  16422. {
  16423. pendingNullCond->mCheckBB = mModule->mBfIRBuilder->CreateBlock("nullCond.check");
  16424. mModule->AddBasicBlock(pendingNullCond->mCheckBB);
  16425. }
  16426. BfIRValue isNotNull;
  16427. if (thisValue.mType->IsNullable())
  16428. {
  16429. BfTypeInstance* nullableType = (BfTypeInstance*)thisValue.mType->ToTypeInstance();
  16430. auto elementType = nullableType->GetUnderlyingType();
  16431. if (elementType->IsValuelessType())
  16432. {
  16433. thisValue = mModule->MakeAddressable(thisValue);
  16434. BfIRValue hasValuePtr = mModule->mBfIRBuilder->CreateInBoundsGEP(thisValue.mValue, 0, 1); // mHasValue
  16435. isNotNull = mModule->mBfIRBuilder->CreateLoad(hasValuePtr);
  16436. thisValue = BfTypedValue(mModule->mBfIRBuilder->GetFakeVal(), elementType, true);
  16437. }
  16438. else
  16439. {
  16440. thisValue = mModule->MakeAddressable(thisValue);
  16441. BfIRValue hasValuePtr = mModule->mBfIRBuilder->CreateInBoundsGEP(thisValue.mValue, 0, 2); // mHasValue
  16442. isNotNull = mModule->mBfIRBuilder->CreateLoad(hasValuePtr);
  16443. BfIRValue valuePtr = mModule->mBfIRBuilder->CreateInBoundsGEP(thisValue.mValue, 0, 1); // mValue
  16444. thisValue = BfTypedValue(valuePtr, elementType, true);
  16445. }
  16446. }
  16447. else
  16448. isNotNull = mModule->mBfIRBuilder->CreateIsNotNull(thisValue.mValue);
  16449. BfIRBlock notNullBB = mModule->mBfIRBuilder->CreateBlock("nullCond.notNull");
  16450. pendingNullCond->mNotNullBBs.Add(notNullBB);
  16451. mModule->mBfIRBuilder->CreateCondBr(isNotNull, notNullBB, pendingNullCond->mDoneBB);
  16452. mModule->AddBasicBlock(notNullBB);
  16453. return thisValue;
  16454. }
  16455. void BfExprEvaluator::CheckDotToken(BfTokenNode* tokenNode)
  16456. {
  16457. if ((tokenNode != NULL) && (tokenNode->mToken == BfToken_DotDot))
  16458. mModule->Fail("Unexpected cascade operation. Chaining can only be used for method invocations", tokenNode);
  16459. }
  16460. void BfExprEvaluator::DoMemberReference(BfMemberReferenceExpression* memberRefExpr, BfTypedValue* outCascadeValue)
  16461. {
  16462. CheckDotToken(memberRefExpr->mDotToken);
  16463. BfAttributeState attributeState;
  16464. attributeState.mTarget = (BfAttributeTargets)(BfAttributeTargets_MemberAccess);
  16465. String findName;
  16466. BfAstNode* nameRefNode = memberRefExpr->mMemberName;
  16467. if (auto attrIdentifierExpr = BfNodeDynCast<BfAttributedIdentifierNode>(memberRefExpr->mMemberName))
  16468. {
  16469. nameRefNode = attrIdentifierExpr->mIdentifier;
  16470. // Don't validate
  16471. attributeState.mCustomAttributes = mModule->GetCustomAttributes(attrIdentifierExpr->mAttributes, BfAttributeTargets_SkipValidate);
  16472. if (nameRefNode != NULL)
  16473. findName = attrIdentifierExpr->mIdentifier->ToString();
  16474. }
  16475. else if (memberRefExpr->mMemberName != NULL)
  16476. findName = memberRefExpr->mMemberName->ToString();
  16477. defer
  16478. (
  16479. if (attributeState.mCustomAttributes != NULL)
  16480. {
  16481. if (mPropDef != NULL)
  16482. attributeState.mTarget = (BfAttributeTargets)(attributeState.mTarget | BfAttributeTargets_Invocation);
  16483. mModule->ValidateCustomAttributes(attributeState.mCustomAttributes, attributeState.mTarget);
  16484. }
  16485. );
  16486. SetAndRestoreValue<BfAttributeState*> prevAttributeState(mModule->mAttributeState, &attributeState);
  16487. BfTypeInstance* expectingTypeInst = NULL;
  16488. if (mExpectingType != NULL)
  16489. {
  16490. expectingTypeInst = mExpectingType->ToTypeInstance();
  16491. if (mExpectingType->IsPointer())
  16492. expectingTypeInst = mExpectingType->GetUnderlyingType()->ToTypeInstance();
  16493. else if (mExpectingType->IsNullable())
  16494. expectingTypeInst = mExpectingType->GetUnderlyingType()->ToTypeInstance();
  16495. else if (mExpectingType->IsConstExprValue())
  16496. expectingTypeInst = mExpectingType->GetUnderlyingType()->ToTypeInstance();
  16497. else if (mExpectingType->IsGenericParam())
  16498. {
  16499. auto genericParam = mModule->GetGenericParamInstance((BfGenericParamType*)mExpectingType);
  16500. if (genericParam->mTypeConstraint != NULL)
  16501. expectingTypeInst = genericParam->mTypeConstraint->ToTypeInstance();
  16502. }
  16503. }
  16504. BfAutoComplete* autoComplete = GetAutoComplete();
  16505. if (autoComplete != NULL)
  16506. {
  16507. SetAndRestoreValue<bool> prevFriendSet(autoComplete->mHasFriendSet, (attributeState.mCustomAttributes != NULL) && (attributeState.mCustomAttributes->Contains(mModule->mCompiler->mFriendAttributeTypeDef)));
  16508. if (memberRefExpr->mTarget == NULL)
  16509. {
  16510. String filter;
  16511. if ((mExpectingType != NULL) &&
  16512. (autoComplete->InitAutocomplete(memberRefExpr->mDotToken, memberRefExpr->mMemberName, filter)))
  16513. {
  16514. if (expectingTypeInst != NULL)
  16515. {
  16516. bool allowPrivate = expectingTypeInst == mModule->mCurTypeInstance;
  16517. if (expectingTypeInst->IsEnum())
  16518. autoComplete->AddEnumTypeMembers(expectingTypeInst, filter, false, allowPrivate);
  16519. autoComplete->AddSelfResultTypeMembers(expectingTypeInst, expectingTypeInst, filter, allowPrivate);
  16520. }
  16521. }
  16522. }
  16523. else
  16524. {
  16525. autoComplete->CheckMemberReference(memberRefExpr->mTarget, memberRefExpr->mDotToken, memberRefExpr->mMemberName, false, mExpectingType);
  16526. if (auto objCreateExpr = BfNodeDynCast<BfObjectCreateExpression>(memberRefExpr->mTarget))
  16527. {
  16528. // This handles a weird case where we have "obj a = new\nWhatever().Thing = 123;".
  16529. // That gets parsed as "Whatever()" being the type we want to create, and then referencing
  16530. // the "Thing" member of that new object.
  16531. //if (objCreateExpr->mArraySizeSpecifier == NULL)
  16532. CheckObjectCreateTypeRef(mExpectingType, objCreateExpr->mNewNode);
  16533. }
  16534. }
  16535. }
  16536. if (memberRefExpr->mTarget == NULL)
  16537. {
  16538. if (mExpectingType == NULL)
  16539. {
  16540. mModule->Fail("Unqualified dot syntax can only be used when the result type can be inferred", nameRefNode);
  16541. return;
  16542. }
  16543. if (expectingTypeInst == NULL)
  16544. {
  16545. mModule->Fail(StrFormat("Unqualified dot syntax cannot be used with type '%s'", mModule->TypeToString(mExpectingType).c_str()), nameRefNode);
  16546. return;
  16547. }
  16548. if (mExpectingType->IsVar())
  16549. {
  16550. mResult = mModule->GetDefaultTypedValue(mExpectingType);
  16551. return;
  16552. }
  16553. BfTypedValue expectingVal(expectingTypeInst);
  16554. mResult = LookupField(memberRefExpr->mMemberName, expectingVal, findName);
  16555. if ((mResult) || (mPropDef != NULL))
  16556. return;
  16557. }
  16558. bool isNullCondLookup = (memberRefExpr->mDotToken != NULL) && (memberRefExpr->mDotToken->GetToken() == BfToken_QuestionDot);
  16559. bool isCascade = ((memberRefExpr->mDotToken != NULL) && (memberRefExpr->mDotToken->GetToken() == BfToken_DotDot));
  16560. BfIdentifierNode* nameLeft = BfNodeDynCast<BfIdentifierNode>(memberRefExpr->mTarget);
  16561. BfIdentifierNode* nameRight = BfIdentifierCast(memberRefExpr->mMemberName);
  16562. if ((nameLeft != NULL) && (nameRight != NULL) && (!isNullCondLookup) && (!isCascade))
  16563. {
  16564. bool hadError = false;
  16565. LookupQualifiedName(memberRefExpr, nameLeft, nameRight, true, &hadError);
  16566. if ((mResult) || (mPropDef != NULL))
  16567. return;
  16568. if (hadError)
  16569. return;
  16570. LookupQualifiedStaticField(memberRefExpr, nameLeft, nameRight, false);
  16571. return;
  16572. }
  16573. BfTypedValue thisValue;
  16574. if (auto exprTarget = BfNodeDynCast<BfExpression>(memberRefExpr->mTarget))
  16575. {
  16576. if (auto typeOfExpr = BfNodeDynCast<BfTypeOfExpression>(memberRefExpr->mTarget))
  16577. {
  16578. if (auto nameIdentifer = BfNodeDynCast<BfIdentifierNode>(memberRefExpr->mMemberName))
  16579. {
  16580. if (LookupTypeProp(typeOfExpr, nameIdentifer))
  16581. return;
  16582. }
  16583. }
  16584. //Hm, not using VisitChild broke our ability to write to a field for a not-initialized local struct
  16585. VisitChild(memberRefExpr->mTarget);
  16586. GetResult();
  16587. thisValue = mResult;
  16588. if (!thisValue)
  16589. {
  16590. if (auto targetIdentifier = BfNodeDynCast<BfIdentifierNode>(exprTarget))
  16591. {
  16592. thisValue = BfTypedValue(mModule->ResolveTypeRef(targetIdentifier, NULL, BfPopulateType_Declaration));
  16593. }
  16594. }
  16595. if (!thisValue.HasType())
  16596. return;
  16597. //thisValue = mResult;
  16598. }
  16599. else if (auto typeRef = BfNodeDynCast<BfTypeReference>(memberRefExpr->mTarget))
  16600. {
  16601. // Look up static field
  16602. thisValue = BfTypedValue(ResolveTypeRef(typeRef));
  16603. }
  16604. if (nameRefNode == NULL)
  16605. {
  16606. mModule->AssertErrorState();
  16607. return;
  16608. }
  16609. if (isNullCondLookup)
  16610. thisValue = SetupNullConditional(thisValue, memberRefExpr->mDotToken);
  16611. mResult = LookupField(nameRefNode, thisValue, findName);
  16612. if ((!mResult) && (mPropDef == NULL))
  16613. {
  16614. if (thisValue.mType != NULL)
  16615. {
  16616. BfTypeInstance* typeInst = thisValue.mType->ToTypeInstance();
  16617. auto compiler = mModule->mCompiler;
  16618. if ((typeInst != NULL) && (compiler->IsAutocomplete()) && (compiler->mResolvePassData->mAutoComplete->CheckFixit(memberRefExpr->mMemberName)))
  16619. {
  16620. FixitAddMember(typeInst, mExpectingType, findName, !thisValue.mValue);
  16621. }
  16622. }
  16623. if ((!thisValue.mValue) && (thisValue.mType != NULL))
  16624. {
  16625. if (auto targetIdentifier = BfNodeDynCast<BfIdentifierNode>(memberRefExpr->mMemberName))
  16626. {
  16627. mResult.mType = mModule->ResolveInnerType(thisValue.mType, targetIdentifier, BfPopulateType_Declaration);
  16628. }
  16629. }
  16630. if ((memberRefExpr->mTarget == NULL) && (expectingTypeInst != NULL) && (autoComplete != NULL))
  16631. {
  16632. if (autoComplete->CheckFixit(memberRefExpr->mMemberName))
  16633. {
  16634. autoComplete->FixitAddCase(expectingTypeInst, memberRefExpr->mMemberName->ToString(), BfTypeVector());
  16635. }
  16636. }
  16637. if (mResult.mType == NULL)
  16638. mModule->Fail("Unable to find member", nameRefNode);
  16639. }
  16640. if ((isNullCondLookup) && (mPropDef == NULL))
  16641. mResult = GetResult();
  16642. if (isCascade)
  16643. {
  16644. if (outCascadeValue != NULL)
  16645. *outCascadeValue = thisValue;
  16646. else
  16647. mModule->Fail("Unexpected cascade operation. Chaining can only be used for method invocations", memberRefExpr->mDotToken);
  16648. }
  16649. }
  16650. void BfExprEvaluator::Visit(BfMemberReferenceExpression* memberRefExpr)
  16651. {
  16652. DoMemberReference(memberRefExpr, NULL);
  16653. }
  16654. void BfExprEvaluator::Visit(BfIndexerExpression* indexerExpr)
  16655. {
  16656. BfTypedValue target;
  16657. bool wantStatic = false;
  16658. // Try first as a non-static indexer, then as a static indexer
  16659. for (int pass = 0; pass < 2; pass++)
  16660. {
  16661. ///
  16662. {
  16663. SetAndRestoreValue<BfEvalExprFlags> prevFlags(mBfEvalExprFlags, (BfEvalExprFlags)(mBfEvalExprFlags | BfEvalExprFlags_NoLookupError), pass == 0);
  16664. VisitChild(indexerExpr->mTarget);
  16665. }
  16666. ResolveGenericType();
  16667. target = GetResult(true);
  16668. if (target)
  16669. break;
  16670. if (pass == 0)
  16671. {
  16672. SetAndRestoreValue<bool> prevIgnoreErrors(mModule->mIgnoreErrors, (mModule->mIgnoreErrors) || (pass == 0));
  16673. auto staticType = mModule->ResolveTypeRef(indexerExpr->mTarget, {});
  16674. if (staticType != NULL)
  16675. {
  16676. wantStatic = true;
  16677. target.mType = staticType;
  16678. break;
  16679. }
  16680. }
  16681. }
  16682. if (!target.HasType())
  16683. return;
  16684. BfCheckedKind checkedKind = BfCheckedKind_NotSet;
  16685. bool isInlined = false;
  16686. if ((mModule->mAttributeState != NULL) && (mModule->mAttributeState->mCustomAttributes != NULL))
  16687. {
  16688. if (mModule->mAttributeState->mCustomAttributes->Contains(mModule->mCompiler->mInlineAttributeTypeDef))
  16689. {
  16690. isInlined = true;
  16691. mModule->mAttributeState->mUsed = true;
  16692. }
  16693. if (mModule->mAttributeState->mCustomAttributes->Contains(mModule->mCompiler->mCheckedAttributeTypeDef))
  16694. {
  16695. checkedKind = BfCheckedKind_Checked;
  16696. mModule->mAttributeState->mUsed = true;
  16697. }
  16698. if (mModule->mAttributeState->mCustomAttributes->Contains(mModule->mCompiler->mUncheckedAttributeTypeDef))
  16699. {
  16700. checkedKind = BfCheckedKind_Unchecked;
  16701. mModule->mAttributeState->mUsed = true;
  16702. }
  16703. }
  16704. bool isNullCondLookup = (indexerExpr->mOpenBracket != NULL) && (indexerExpr->mOpenBracket->GetToken() == BfToken_QuestionLBracket);
  16705. if (isNullCondLookup)
  16706. target = SetupNullConditional(target, indexerExpr->mOpenBracket);
  16707. if (target.mType->IsVar())
  16708. {
  16709. mResult = BfTypedValue(mModule->GetDefaultValue(target.mType), target.mType, true);
  16710. return;
  16711. }
  16712. if (target.mType->IsTypeInstance())
  16713. {
  16714. mIndexerValues.clear();
  16715. SizedArray<BfExpression*, 2> argExprs;
  16716. BfSizedArray<BfExpression*> sizedArgExprs(indexerExpr->mArguments);
  16717. BfResolvedArgs argValues(&sizedArgExprs);
  16718. ResolveArgValues(argValues, BfResolveArgsFlag_DeferParamEval);
  16719. //exprEvaluator.MatchMethod(elementExpr, NULL, initValue, false, false, "Add", argValues, NULL);
  16720. mIndexerValues = argValues.mResolvedArgs;
  16721. for (auto& val : mIndexerValues)
  16722. if (!val.mTypedValue)
  16723. val.mTypedValue = mModule->GetDefaultTypedValue(mModule->mContext->mBfObjectType);
  16724. BfMethodMatcher methodMatcher(indexerExpr->mTarget, mModule, "[]", mIndexerValues, NULL);
  16725. methodMatcher.mCheckedKind = checkedKind;
  16726. //methodMatcher.CheckType(target.mType->ToTypeInstance(), target, false);
  16727. BfMethodDef* methodDef = NULL;
  16728. auto startCheckTypeInst = target.mType->ToTypeInstance();
  16729. for (int pass = 0; pass < 2; pass++)
  16730. {
  16731. bool isFailurePass = pass == 1;
  16732. auto curCheckType = startCheckTypeInst;
  16733. while (curCheckType != NULL)
  16734. {
  16735. BfProtectionCheckFlags protectionCheckFlags = BfProtectionCheckFlag_None;
  16736. BfPropertyDef* foundProp = NULL;
  16737. BfTypeInstance* foundPropTypeInst = NULL;
  16738. int matchedIndexCount = 0;
  16739. curCheckType->mTypeDef->PopulateMemberSets();
  16740. BfMemberSetEntry* entry;
  16741. BfPropertyDef* matchedProp = NULL;
  16742. BfPropertyDef* nextProp = NULL;
  16743. if (curCheckType->mTypeDef->mPropertySet.TryGetWith(String("[]"), &entry))
  16744. nextProp = (BfPropertyDef*)entry->mMemberDef;
  16745. while (nextProp != NULL)
  16746. {
  16747. auto prop = nextProp;
  16748. nextProp = nextProp->mNextWithSameName;
  16749. //TODO: Match against setMethod (minus last param) if we have no 'get' method
  16750. for (auto checkMethod : prop->mMethods)
  16751. {
  16752. if (checkMethod->mMethodType != BfMethodType_PropertyGetter)
  16753. continue;
  16754. // For generic params - check interface constraints for an indexer, call that method
  16755. BF_ASSERT(!target.mType->IsGenericParam());
  16756. if (checkMethod->mIsStatic != wantStatic)
  16757. continue;
  16758. if (checkMethod->mExplicitInterface != NULL)
  16759. continue;
  16760. auto autoComplete = GetAutoComplete();
  16761. bool wasCapturingMethodMatchInfo = false;
  16762. if (autoComplete != NULL)
  16763. {
  16764. // Set to false to make sure we don't capture method match info from 'params' array creation
  16765. wasCapturingMethodMatchInfo = autoComplete->mIsCapturingMethodMatchInfo;
  16766. autoComplete->mIsCapturingMethodMatchInfo = false;
  16767. }
  16768. defer
  16769. (
  16770. if (autoComplete != NULL)
  16771. autoComplete->mIsCapturingMethodMatchInfo = wasCapturingMethodMatchInfo;
  16772. );
  16773. if ((!isFailurePass) && (!methodMatcher.WantsCheckMethod(protectionCheckFlags, startCheckTypeInst, curCheckType, checkMethod)))
  16774. continue;
  16775. if (!methodMatcher.IsMemberAccessible(curCheckType, checkMethod->mDeclaringType))
  16776. continue;
  16777. methodMatcher.mCheckedKind = checkedKind;
  16778. methodMatcher.mTarget = target;
  16779. methodMatcher.CheckMethod(startCheckTypeInst, curCheckType, checkMethod, false);
  16780. if ((methodMatcher.mBestMethodDef == checkMethod) ||
  16781. ((foundProp == NULL) && (methodMatcher.mBackupMethodDef == checkMethod)))
  16782. {
  16783. foundPropTypeInst = curCheckType;
  16784. foundProp = prop;
  16785. matchedIndexCount = (int)checkMethod->mParams.size();
  16786. }
  16787. }
  16788. }
  16789. if (foundProp != NULL)
  16790. {
  16791. int indexDiff = matchedIndexCount - (int)mIndexerValues.size();
  16792. if (indexDiff > 0)
  16793. {
  16794. mModule->Fail(StrFormat("Expected %d more indices", indexDiff), indexerExpr->mTarget);
  16795. //mModule->mCompiler->mPassInstance->MoreInfo("See method declaration", methodInstance->mMethodDef->mMethodDeclaration);
  16796. }
  16797. else if (indexDiff < 0)
  16798. {
  16799. mModule->Fail(StrFormat("Expected %d fewer indices", -indexDiff), indexerExpr->mTarget);
  16800. }
  16801. else
  16802. {
  16803. mPropSrc = indexerExpr->mOpenBracket;
  16804. mPropDef = foundProp;
  16805. if (foundProp->mIsStatic)
  16806. {
  16807. mPropTarget = BfTypedValue(curCheckType);
  16808. }
  16809. else
  16810. {
  16811. if (target.mType != foundPropTypeInst)
  16812. mPropTarget = mModule->Cast(indexerExpr->mTarget, target, foundPropTypeInst);
  16813. else
  16814. mPropTarget = target;
  16815. }
  16816. mOrigPropTarget = mPropTarget;
  16817. if (isInlined)
  16818. mPropGetMethodFlags = (BfGetMethodInstanceFlags)(mPropGetMethodFlags | BfGetMethodInstanceFlag_ForceInline);
  16819. mPropCheckedKind = checkedKind;
  16820. }
  16821. return;
  16822. }
  16823. curCheckType = curCheckType->mBaseType;
  16824. }
  16825. }
  16826. mModule->Fail("Unable to find indexer property", indexerExpr->mTarget);
  16827. return;
  16828. }
  16829. bool wantsChecks = checkedKind == BfCheckedKind_Checked;
  16830. if (checkedKind == BfCheckedKind_NotSet)
  16831. wantsChecks = mModule->GetDefaultCheckedKind() == BfCheckedKind_Checked;
  16832. //target.mType = mModule->ResolveGenericType(target.mType);
  16833. if (target.mType->IsVar())
  16834. {
  16835. mResult = target;
  16836. return;
  16837. }
  16838. if ((!target.mType->IsPointer()) && (!target.mType->IsSizedArray()))
  16839. {
  16840. mModule->Fail("Expected pointer or array type", indexerExpr->mTarget);
  16841. return;
  16842. }
  16843. auto _GetDefaultResult = [&]()
  16844. {
  16845. return mModule->GetDefaultTypedValue(target.mType->GetUnderlyingType(), false, BfDefaultValueKind_Addr);
  16846. };
  16847. if (indexerExpr->mArguments.size() != 1)
  16848. {
  16849. mModule->Fail("Expected single index", indexerExpr->mOpenBracket);
  16850. mResult = _GetDefaultResult();
  16851. return;
  16852. }
  16853. if (indexerExpr->mArguments[0] == NULL)
  16854. {
  16855. mModule->AssertErrorState();
  16856. mResult = _GetDefaultResult();
  16857. return;
  16858. }
  16859. bool isUndefIndex = false;
  16860. auto indexArgument = mModule->CreateValueFromExpression(indexerExpr->mArguments[0]);
  16861. if (!indexArgument)
  16862. return;
  16863. if (!indexArgument.mType->IsIntegral())
  16864. {
  16865. if (indexArgument.mType->IsVar())
  16866. {
  16867. isUndefIndex = true;
  16868. indexArgument = mModule->GetDefaultTypedValue(mModule->GetPrimitiveType(BfTypeCode_IntPtr), false, BfDefaultValueKind_Undef);
  16869. }
  16870. else
  16871. {
  16872. indexArgument = mModule->Cast(indexerExpr->mArguments[0], indexArgument, mModule->GetPrimitiveType(BfTypeCode_IntPtr));
  16873. if (!indexArgument)
  16874. indexArgument = mModule->GetDefaultTypedValue(mModule->GetPrimitiveType(BfTypeCode_IntPtr));
  16875. }
  16876. }
  16877. if (indexArgument.mType->IsPrimitiveType())
  16878. {
  16879. auto primType = (BfPrimitiveType*)indexArgument.mType;
  16880. if ((!primType->IsSigned()) && (primType->mSize < 8))
  16881. {
  16882. // GEP will always do a signed upcast so we need to cast manually if we are unsigned
  16883. indexArgument = BfTypedValue(mModule->mBfIRBuilder->CreateNumericCast(indexArgument.mValue, false, BfTypeCode_IntPtr), mModule->GetPrimitiveType(BfTypeCode_IntPtr));
  16884. }
  16885. }
  16886. mModule->PopulateType(target.mType);
  16887. if (target.mType->IsSizedArray())
  16888. {
  16889. BfSizedArrayType* sizedArrayType = (BfSizedArrayType*)target.mType;
  16890. auto underlyingType = sizedArrayType->mElementType;
  16891. if (indexArgument.mValue.IsConst())
  16892. {
  16893. auto indexConst = mModule->mBfIRBuilder->GetConstant(indexArgument.mValue);
  16894. if (indexConst->mUInt64 >= (uint64)sizedArrayType->mElementCount)
  16895. {
  16896. if (!mModule->IsInSpecializedSection())
  16897. {
  16898. mModule->Fail(StrFormat("Index '%d' is out of bounds for type '%s'", indexConst->mInt32, mModule->TypeToString(target.mType).c_str()), indexerExpr->mArguments[0]);
  16899. mResult = _GetDefaultResult();
  16900. return;
  16901. }
  16902. else
  16903. {
  16904. // Is this any good?
  16905. mModule->mBfIRBuilder->CreateUnreachable();
  16906. }
  16907. }
  16908. }
  16909. else if (((mModule->HasCompiledOutput()) || (mModule->mIsComptimeModule)) &&
  16910. (wantsChecks))
  16911. {
  16912. if (checkedKind == BfCheckedKind_NotSet)
  16913. checkedKind = mModule->GetDefaultCheckedKind();
  16914. if (checkedKind == BfCheckedKind_Checked)
  16915. {
  16916. auto oobBlock = mModule->mBfIRBuilder->CreateBlock("oob", true);
  16917. auto contBlock = mModule->mBfIRBuilder->CreateBlock("cont", true);
  16918. auto indexType = (BfPrimitiveType*)indexArgument.mType;
  16919. if (!mModule->mSystem->DoesLiteralFit(indexType->mTypeDef->mTypeCode, sizedArrayType->mElementCount))
  16920. {
  16921. // We need to upsize the index so we can compare it against the larger elementCount
  16922. indexType = mModule->GetPrimitiveType(BfTypeCode_IntPtr);
  16923. indexArgument = mModule->Cast(indexerExpr->mArguments[0], indexArgument, indexType);
  16924. }
  16925. auto cmpRes = mModule->mBfIRBuilder->CreateCmpGTE(indexArgument.mValue, mModule->mBfIRBuilder->CreateConst(indexType->mTypeDef->mTypeCode, (uint64)sizedArrayType->mElementCount), false);
  16926. mModule->mBfIRBuilder->CreateCondBr(cmpRes, oobBlock, contBlock);
  16927. mModule->mBfIRBuilder->SetInsertPoint(oobBlock);
  16928. auto internalType = mModule->ResolveTypeDef(mModule->mCompiler->mInternalTypeDef);
  16929. auto oobFunc = mModule->GetMethodByName(internalType->ToTypeInstance(), "ThrowIndexOutOfRange");
  16930. if (oobFunc.mFunc)
  16931. {
  16932. /*if (!mModule->mCompiler->mIsResolveOnly)
  16933. {
  16934. OutputDebugStrF("-OOB %d %d\n", oobFunc.mFunc.mId, oobFunc.mFunc.mFlags);
  16935. }*/
  16936. if (mModule->mIsComptimeModule)
  16937. mModule->mCompiler->mCEMachine->QueueMethod(oobFunc.mMethodInstance, oobFunc.mFunc);
  16938. SizedArray<BfIRValue, 1> args;
  16939. args.push_back(mModule->GetConstValue(0));
  16940. mModule->mBfIRBuilder->CreateCall(oobFunc.mFunc, args);
  16941. mModule->mBfIRBuilder->CreateUnreachable();
  16942. mModule->mBfIRBuilder->SetInsertPoint(contBlock);
  16943. }
  16944. else
  16945. {
  16946. mModule->Fail("System.Internal class must contain method 'ThrowIndexOutOfRange'");
  16947. }
  16948. }
  16949. }
  16950. // If this is a 'bag of bytes', we should try hard not to have to make this addressable
  16951. if ((!target.IsAddr()) && (!target.mType->IsSizeAligned()))
  16952. mModule->MakeAddressable(target);
  16953. mModule->PopulateType(underlyingType);
  16954. if ((sizedArrayType->IsUndefSizedArray()) || (isUndefIndex))
  16955. {
  16956. mResult = mModule->GetDefaultTypedValue(underlyingType, false, BfDefaultValueKind_Addr);
  16957. }
  16958. else if (sizedArrayType->IsValuelessType())
  16959. {
  16960. if (underlyingType->IsValuelessType())
  16961. mResult = BfTypedValue(mModule->mBfIRBuilder->GetFakeVal(), underlyingType, true);
  16962. else
  16963. {
  16964. mResult = mModule->GetDefaultTypedValue(underlyingType, false, BfDefaultValueKind_Addr);
  16965. }
  16966. }
  16967. else if (target.IsAddr())
  16968. {
  16969. if (target.mType->IsSizeAligned())
  16970. {
  16971. auto gepResult = mModule->mBfIRBuilder->CreateInBoundsGEP(target.mValue, mModule->GetConstValue(0), indexArgument.mValue);
  16972. mResult = BfTypedValue(gepResult, underlyingType, target.IsReadOnly() ? BfTypedValueKind_ReadOnlyAddr : BfTypedValueKind_Addr);
  16973. }
  16974. else
  16975. {
  16976. auto indexResult = mModule->CreateIndexedValue(underlyingType, target.mValue, indexArgument.mValue);
  16977. mResult = BfTypedValue(indexResult, underlyingType, target.IsReadOnly() ? BfTypedValueKind_ReadOnlyAddr : BfTypedValueKind_Addr);
  16978. }
  16979. }
  16980. else
  16981. {
  16982. if ((!target.mValue.IsConst()) && (!indexArgument.mValue.IsConst()))
  16983. {
  16984. mModule->Fail("Unable to index value", indexerExpr->mTarget);
  16985. return;
  16986. }
  16987. mModule->mBfIRBuilder->PopulateType(target.mType);
  16988. auto gepResult = mModule->mBfIRBuilder->CreateExtractValue(target.mValue, indexArgument.mValue);
  16989. if ((underlyingType->IsString()) || (underlyingType->IsPointer()))
  16990. {
  16991. auto resultConst = mModule->mBfIRBuilder->GetConstant(gepResult);
  16992. if ((resultConst != NULL) && (resultConst->mTypeCode == BfTypeCode_Int32))
  16993. {
  16994. int strId = resultConst->mInt32;
  16995. const StringImpl& str = mModule->mContext->mStringObjectIdMap[strId].mString;
  16996. if (underlyingType->IsString())
  16997. gepResult = mModule->GetStringObjectValue(str, false);
  16998. else
  16999. gepResult = mModule->GetStringCharPtr(strId);
  17000. }
  17001. }
  17002. mResult = BfTypedValue(gepResult, underlyingType, BfTypedValueKind_Value);
  17003. }
  17004. }
  17005. else
  17006. {
  17007. target = mModule->LoadValue(target);
  17008. BfPointerType* pointerType = (BfPointerType*)target.mType;
  17009. auto underlyingType = pointerType->mElementType;
  17010. mModule->mBfIRBuilder->PopulateType(underlyingType);
  17011. if (isUndefIndex)
  17012. {
  17013. mResult = mModule->GetDefaultTypedValue(underlyingType, false, BfDefaultValueKind_Addr);
  17014. }
  17015. else
  17016. {
  17017. BfIRValue result = mModule->CreateIndexedValue(underlyingType, target.mValue, indexArgument.mValue);
  17018. mResult = BfTypedValue(result, underlyingType, true);
  17019. }
  17020. }
  17021. }
  17022. void BfExprEvaluator::Visit(BfUnaryOperatorExpression* unaryOpExpr)
  17023. {
  17024. BfAutoParentNodeEntry autoParentNodeEntry(mModule, unaryOpExpr);
  17025. PerformUnaryOperation(unaryOpExpr->mExpression, unaryOpExpr->mOp, unaryOpExpr->mOpToken, BfUnaryOpFlag_None);
  17026. }
  17027. void BfExprEvaluator::PerformUnaryOperation(BfExpression* unaryOpExpr, BfUnaryOp unaryOp, BfTokenNode* opToken, BfUnaryOpFlags opFlags)
  17028. {
  17029. {
  17030. // If this is a cast, we don't want the value to be coerced before the unary operator is applied.
  17031. // WAIT: Why not?
  17032. //SetAndRestoreValue<BfType*> prevExpectingType(mExpectingType, NULL);
  17033. BfType* prevExpedcting = mExpectingType;
  17034. switch (unaryOp)
  17035. {
  17036. case BfUnaryOp_Negate:
  17037. case BfUnaryOp_Positive:
  17038. case BfUnaryOp_InvertBits:
  17039. // If we're expecting an int64 or uint64 then just leave the type as unknown
  17040. if ((mExpectingType != NULL) && (mExpectingType->IsInteger()) && (mExpectingType->mSize == 8))
  17041. mExpectingType = NULL;
  17042. // Otherwise keep expecting type
  17043. break;
  17044. default:
  17045. mExpectingType = NULL;
  17046. }
  17047. VisitChild(unaryOpExpr);
  17048. mExpectingType = prevExpedcting;
  17049. }
  17050. BfExprEvaluator::PerformUnaryOperation_OnResult(unaryOpExpr, unaryOp, opToken, opFlags);
  17051. }
  17052. BfTypedValue BfExprEvaluator::PerformUnaryOperation_TryOperator(const BfTypedValue& inValue, BfExpression* unaryOpExpr, BfUnaryOp unaryOp, BfTokenNode* opToken, BfUnaryOpFlags opFlags)
  17053. {
  17054. if ((!inValue.mType->IsTypeInstance()) && (!inValue.mType->IsGenericParam()))
  17055. return BfTypedValue();
  17056. SizedArray<BfResolvedArg, 1> args;
  17057. BfResolvedArg resolvedArg;
  17058. resolvedArg.mTypedValue = inValue;
  17059. args.push_back(resolvedArg);
  17060. BfMethodMatcher methodMatcher(opToken, mModule, "", args, NULL);
  17061. methodMatcher.mBfEvalExprFlags = BfEvalExprFlags_NoAutoComplete;
  17062. methodMatcher.mAllowImplicitRef = true;
  17063. BfBaseClassWalker baseClassWalker(inValue.mType, NULL, mModule);
  17064. BfUnaryOp findOp = unaryOp;
  17065. bool isPostOp = false;
  17066. if (findOp == BfUnaryOp_PostIncrement)
  17067. {
  17068. findOp = BfUnaryOp_Increment;
  17069. isPostOp = true;
  17070. }
  17071. if (findOp == BfUnaryOp_PostDecrement)
  17072. {
  17073. findOp = BfUnaryOp_Decrement;
  17074. isPostOp = true;
  17075. }
  17076. bool isConstraintCheck = ((opFlags & BfUnaryOpFlag_IsConstraintCheck) != 0);
  17077. BfType* operatorConstraintReturnType = NULL;
  17078. BfType* bestSelfType = NULL;
  17079. while (true)
  17080. {
  17081. auto entry = baseClassWalker.Next();
  17082. auto checkType = entry.mTypeInstance;
  17083. if (checkType == NULL)
  17084. break;
  17085. for (auto operatorDef : checkType->mTypeDef->mOperators)
  17086. {
  17087. if (operatorDef->mOperatorDeclaration->mUnaryOp == findOp)
  17088. {
  17089. if (!methodMatcher.IsMemberAccessible(checkType, operatorDef->mDeclaringType))
  17090. continue;
  17091. int prevArgSize = (int)args.mSize;
  17092. if (!operatorDef->mIsStatic)
  17093. {
  17094. // Try without arg
  17095. args.mSize = 0;
  17096. }
  17097. if (isConstraintCheck)
  17098. {
  17099. auto returnType = mModule->CheckOperator(checkType, operatorDef, inValue, BfTypedValue());
  17100. if (returnType != NULL)
  17101. {
  17102. operatorConstraintReturnType = returnType;
  17103. methodMatcher.mBestMethodDef = operatorDef;
  17104. }
  17105. }
  17106. else
  17107. {
  17108. if (methodMatcher.CheckMethod(NULL, checkType, operatorDef, false))
  17109. methodMatcher.mSelfType = entry.mSrcType;
  17110. }
  17111. args.mSize = prevArgSize;
  17112. }
  17113. }
  17114. }
  17115. if (methodMatcher.mBestMethodDef == NULL)
  17116. {
  17117. // Check method generic constraints
  17118. if ((mModule->mCurMethodInstance != NULL) && (mModule->mCurMethodInstance->mIsUnspecialized) && (mModule->mCurMethodInstance->mMethodInfoEx != NULL))
  17119. {
  17120. for (int genericParamIdx = 0; genericParamIdx < mModule->mCurMethodInstance->mMethodInfoEx->mGenericParams.size(); genericParamIdx++)
  17121. {
  17122. auto genericParam = mModule->mCurMethodInstance->mMethodInfoEx->mGenericParams[genericParamIdx];
  17123. for (auto& opConstraint : genericParam->mOperatorConstraints)
  17124. {
  17125. if (opConstraint.mUnaryOp == findOp)
  17126. {
  17127. if (mModule->CanCast(args[0].mTypedValue, opConstraint.mRightType, isConstraintCheck ? BfCastFlags_IsConstraintCheck : BfCastFlags_None))
  17128. {
  17129. return BfTypedValue(mModule->mBfIRBuilder->GetFakeVal(), genericParam->mExternType);
  17130. }
  17131. }
  17132. }
  17133. }
  17134. }
  17135. // Check type generic constraints
  17136. if ((mModule->mCurTypeInstance->IsGenericTypeInstance()) && (mModule->mCurTypeInstance->IsUnspecializedType()))
  17137. {
  17138. auto genericTypeInst = (BfTypeInstance*)mModule->mCurTypeInstance;
  17139. for (int genericParamIdx = 0; genericParamIdx < genericTypeInst->mGenericTypeInfo->mGenericParams.size(); genericParamIdx++)
  17140. {
  17141. auto genericParam = mModule->GetGenericTypeParamInstance(genericParamIdx);
  17142. for (auto& opConstraint : genericParam->mOperatorConstraints)
  17143. {
  17144. if (opConstraint.mUnaryOp == findOp)
  17145. {
  17146. if (mModule->CanCast(args[0].mTypedValue, opConstraint.mRightType, isConstraintCheck ? BfCastFlags_IsConstraintCheck : BfCastFlags_None))
  17147. {
  17148. return BfTypedValue(mModule->mBfIRBuilder->GetFakeVal(), genericParam->mExternType);
  17149. }
  17150. }
  17151. }
  17152. }
  17153. }
  17154. return BfTypedValue();
  17155. }
  17156. if ((!baseClassWalker.mMayBeFromInterface) && (opToken != NULL))
  17157. mModule->SetElementType(opToken, BfSourceElementType_Method);
  17158. auto methodDef = methodMatcher.mBestMethodDef;
  17159. auto autoComplete = GetAutoComplete();
  17160. if ((autoComplete != NULL) && (autoComplete->IsAutocompleteNode(opToken)))
  17161. {
  17162. auto operatorDecl = BfNodeDynCast<BfOperatorDeclaration>(methodDef->mMethodDeclaration);
  17163. if ((operatorDecl != NULL) && (operatorDecl->mOpTypeToken != NULL))
  17164. autoComplete->SetDefinitionLocation(operatorDecl->mOpTypeToken);
  17165. }
  17166. SizedArray<BfExpression*, 2> argSrcs;
  17167. argSrcs.push_back(unaryOpExpr);
  17168. BfTypedValue targetVal = args[0].mTypedValue;
  17169. BfTypedValue postOpVal;
  17170. if (isPostOp)
  17171. postOpVal = mModule->LoadValue(targetVal);
  17172. BfTypedValue callTarget;
  17173. if (!methodMatcher.mBestMethodDef->mIsStatic)
  17174. {
  17175. callTarget = targetVal;
  17176. args.Clear();
  17177. }
  17178. BfTypedValue result;
  17179. if (isConstraintCheck)
  17180. {
  17181. result = BfTypedValue(mModule->mBfIRBuilder->GetFakeVal(), operatorConstraintReturnType);
  17182. }
  17183. else
  17184. {
  17185. SetAndRestoreValue<BfEvalExprFlags> prevFlags(mBfEvalExprFlags, (BfEvalExprFlags)(mBfEvalExprFlags | BfEvalExprFlags_NoAutoComplete));
  17186. result = CreateCall(&methodMatcher, callTarget);
  17187. }
  17188. if (!methodMatcher.mBestMethodDef->mIsStatic)
  17189. {
  17190. if (!isPostOp)
  17191. result = mModule->LoadValue(targetVal);
  17192. }
  17193. else if ((result.mType != NULL) && (methodMatcher.mSelfType != NULL) && (result.mType->IsSelf()))
  17194. {
  17195. BF_ASSERT(mModule->IsInGeneric());
  17196. result = mModule->GetDefaultTypedValue(methodMatcher.mSelfType);
  17197. }
  17198. if ((methodMatcher.mBestMethodInstance) &&
  17199. ((findOp == BfUnaryOp_Increment) || (findOp == BfUnaryOp_Decrement)))
  17200. {
  17201. if (methodMatcher.mBestMethodInstance.mMethodInstance->mIsIntrinsic)
  17202. {
  17203. if (args[0].mTypedValue.IsAddr())
  17204. mModule->mBfIRBuilder->CreateStore(result.mValue, args[0].mTypedValue.mValue);
  17205. else
  17206. {
  17207. mModule->AssertErrorState();
  17208. }
  17209. }
  17210. else
  17211. {
  17212. if (!result.mType->IsValuelessType())
  17213. {
  17214. if (targetVal.IsAddr())
  17215. {
  17216. result = mModule->LoadValue(result);
  17217. mModule->mBfIRBuilder->CreateStore(result.mValue, targetVal.mValue);
  17218. }
  17219. }
  17220. }
  17221. }
  17222. if (postOpVal)
  17223. result = postOpVal;
  17224. return result;
  17225. }
  17226. void BfExprEvaluator::PerformUnaryOperation_OnResult(BfExpression* unaryOpExpr, BfUnaryOp unaryOp, BfTokenNode* opToken, BfUnaryOpFlags opFlags)
  17227. {
  17228. BfAstNode* propSrc = mPropSrc;
  17229. BfTypedValue propTarget = mPropTarget;
  17230. BfPropertyDef* propDef = mPropDef;
  17231. SizedArray<BfResolvedArg, 2> indexerVals = mIndexerValues;
  17232. BfTypedValue writeToProp;
  17233. GetResult();
  17234. if (!mResult)
  17235. return;
  17236. if (mResult.mType->IsRef())
  17237. mResult.mType = mResult.mType->GetUnderlyingType();
  17238. if (mResult.mType->IsVar())
  17239. {
  17240. mResult = BfTypedValue(mModule->GetDefaultValue(mResult.mType), mResult.mType);
  17241. return;
  17242. }
  17243. if (BfCanOverloadOperator(unaryOp))
  17244. {
  17245. auto opResult = PerformUnaryOperation_TryOperator(mResult, unaryOpExpr, unaryOp, opToken, opFlags);
  17246. if (opResult)
  17247. {
  17248. mResult = opResult;
  17249. return;
  17250. }
  17251. }
  17252. bool numericFail = false;
  17253. switch (unaryOp)
  17254. {
  17255. case BfUnaryOp_Not:
  17256. {
  17257. CheckResultForReading(mResult);
  17258. auto boolType = mModule->GetPrimitiveType(BfTypeCode_Boolean);
  17259. auto value = mModule->LoadValue(mResult);
  17260. value = mModule->Cast(unaryOpExpr, value, boolType);
  17261. if (!value)
  17262. {
  17263. mResult = BfTypedValue();
  17264. return;
  17265. }
  17266. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateNot(value.mValue), boolType);
  17267. }
  17268. break;
  17269. case BfUnaryOp_Positive:
  17270. return;
  17271. case BfUnaryOp_Negate:
  17272. {
  17273. CheckResultForReading(mResult);
  17274. auto value = mModule->LoadValue(mResult);
  17275. if (!value)
  17276. {
  17277. mResult = BfTypedValue();
  17278. return;
  17279. }
  17280. BfType* origType = value.mType;
  17281. if (value.mType->IsTypedPrimitive())
  17282. value.mType = value.mType->GetUnderlyingType();
  17283. if (value.mType->IsIntegral())
  17284. {
  17285. auto primType = (BfPrimitiveType*)value.mType;
  17286. auto wantType = primType;
  17287. auto constant = mModule->mBfIRBuilder->GetConstant(value.mValue);
  17288. if ((constant != NULL) && (mModule->mBfIRBuilder->IsInt(constant->mTypeCode)))
  17289. {
  17290. if ((primType->mTypeDef->mTypeCode == BfTypeCode_UInt32) && (constant->mInt64 == 0x80000000LL))
  17291. {
  17292. mResult = BfTypedValue(mModule->GetConstValue32(-0x80000000LL), mModule->GetPrimitiveType(BfTypeCode_Int32));
  17293. return;
  17294. }
  17295. else if ((primType->mTypeDef->mTypeCode == BfTypeCode_UInt64) && (constant->mInt64 == 0x8000000000000000LL))
  17296. {
  17297. mResult = BfTypedValue(mModule->GetConstValue64(-0x8000000000000000LL), mModule->GetPrimitiveType(BfTypeCode_Int64));
  17298. return;
  17299. }
  17300. }
  17301. /*if (auto constantInt = dyn_cast<ConstantInt>((Value*)value.mValue))
  17302. {
  17303. int64 i64Val = constantInt->getSExtValue();
  17304. // This is a special case where the user entered -0x80000000 (maxint) but we thought "0x80000000" was a uint in the parser
  17305. // which would get upcasted to an int64 for this negate. Properly bring back down to an int32
  17306. if ((primType->mTypeDef->mTypeCode == BfTypeCode_UInt32) && (i64Val == -0x80000000LL))
  17307. {
  17308. mResult = BfTypedValue(mModule->GetConstValue((int)i64Val), mModule->GetPrimitiveType(BfTypeCode_Int32));
  17309. return;
  17310. }
  17311. }*/
  17312. if (!primType->IsSigned())
  17313. {
  17314. if (primType->mSize == 1)
  17315. wantType = mModule->GetPrimitiveType(BfTypeCode_Int16);
  17316. else if (primType->mSize == 2)
  17317. wantType = mModule->GetPrimitiveType(BfTypeCode_Int32);
  17318. else if (primType->mSize == 4)
  17319. wantType = mModule->GetPrimitiveType(BfTypeCode_Int64);
  17320. else
  17321. mModule->Fail("Operator '-' cannot be applied to uint64", opToken);
  17322. }
  17323. if (primType != wantType)
  17324. {
  17325. value = mModule->Cast(unaryOpExpr, value, wantType, BfCastFlags_Explicit);
  17326. if (!value)
  17327. {
  17328. mResult = BfTypedValue();
  17329. return;
  17330. }
  17331. }
  17332. if (origType->mSize == wantType->mSize) // Allow negative of primitive typed but not if we had to upsize
  17333. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateNeg(value.mValue), origType);
  17334. else
  17335. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateNeg(value.mValue), wantType);
  17336. }
  17337. else if (value.mType->IsFloat())
  17338. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateNeg(value.mValue), origType);
  17339. else
  17340. numericFail = true;
  17341. }
  17342. break;
  17343. case BfUnaryOp_InvertBits:
  17344. {
  17345. CheckResultForReading(mResult);
  17346. auto value = mModule->LoadValue(mResult);
  17347. if (!value)
  17348. return;
  17349. bool isInteger = value.mType->IsIntegral();
  17350. if (value.mType->IsTypedPrimitive())
  17351. isInteger = value.mType->GetUnderlyingType()->IsIntegral();
  17352. if (!isInteger)
  17353. {
  17354. mResult = BfTypedValue();
  17355. mModule->Fail("Operator can only be used on integer types", opToken);
  17356. return;
  17357. }
  17358. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateNot(value.mValue), value.mType);
  17359. }
  17360. break;
  17361. case BfUnaryOp_AddressOf:
  17362. {
  17363. MarkResultUsed();
  17364. mModule->FixIntUnknown(mResult);
  17365. mModule->PopulateType(mResult.mType);
  17366. auto ptrType = mModule->CreatePointerType(mResult.mType);
  17367. if (mResult.mType->IsValuelessType())
  17368. {
  17369. // Sentinel value
  17370. auto val = mModule->mBfIRBuilder->CreateIntToPtr(mModule->mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, 1), mModule->mBfIRBuilder->MapType(ptrType));
  17371. mResult = BfTypedValue(val, ptrType);
  17372. }
  17373. else if (!CheckModifyResult(mResult, unaryOpExpr, "take address of", false, true))
  17374. {
  17375. if (!mResult.IsAddr())
  17376. mResult = mModule->MakeAddressable(mResult);
  17377. mResult = BfTypedValue(mResult.mValue, ptrType, false);
  17378. }
  17379. else
  17380. mResult = BfTypedValue(mResult.mValue, ptrType, false);
  17381. }
  17382. break;
  17383. case BfUnaryOp_Dereference:
  17384. {
  17385. CheckResultForReading(mResult);
  17386. if (!mResult.mType->IsPointer())
  17387. {
  17388. mResult = BfTypedValue();
  17389. mModule->Fail("Cannot dereference non-pointer type", unaryOpExpr);
  17390. return;
  17391. }
  17392. if (mResult.mValue.IsConst())
  17393. {
  17394. auto constant = mModule->mBfIRBuilder->GetConstant(mResult.mValue);
  17395. bool isNull = constant->mTypeCode == BfTypeCode_NullPtr;
  17396. if (constant->mConstType == BfConstType_ExtractValue)
  17397. {
  17398. auto constExtract = (BfConstantExtractValue*)constant;
  17399. auto targetConst = mModule->mBfIRBuilder->GetConstantById(constExtract->mTarget);
  17400. if (targetConst->mConstType == BfConstType_AggZero)
  17401. isNull = true;
  17402. }
  17403. if (isNull)
  17404. {
  17405. mModule->Warn(0, "Cannot dereference a null pointer", unaryOpExpr);
  17406. mResult = mModule->GetDefaultTypedValue(mResult.mType, false, BfDefaultValueKind_Addr);
  17407. mResult = mModule->LoadValue(mResult);
  17408. }
  17409. }
  17410. auto derefTarget = mModule->LoadValue(mResult);
  17411. BfPointerType* pointerType = (BfPointerType*)derefTarget.mType;
  17412. auto resolvedType = mModule->ResolveType(pointerType->mElementType);
  17413. if (resolvedType == NULL)
  17414. {
  17415. mResult = BfTypedValue();
  17416. return;
  17417. }
  17418. mModule->PopulateType(resolvedType);
  17419. if (resolvedType->IsValuelessType())
  17420. mResult = BfTypedValue(mModule->mBfIRBuilder->GetFakeVal(), resolvedType, true);
  17421. else
  17422. mResult = BfTypedValue(derefTarget.mValue, resolvedType, true);
  17423. }
  17424. break;
  17425. case BfUnaryOp_PostIncrement:
  17426. case BfUnaryOp_Increment:
  17427. {
  17428. CheckResultForReading(mResult);
  17429. auto ptr = mResult;
  17430. //if ((propDef == NULL) && (!mModule->CheckModifyValue(ptr, opToken)))
  17431. if ((propDef == NULL) && (!CheckModifyResult(ptr, opToken, "increment")))
  17432. return;
  17433. BfTypedValue origTypedVal = mModule->LoadValue(ptr, NULL, mIsVolatileReference);
  17434. BfIRValue origVal = origTypedVal.mValue;
  17435. BfIRValue constValue = mModule->GetConstValue(1, ptr.mType);
  17436. BfIRValue resultValue;
  17437. if (ptr.mType->IsPointer())
  17438. {
  17439. BfPointerType* ptrType = (BfPointerType*)ptr.mType;
  17440. BfType* intPtrType = mModule->GetPrimitiveType(BfTypeCode_IntPtr);
  17441. constValue = mModule->GetConstValue(ptrType->mElementType->GetStride(), intPtrType);
  17442. auto i8PtrType = mModule->mBfIRBuilder->GetPointerTo(mModule->mBfIRBuilder->GetPrimitiveType(BfTypeCode_Int8));
  17443. BfIRValue origPtrValue = mModule->mBfIRBuilder->CreateBitCast(origVal, i8PtrType);
  17444. BfIRValue newPtrValue = mModule->mBfIRBuilder->CreateInBoundsGEP(origPtrValue, constValue);
  17445. resultValue = mModule->mBfIRBuilder->CreateBitCast(newPtrValue, mModule->mBfIRBuilder->MapType(ptr.mType));
  17446. }
  17447. else
  17448. {
  17449. constValue = mModule->GetConstValue(1, ptr.mType);
  17450. if (!constValue)
  17451. {
  17452. numericFail = true;
  17453. break;
  17454. }
  17455. if ((ptr.mType->IsIntegral()) || (ptr.mType->IsEnum()) || (ptr.mType->IsFloat()))
  17456. {
  17457. resultValue = mModule->mBfIRBuilder->CreateAdd(origVal, constValue/*, "inc"*/);
  17458. }
  17459. else
  17460. {
  17461. numericFail = true;
  17462. break;
  17463. }
  17464. }
  17465. if ((propDef != NULL) && (!ptr.IsAddr()))
  17466. writeToProp = BfTypedValue(resultValue, ptr.mType);
  17467. else
  17468. mModule->mBfIRBuilder->CreateStore(resultValue, ptr.mValue, mIsVolatileReference);
  17469. if (unaryOp == BfUnaryOp_PostIncrement)
  17470. mResult = BfTypedValue(origVal, ptr.mType, false);
  17471. else
  17472. mResult = BfTypedValue(resultValue, ptr.mType, false);
  17473. }
  17474. break;
  17475. case BfUnaryOp_PostDecrement:
  17476. case BfUnaryOp_Decrement:
  17477. {
  17478. CheckResultForReading(mResult);
  17479. auto ptr = mResult;
  17480. //if ((propDef == NULL) && (!mModule->CheckModifyValue(ptr, opToken)))
  17481. //return;
  17482. if ((propDef == NULL) && (!CheckModifyResult(ptr, opToken, "decrement")))
  17483. return;
  17484. BfTypedValue origTypedVal = mModule->LoadValue(ptr, NULL, mIsVolatileReference);
  17485. BfIRValue origVal = origTypedVal.mValue;
  17486. BfIRValue constValue = mModule->GetConstValue(1, ptr.mType);
  17487. BfIRValue resultValue;
  17488. if (ptr.mType->IsPointer())
  17489. {
  17490. BfPointerType* ptrType = (BfPointerType*)ptr.mType;
  17491. BfType* intPtrType = mModule->GetPrimitiveType(BfTypeCode_IntPtr);
  17492. constValue = mModule->GetConstValue(-ptrType->mElementType->GetStride(), intPtrType);
  17493. auto i8PtrType = mModule->mBfIRBuilder->GetPointerTo(mModule->mBfIRBuilder->GetPrimitiveType(BfTypeCode_Int8));
  17494. BfIRValue origPtrValue = mModule->mBfIRBuilder->CreateBitCast(origVal, i8PtrType);
  17495. BfIRValue newPtrValue = mModule->mBfIRBuilder->CreateInBoundsGEP(origPtrValue, constValue);
  17496. resultValue = mModule->mBfIRBuilder->CreateBitCast(newPtrValue, mModule->mBfIRBuilder->MapType(ptr.mType));
  17497. }
  17498. else
  17499. {
  17500. BfIRValue constValue = mModule->GetConstValue(1, ptr.mType);
  17501. if (!constValue)
  17502. {
  17503. numericFail = true;
  17504. break;
  17505. }
  17506. if ((ptr.mType->IsIntegral()) || (ptr.mType->IsEnum()))
  17507. {
  17508. resultValue = mModule->mBfIRBuilder->CreateSub(origVal, constValue);
  17509. }
  17510. else if (ptr.mType->IsFloat())
  17511. {
  17512. resultValue = mModule->mBfIRBuilder->CreateSub(origVal, constValue);
  17513. }
  17514. else
  17515. {
  17516. numericFail = true;
  17517. break;
  17518. }
  17519. }
  17520. if ((propDef != NULL) && (!ptr.IsAddr()))
  17521. writeToProp = BfTypedValue(resultValue, ptr.mType);
  17522. else
  17523. mModule->mBfIRBuilder->CreateStore(resultValue, ptr.mValue, mIsVolatileReference);
  17524. if (unaryOp == BfUnaryOp_PostDecrement)
  17525. mResult = BfTypedValue(origVal, ptr.mType, false);
  17526. else
  17527. mResult = BfTypedValue(resultValue, ptr.mType, false);
  17528. }
  17529. break;
  17530. case BfUnaryOp_Ref:
  17531. case BfUnaryOp_Mut:
  17532. {
  17533. if (mAllowReadOnlyReference)
  17534. {
  17535. if (mResult.mKind == BfTypedValueKind_ReadOnlyAddr)
  17536. mResult.mKind = BfTypedValueKind_Addr;
  17537. }
  17538. CheckResultForReading(mResult);
  17539. if ((unaryOp == BfUnaryOp_Mut) && (!mResult.mType->IsComposite()) && (!mResult.mType->IsGenericParam()))
  17540. {
  17541. // Non-composite types are already mutable, leave them alone...
  17542. break;
  17543. }
  17544. if ((unaryOp != BfUnaryOp_Mut) || (mResult.mKind != BfTypedValueKind_MutableValue))
  17545. {
  17546. if (!CheckModifyResult(mResult, unaryOpExpr, StrFormat("use '%s' on", BfGetOpName(unaryOp)).c_str()))
  17547. {
  17548. // Just leave the non-ref version in mResult
  17549. return;
  17550. }
  17551. }
  17552. if ((mBfEvalExprFlags & BfEvalExprFlags_AllowRefExpr) == 0)
  17553. {
  17554. mResult = BfTypedValue();
  17555. mModule->Fail(StrFormat("Invalid usage of '%s' expression", BfGetOpName(unaryOp)), opToken);
  17556. return;
  17557. }
  17558. ResolveGenericType();
  17559. if (mResult.mType->IsVar())
  17560. break;
  17561. mResult = BfTypedValue(mResult.mValue, mModule->CreateRefType(mResult.mType, (unaryOp == BfUnaryOp_Ref) ? BfRefType::RefKind_Ref : BfRefType::RefKind_Mut));
  17562. }
  17563. break;
  17564. case BfUnaryOp_Out:
  17565. {
  17566. if (!CheckModifyResult(mResult, unaryOpExpr, "use 'out' on"))
  17567. {
  17568. // Just leave the non-ref version in mResult
  17569. return;
  17570. }
  17571. if ((mBfEvalExprFlags & BfEvalExprFlags_AllowOutExpr) == 0)
  17572. {
  17573. mModule->Fail("Invalid usage of 'out' expression", opToken);
  17574. return;
  17575. }
  17576. if (mInsidePendingNullable)
  17577. {
  17578. // 'out' inside null conditionals never actually causes a definite assignment...
  17579. }
  17580. else
  17581. MarkResultAssigned();
  17582. MarkResultUsed();
  17583. ResolveGenericType();
  17584. if (mResult.mType->IsVar())
  17585. break;
  17586. mResult = BfTypedValue(mResult.mValue, mModule->CreateRefType(mResult.mType, BfRefType::RefKind_Out));
  17587. }
  17588. break;
  17589. case BfUnaryOp_Params:
  17590. {
  17591. bool allowParams = (mBfEvalExprFlags & BfEvalExprFlags_AllowParamsExpr) != 0;
  17592. if (allowParams)
  17593. {
  17594. if ((mResultLocalVar != NULL) && (mResultLocalVar->mCompositeCount >= 0)) // Delegate params
  17595. {
  17596. allowParams = true;
  17597. }
  17598. else
  17599. {
  17600. auto isValid = false;
  17601. auto genericTypeInst = mResult.mType->ToGenericTypeInstance();
  17602. if ((genericTypeInst != NULL) && (genericTypeInst->mTypeDef == mModule->mCompiler->mSpanTypeDef))
  17603. isValid = true;
  17604. else if (mResult.mType->IsArray())
  17605. isValid = true;
  17606. if (!isValid)
  17607. {
  17608. mModule->Fail(StrFormat("A 'params' expression cannot be used on type '%s'", mModule->TypeToString(mResult.mType).c_str()), opToken);
  17609. }
  17610. }
  17611. }
  17612. if (allowParams)
  17613. {
  17614. mResult = mModule->LoadValue(mResult);
  17615. if (mResult.IsSplat())
  17616. mResult.mKind = BfTypedValueKind_ParamsSplat;
  17617. else
  17618. mResult.mKind = BfTypedValueKind_Params;
  17619. }
  17620. else
  17621. {
  17622. mModule->Fail("Illegal use of 'params' expression", opToken);
  17623. }
  17624. }
  17625. break;
  17626. case BfUnaryOp_Cascade:
  17627. {
  17628. mModule->Fail("Illegal use of argument cascade expression", opToken);
  17629. }
  17630. break;
  17631. default:
  17632. mModule->Fail("INTERNAL ERROR: Unhandled unary operator", unaryOpExpr);
  17633. break;
  17634. }
  17635. if (numericFail)
  17636. {
  17637. if (opToken == NULL)
  17638. {
  17639. BF_ASSERT(mModule->mBfIRBuilder->mIgnoreWrites);
  17640. }
  17641. else if ((mResult.mType != NULL) && (mResult.mType->IsInterface()))
  17642. {
  17643. mModule->Fail(
  17644. StrFormat("Operator '%s' cannot be used on interface '%s'. Consider rewriting using generics and use this interface as a generic constraint.",
  17645. BfTokenToString(opToken->mToken), mModule->TypeToString(mResult.mType).c_str()), opToken);
  17646. }
  17647. else
  17648. {
  17649. mModule->Fail(
  17650. StrFormat("Operator '%s' cannot be used because type '%s' is neither a numeric type nor does it define an applicable operator overload",
  17651. BfTokenToString(opToken->mToken), mModule->TypeToString(mResult.mType).c_str()), opToken);
  17652. }
  17653. mResult = BfTypedValue();
  17654. }
  17655. if (writeToProp)
  17656. {
  17657. auto setMethod = GetPropertyMethodDef(propDef, BfMethodType_PropertySetter, mPropCheckedKind, mPropTarget);
  17658. if (setMethod == NULL)
  17659. {
  17660. mModule->Fail("Property has no setter", propSrc);
  17661. return;
  17662. }
  17663. auto methodInstance = GetPropertyMethodInstance(setMethod);
  17664. if (!methodInstance.mFunc)
  17665. return;
  17666. if (propSrc != NULL)
  17667. mModule->UpdateExprSrcPos(propSrc);
  17668. SizedArray<BfIRValue, 4> args;
  17669. if (!setMethod->mIsStatic)
  17670. PushThis(propSrc, propTarget, methodInstance.mMethodInstance, args);
  17671. //args.push_back(propTarget.mValue);
  17672. for (int paramIdx = 0; paramIdx < (int)indexerVals.size(); paramIdx++)
  17673. {
  17674. auto val = mModule->Cast(propSrc, indexerVals[paramIdx].mTypedValue, methodInstance.mMethodInstance->GetParamType(paramIdx));
  17675. if (!val)
  17676. return;
  17677. PushArg(val, args);
  17678. }
  17679. PushArg(writeToProp, args);
  17680. CreateCall(opToken, methodInstance.mMethodInstance, methodInstance.mFunc, false, args);
  17681. }
  17682. }
  17683. void BfExprEvaluator::PerformBinaryOperation(BfExpression* leftExpression, BfExpression* rightExpression, BfBinaryOp binaryOp, BfTokenNode* opToken, BfBinOpFlags flags, BfTypedValue leftValue)
  17684. {
  17685. BfTypedValue rightValue;
  17686. if (rightExpression == NULL)
  17687. {
  17688. mModule->AssertErrorState();
  17689. return;
  17690. }
  17691. if (!leftValue)
  17692. {
  17693. if (!rightValue)
  17694. mModule->CreateValueFromExpression(rightExpression, mExpectingType, (BfEvalExprFlags)(mBfEvalExprFlags & BfEvalExprFlags_InheritFlags));
  17695. return;
  17696. }
  17697. if (leftValue.mType->IsRef())
  17698. leftValue.mType = leftValue.mType->GetUnderlyingType();
  17699. if ((binaryOp == BfBinaryOp_ConditionalAnd) || (binaryOp == BfBinaryOp_ConditionalOr))
  17700. {
  17701. if (mModule->mCurMethodState->mDeferredLocalAssignData != NULL)
  17702. mModule->mCurMethodState->mDeferredLocalAssignData->BreakExtendChain();
  17703. if (mModule->mCurMethodState->mCurScope->mScopeKind == BfScopeKind_StatementTarget)
  17704. mModule->mCurMethodState->mCurScope->mScopeKind = BfScopeKind_StatementTarget_Conditional;
  17705. bool isAnd = binaryOp == BfBinaryOp_ConditionalAnd;
  17706. auto boolType = mModule->GetPrimitiveType(BfTypeCode_Boolean);
  17707. leftValue = mModule->Cast(leftExpression, leftValue, boolType);
  17708. if (!leftValue)
  17709. {
  17710. mModule->CreateValueFromExpression(rightExpression);
  17711. return;
  17712. }
  17713. auto prevBB = mModule->mBfIRBuilder->GetInsertBlock();
  17714. SetAndRestoreValue<bool> prevInCondBlock(mModule->mCurMethodState->mInConditionalBlock, true);
  17715. // The RHS is not guaranteed to be executed
  17716. if ((mModule->mCurMethodState->mDeferredLocalAssignData != NULL) &&
  17717. (mModule->mCurMethodState->mDeferredLocalAssignData->mIsIfCondition))
  17718. mModule->mCurMethodState->mDeferredLocalAssignData->mIfMayBeSkipped = true;
  17719. if (isAnd)
  17720. {
  17721. bool isConstBranch = false;
  17722. bool constResult = false;
  17723. if (leftValue.mValue.IsConst())
  17724. {
  17725. auto constValue = mModule->mBfIRBuilder->GetConstant(leftValue.mValue);
  17726. if (constValue->mTypeCode == BfTypeCode_Boolean)
  17727. {
  17728. isConstBranch = true;
  17729. constResult = constValue->mBool;
  17730. }
  17731. }
  17732. if (isConstBranch)
  17733. {
  17734. if ((constResult) || (HasVariableDeclaration(rightExpression)))
  17735. {
  17736. // Only right side
  17737. rightValue = mModule->CreateValueFromExpression(rightExpression, boolType, (BfEvalExprFlags)(mBfEvalExprFlags & BfEvalExprFlags_InheritFlags));
  17738. mResult = rightValue;
  17739. }
  17740. else
  17741. {
  17742. // Always false
  17743. SetAndRestoreValue<bool> prevIgnoreWrites(mModule->mBfIRBuilder->mIgnoreWrites, true);
  17744. rightValue = mModule->CreateValueFromExpression(rightExpression, boolType, (BfEvalExprFlags)(mBfEvalExprFlags & BfEvalExprFlags_InheritFlags));
  17745. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConst(BfTypeCode_Boolean, 0), boolType);
  17746. }
  17747. }
  17748. else
  17749. {
  17750. auto rhsBB = mModule->mBfIRBuilder->CreateBlock("land.rhs");
  17751. auto endBB = mModule->mBfIRBuilder->CreateBlock("land.end");
  17752. // This makes any 'scope' allocs be dyn since we aren't sure if this will be short-circuited
  17753. SetAndRestoreValue<bool> prevIsConditional(mModule->mCurMethodState->mCurScope->mIsConditional, true);
  17754. mModule->mBfIRBuilder->CreateCondBr(leftValue.mValue, rhsBB, endBB);
  17755. mModule->AddBasicBlock(rhsBB);
  17756. rightValue = mModule->CreateValueFromExpression(rightExpression, boolType, (BfEvalExprFlags)(mBfEvalExprFlags & BfEvalExprFlags_InheritFlags));
  17757. mModule->mBfIRBuilder->CreateBr(endBB);
  17758. auto endRhsBB = mModule->mBfIRBuilder->GetInsertBlock();
  17759. mModule->AddBasicBlock(endBB);
  17760. auto phi = mModule->mBfIRBuilder->CreatePhi(mModule->mBfIRBuilder->MapType(boolType), 2);
  17761. mModule->mBfIRBuilder->AddPhiIncoming(phi, mModule->GetConstValue(0, boolType), prevBB);
  17762. if (rightValue)
  17763. mModule->mBfIRBuilder->AddPhiIncoming(phi, rightValue.mValue, endRhsBB);
  17764. mResult = BfTypedValue(phi, boolType);
  17765. }
  17766. }
  17767. else
  17768. {
  17769. // Put variables in here into a 'possibly assigned' but never commit it.
  17770. // Because if we had "if ((Get(out a)) || (GetOther(out a))" then the LHS would already set it as defined, so
  17771. // the RHS is inconsequential
  17772. BfDeferredLocalAssignData deferredLocalAssignData;
  17773. deferredLocalAssignData.ExtendFrom(mModule->mCurMethodState->mDeferredLocalAssignData, false);
  17774. deferredLocalAssignData.mVarIdBarrier = mModule->mCurMethodState->GetRootMethodState()->mCurLocalVarId;
  17775. SetAndRestoreValue<BfDeferredLocalAssignData*> prevDLA(mModule->mCurMethodState->mDeferredLocalAssignData, &deferredLocalAssignData);
  17776. bool isConstBranch = false;
  17777. bool constResult = false;
  17778. if (leftValue.mValue.IsConst())
  17779. {
  17780. auto constValue = mModule->mBfIRBuilder->GetConstant(leftValue.mValue);
  17781. if (constValue->mTypeCode == BfTypeCode_Boolean)
  17782. {
  17783. isConstBranch = true;
  17784. constResult = constValue->mBool;
  17785. }
  17786. }
  17787. if (isConstBranch)
  17788. {
  17789. if ((constResult) && (!HasVariableDeclaration(rightExpression)))
  17790. {
  17791. // Always true
  17792. SetAndRestoreValue<bool> prevIgnoreWrites(mModule->mBfIRBuilder->mIgnoreWrites, true);
  17793. rightValue = mModule->CreateValueFromExpression(rightExpression, boolType, (BfEvalExprFlags)(mBfEvalExprFlags & BfEvalExprFlags_InheritFlags));
  17794. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConst(BfTypeCode_Boolean, 1), boolType);
  17795. }
  17796. else
  17797. {
  17798. // Only right side
  17799. rightValue = mModule->CreateValueFromExpression(rightExpression, boolType, (BfEvalExprFlags)(mBfEvalExprFlags & BfEvalExprFlags_InheritFlags));
  17800. mResult = rightValue;
  17801. }
  17802. }
  17803. else
  17804. {
  17805. auto rhsBB = mModule->mBfIRBuilder->CreateBlock("lor.rhs");
  17806. auto endBB = mModule->mBfIRBuilder->CreateBlock("lor.end");
  17807. // This makes any 'scope' allocs be dyn since we aren't sure if this will be short-circuited
  17808. SetAndRestoreValue<bool> prevIsConditional(mModule->mCurMethodState->mCurScope->mIsConditional, true);
  17809. mModule->mBfIRBuilder->CreateCondBr(leftValue.mValue, endBB, rhsBB);
  17810. mModule->AddBasicBlock(rhsBB);
  17811. rightValue = mModule->CreateValueFromExpression(rightExpression, boolType, (BfEvalExprFlags)(mBfEvalExprFlags & BfEvalExprFlags_InheritFlags));
  17812. mModule->mBfIRBuilder->CreateBr(endBB);
  17813. auto endRhsBB = mModule->mBfIRBuilder->GetInsertBlock();
  17814. mModule->AddBasicBlock(endBB);
  17815. auto phi = mModule->mBfIRBuilder->CreatePhi(mModule->mBfIRBuilder->MapType(boolType), 2);
  17816. mModule->mBfIRBuilder->AddPhiIncoming(phi, mModule->GetConstValue(1, boolType), prevBB);
  17817. if (rightValue)
  17818. mModule->mBfIRBuilder->AddPhiIncoming(phi, rightValue.mValue, endRhsBB);
  17819. mResult = BfTypedValue(phi, boolType);
  17820. }
  17821. }
  17822. return;
  17823. }
  17824. BfType* wantType = leftValue.mType;
  17825. if ((binaryOp == BfBinaryOp_LeftShift) || (binaryOp == BfBinaryOp_RightShift))
  17826. wantType = NULL; // Don't presume
  17827. wantType = mModule->FixIntUnknown(wantType);
  17828. rightValue = mModule->CreateValueFromExpression(rightExpression, wantType, (BfEvalExprFlags)((mBfEvalExprFlags & BfEvalExprFlags_InheritFlags) | BfEvalExprFlags_NoCast));
  17829. if ((!leftValue) || (!rightValue))
  17830. return;
  17831. PerformBinaryOperation(leftExpression, rightExpression, binaryOp, opToken, flags, leftValue, rightValue);
  17832. }
  17833. void BfExprEvaluator::PerformBinaryOperation(BfExpression* leftExpression, BfExpression* rightExpression, BfBinaryOp binaryOp, BfTokenNode* opToken, BfBinOpFlags flags)
  17834. {
  17835. BfTypedValue leftValue;
  17836. if (leftExpression != NULL)
  17837. {
  17838. leftValue = mModule->CreateValueFromExpression(leftExpression, mExpectingType, (BfEvalExprFlags)((mBfEvalExprFlags & BfEvalExprFlags_InheritFlags) | BfEvalExprFlags_NoCast | BfEvalExprFlags_AllowIntUnknown));
  17839. }
  17840. return PerformBinaryOperation(leftExpression, rightExpression, binaryOp, opToken, flags, leftValue);
  17841. }
  17842. bool BfExprEvaluator::CheckConstCompare(BfBinaryOp binaryOp, BfAstNode* opToken, const BfTypedValue& leftValue, const BfTypedValue& rightValue)
  17843. {
  17844. if ((binaryOp < BfBinaryOp_Equality) || (binaryOp > BfBinaryOp_LessThanOrEqual))
  17845. return false;
  17846. // LHS is expected to be a value and RHS is expected to be a const
  17847. if (!leftValue.mType->IsIntegral())
  17848. return false;
  17849. BF_ASSERT(rightValue.mValue.IsConst());
  17850. auto rightConst = mModule->mBfIRBuilder->GetConstant(rightValue.mValue);
  17851. if (!mModule->mBfIRBuilder->IsInt(rightConst->mTypeCode))
  17852. return false;
  17853. BfType* checkType = leftValue.mType;
  17854. if (checkType->IsTypedPrimitive())
  17855. checkType = checkType->GetUnderlyingType();
  17856. if (!checkType->IsPrimitiveType())
  17857. return false;
  17858. BfTypeCode typeCode = ((BfPrimitiveType*)checkType)->mTypeDef->mTypeCode;
  17859. int64 minValue = 0;
  17860. int64 maxValue = 0;
  17861. switch (typeCode)
  17862. {
  17863. case BfTypeCode_Int8:
  17864. minValue = -0x80;
  17865. maxValue = 0x7F;
  17866. break;
  17867. case BfTypeCode_Int16:
  17868. minValue = -0x8000;
  17869. maxValue = 0x7FFF;
  17870. break;
  17871. case BfTypeCode_Int32:
  17872. minValue = -0x80000000LL;
  17873. maxValue = 0x7FFFFFFF;
  17874. break;
  17875. case BfTypeCode_Int64:
  17876. minValue = -0x8000000000000000LL;
  17877. maxValue = 0x7FFFFFFFFFFFFFFFLL;
  17878. break;
  17879. case BfTypeCode_UInt8:
  17880. maxValue = 0xFF;
  17881. break;
  17882. case BfTypeCode_UInt16:
  17883. maxValue = 0xFFFF;
  17884. break;
  17885. case BfTypeCode_UInt32:
  17886. maxValue = 0xFFFFFFFF;
  17887. break;
  17888. default:
  17889. return false;
  17890. }
  17891. int constResult = -1;
  17892. if (typeCode == BfTypeCode_UInt64)
  17893. {
  17894. switch (binaryOp)
  17895. {
  17896. case BfBinaryOp_Equality:
  17897. case BfBinaryOp_StrictEquality:
  17898. if (rightConst->mInt64 < minValue)
  17899. constResult = 0;
  17900. break;
  17901. case BfBinaryOp_InEquality:
  17902. case BfBinaryOp_StrictInEquality:
  17903. if (rightConst->mInt64 < minValue)
  17904. constResult = 1;
  17905. break;
  17906. case BfBinaryOp_LessThan:
  17907. if (rightConst->mInt64 <= minValue)
  17908. constResult = 0;
  17909. break;
  17910. case BfBinaryOp_LessThanOrEqual:
  17911. if (rightConst->mInt64 < minValue)
  17912. constResult = 0;
  17913. break;
  17914. default: break;
  17915. }
  17916. return false;
  17917. }
  17918. else
  17919. {
  17920. switch (binaryOp)
  17921. {
  17922. case BfBinaryOp_Equality:
  17923. case BfBinaryOp_StrictEquality:
  17924. if (rightConst->mInt64 < minValue)
  17925. constResult = 0;
  17926. else if (rightConst->mInt64 > maxValue)
  17927. constResult = 0;
  17928. break;
  17929. case BfBinaryOp_InEquality:
  17930. case BfBinaryOp_StrictInEquality:
  17931. if (rightConst->mInt64 < minValue)
  17932. constResult = 1;
  17933. else if (rightConst->mInt64 > maxValue)
  17934. constResult = 1;
  17935. break;
  17936. case BfBinaryOp_LessThan:
  17937. if (rightConst->mInt64 <= minValue)
  17938. constResult = 0;
  17939. else if (rightConst->mInt64 > maxValue)
  17940. constResult = 1;
  17941. break;
  17942. case BfBinaryOp_LessThanOrEqual:
  17943. if (rightConst->mInt64 < minValue)
  17944. constResult = 0;
  17945. else if (rightConst->mInt64 >= maxValue)
  17946. constResult = 1;
  17947. break;
  17948. case BfBinaryOp_GreaterThan:
  17949. if (rightConst->mInt64 >= maxValue)
  17950. constResult = 0;
  17951. else if (rightConst->mInt64 < minValue)
  17952. constResult = 1;
  17953. break;
  17954. case BfBinaryOp_GreaterThanOrEqual:
  17955. if (rightConst->mInt64 > maxValue)
  17956. constResult = 0;
  17957. else if (rightConst->mInt64 <= minValue)
  17958. constResult = 1;
  17959. break;
  17960. default: break;
  17961. }
  17962. }
  17963. if (constResult == 0)
  17964. {
  17965. mModule->Warn(0, "The result of this operation is always 'false'", opToken);
  17966. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConst(BfTypeCode_Boolean, 1), mModule->GetPrimitiveType(BfTypeCode_Boolean));
  17967. return true;
  17968. }
  17969. else if (constResult == 1)
  17970. {
  17971. mModule->Warn(0, "The result of this operation is always 'true'", opToken);
  17972. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConst(BfTypeCode_Boolean, 1), mModule->GetPrimitiveType(BfTypeCode_Boolean));
  17973. return true;
  17974. }
  17975. return false;
  17976. }
  17977. void BfExprEvaluator::AddStrings(const BfTypedValue& leftValue, const BfTypedValue& rightValue, BfAstNode* refNode)
  17978. {
  17979. if ((leftValue.mValue.IsConst()) && (rightValue.mValue.IsConst()))
  17980. {
  17981. String* lhsStr = mModule->GetStringPoolString(leftValue.mValue, mModule->mBfIRBuilder);
  17982. String* rhsStr = mModule->GetStringPoolString(rightValue.mValue, mModule->mBfIRBuilder);
  17983. if ((lhsStr != NULL) && (rhsStr != NULL))
  17984. {
  17985. String resultStr = *lhsStr + *rhsStr;
  17986. BfVariant variant;
  17987. variant.mTypeCode = BfTypeCode_CharPtr;
  17988. variant.mString = &resultStr;
  17989. GetLiteral(refNode, variant);
  17990. return;
  17991. }
  17992. }
  17993. mModule->Fail("Strings can only be added when they are constants. Consider allocating a string and using Concat.", refNode);
  17994. return;
  17995. }
  17996. void BfExprEvaluator::PerformBinaryOperation(BfAstNode* leftExpression, BfAstNode* rightExpression, BfBinaryOp binaryOp, BfAstNode* opToken, BfBinOpFlags flags, BfTypedValue leftValue, BfTypedValue rightValue)
  17997. {
  17998. bool noClassify = (flags & BfBinOpFlag_NoClassify) != 0;
  17999. bool forceLeftType = (flags & BfBinOpFlag_ForceLeftType) != 0;
  18000. bool deferRight = (flags & BfBinOpFlag_DeferRight) != 0;
  18001. if (deferRight)
  18002. {
  18003. rightValue = mModule->GetDefaultTypedValue(mModule->GetPrimitiveType(BfTypeCode_Var));
  18004. }
  18005. if ((rightValue.mValue.IsConst()) && (!leftValue.mValue.IsConst()))
  18006. {
  18007. if (CheckConstCompare(binaryOp, opToken, leftValue, rightValue))
  18008. return;
  18009. }
  18010. else if ((leftValue.mValue.IsConst()) && (!rightValue.mValue.IsConst()))
  18011. {
  18012. if (CheckConstCompare(BfGetOppositeBinaryOp(binaryOp), opToken, rightValue, leftValue))
  18013. return;
  18014. }
  18015. if ((binaryOp == BfBinaryOp_NullCoalesce) && ((leftValue.mType->IsPointer()) || (leftValue.mType->IsFunction()) || (leftValue.mType->IsObject())))
  18016. {
  18017. auto prevBB = mModule->mBfIRBuilder->GetInsertBlock();
  18018. auto rhsBB = mModule->mBfIRBuilder->CreateBlock("nullc.rhs");
  18019. auto endBB = mModule->mBfIRBuilder->CreateBlock("nullc.end");
  18020. BfIRValue isNull;
  18021. if (leftValue.mType->IsFunction())
  18022. isNull = mModule->mBfIRBuilder->CreateIsNull(
  18023. mModule->mBfIRBuilder->CreateIntToPtr(leftValue.mValue, mModule->mBfIRBuilder->MapType(mModule->GetPrimitiveType(BfTypeCode_NullPtr))));
  18024. else
  18025. isNull = mModule->mBfIRBuilder->CreateIsNull(leftValue.mValue);
  18026. mModule->mBfIRBuilder->CreateCondBr(isNull, rhsBB, endBB);
  18027. mModule->AddBasicBlock(rhsBB);
  18028. if (!rightValue)
  18029. {
  18030. mModule->AssertErrorState();
  18031. return;
  18032. }
  18033. else
  18034. {
  18035. auto rightToLeftValue = mModule->CastToValue(rightExpression, rightValue, leftValue.mType, BfCastFlags_SilentFail);
  18036. if (rightToLeftValue)
  18037. {
  18038. rightValue = BfTypedValue(rightToLeftValue, leftValue.mType);
  18039. }
  18040. else
  18041. {
  18042. auto leftToRightValue = mModule->CastToValue(leftExpression, leftValue, rightValue.mType, BfCastFlags_SilentFail);
  18043. if (leftToRightValue)
  18044. {
  18045. leftValue = BfTypedValue(leftToRightValue, rightValue.mType);
  18046. }
  18047. else
  18048. {
  18049. // Note: Annoying trigraph split for '??'
  18050. mModule->Fail(StrFormat("Operator '?" "?' cannot be applied to operands of type '%s' and '%s'",
  18051. mModule->TypeToString(leftValue.mType).c_str(), mModule->TypeToString(rightValue.mType).c_str()), opToken);
  18052. leftValue = mModule->GetDefaultTypedValue(rightValue.mType);
  18053. }
  18054. }
  18055. }
  18056. mModule->mBfIRBuilder->CreateBr(endBB);
  18057. auto endRhsBB = mModule->mBfIRBuilder->GetInsertBlock();
  18058. mModule->AddBasicBlock(endBB);
  18059. auto phi = mModule->mBfIRBuilder->CreatePhi(mModule->mBfIRBuilder->MapType(leftValue.mType), 2);
  18060. mModule->mBfIRBuilder->AddPhiIncoming(phi, leftValue.mValue, prevBB);
  18061. mModule->mBfIRBuilder->AddPhiIncoming(phi, rightValue.mValue, endRhsBB);
  18062. mResult = BfTypedValue(phi, leftValue.mType);
  18063. return;
  18064. }
  18065. if ((binaryOp == BfBinaryOp_LeftShift) || (binaryOp == BfBinaryOp_RightShift))
  18066. {
  18067. forceLeftType = true;
  18068. }
  18069. if (rightValue.mType->IsRef())
  18070. rightValue.mType = rightValue.mType->GetUnderlyingType();
  18071. mModule->FixIntUnknown(leftValue, rightValue);
  18072. // Prefer floats, prefer chars
  18073. int leftCompareSize = leftValue.mType->mSize;
  18074. if (leftValue.mType->IsFloat())
  18075. leftCompareSize += 0x10;
  18076. if (leftValue.mType->IsChar())
  18077. leftCompareSize += 0x100;
  18078. if (!leftValue.mType->IsPrimitiveType())
  18079. leftCompareSize += 0x1000;
  18080. int rightCompareSize = rightValue.mType->mSize;
  18081. if (rightValue.mType->IsFloat())
  18082. rightCompareSize += 0x10;
  18083. if (rightValue.mType->IsChar())
  18084. rightCompareSize += 0x100;
  18085. if (!rightValue.mType->IsPrimitiveType())
  18086. rightCompareSize += 0x1000;
  18087. if ((leftValue.mType->IsTypeInstance()) && (rightValue.mType->IsTypeInstance()))
  18088. {
  18089. int leftInheritDepth = leftValue.mType->ToTypeInstance()->mInheritDepth;
  18090. int rightInheritDepth = rightValue.mType->ToTypeInstance()->mInheritDepth;
  18091. if (leftInheritDepth < rightInheritDepth)
  18092. {
  18093. // If both are type instances then choose the type with the lowest inherit depth
  18094. // so we will choose the base type when applicable
  18095. forceLeftType = true;
  18096. }
  18097. }
  18098. auto resultType = leftValue.mType;
  18099. if (!forceLeftType)
  18100. {
  18101. bool handled = false;
  18102. // If one of these is a constant that can be converted into a smaller type, then do that
  18103. if (rightValue.mValue.IsConst())
  18104. {
  18105. if (mModule->CanCast(rightValue, leftValue.mType, BfCastFlags_NoBox))
  18106. {
  18107. resultType = leftValue.mType;
  18108. handled = true;
  18109. }
  18110. }
  18111. // If left is an IntUnknown, allow the right to inform the type
  18112. if (leftValue.mType->IsIntUnknown())
  18113. {
  18114. if (leftValue.mValue.IsConst())
  18115. {
  18116. if (mModule->CanCast(leftValue, rightValue.mType))
  18117. {
  18118. resultType = rightValue.mType;
  18119. handled = true;
  18120. }
  18121. }
  18122. }
  18123. if ((leftValue.mType->IsPointer()) &&
  18124. (rightValue.mType->IsPointer()))
  18125. {
  18126. BfPointerType* leftPointerType = (BfPointerType*)leftValue.mType;
  18127. BfPointerType* rightPointerType = (BfPointerType*)rightValue.mType;
  18128. // If one is a pointer to a sized array then use the other type
  18129. if (leftPointerType->mElementType->IsSizedArray())
  18130. {
  18131. resultType = rightPointerType;
  18132. handled = true;
  18133. }
  18134. else if (rightPointerType->mElementType->IsSizedArray())
  18135. {
  18136. resultType = leftPointerType;
  18137. handled = true;
  18138. }
  18139. }
  18140. if (!handled)
  18141. {
  18142. if ((resultType->IsNull()) ||
  18143. (rightCompareSize > leftCompareSize) ||
  18144. (((rightCompareSize == leftCompareSize) && (!rightValue.mType->IsSigned()))) ||
  18145. (rightValue.mType->IsTypedPrimitive()))
  18146. {
  18147. // Select the type with the "most information"
  18148. if (!rightValue.mType->IsNull())
  18149. resultType = rightValue.mType;
  18150. }
  18151. if ((!resultType->IsPointer()) && (rightValue.mType->IsPointer()))
  18152. resultType = rightValue.mType;
  18153. }
  18154. }
  18155. bool explicitCast = false;
  18156. BfTypedValue* resultTypedValue;
  18157. BfTypedValue* otherTypedValue;
  18158. BfType* otherType;
  18159. BfAstNode* resultTypeSrc;
  18160. BfAstNode* otherTypeSrc;
  18161. if (resultType == leftValue.mType)
  18162. {
  18163. resultTypedValue = &leftValue;
  18164. resultTypeSrc = leftExpression;
  18165. otherTypedValue = &rightValue;
  18166. otherTypeSrc = rightExpression;
  18167. otherType = otherTypedValue->mType;
  18168. }
  18169. else
  18170. {
  18171. resultTypedValue = &rightValue;
  18172. resultTypeSrc = rightExpression;
  18173. otherTypedValue = &leftValue;
  18174. otherTypeSrc = leftExpression;
  18175. otherType = otherTypedValue->mType;
  18176. }
  18177. auto _OpFail = [&]()
  18178. {
  18179. if ((rightValue.mType != NULL) && (leftValue.mType != NULL))
  18180. {
  18181. if (rightValue.mType != leftValue.mType)
  18182. mModule->Fail(StrFormat("Cannot perform binary operation '%s' between types '%s' and '%s'",
  18183. BfGetOpName(binaryOp), mModule->TypeToString(leftValue.mType).c_str(), mModule->TypeToString(rightValue.mType).c_str()), opToken);
  18184. else
  18185. {
  18186. if (leftValue.mType->IsInterface())
  18187. {
  18188. 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.",
  18189. BfGetOpName(binaryOp), mModule->TypeToString(leftValue.mType).c_str()), opToken);
  18190. }
  18191. else
  18192. {
  18193. mModule->Fail(StrFormat("Cannot perform binary operation '%s' between two instances of type '%s'",
  18194. BfGetOpName(binaryOp), mModule->TypeToString(leftValue.mType).c_str()), opToken);
  18195. }
  18196. }
  18197. }
  18198. else
  18199. mModule->Fail(StrFormat("Cannot perform binary operation '%s'", BfGetOpName(binaryOp)), opToken);
  18200. };
  18201. // This case fixes cases like "c == 0" where "0" is technically an int but can be reduced
  18202. if (BfBinOpEqualityCheck(binaryOp))
  18203. {
  18204. if ((resultType != otherType) && (resultTypedValue->mValue.IsConst()) && (mModule->CanCast(*resultTypedValue, otherType)))
  18205. {
  18206. std::swap(resultTypedValue, otherTypedValue);
  18207. std::swap(resultTypeSrc, otherTypeSrc);
  18208. std::swap(resultType, otherType);
  18209. }
  18210. }
  18211. BfIRValue convLeftValue;
  18212. BfIRValue convRightValue;
  18213. if (((resultType->IsVar()) || (otherType->IsVar())) && (!deferRight))
  18214. {
  18215. bool isComparison = (binaryOp >= BfBinaryOp_Equality) && (binaryOp <= BfBinaryOp_LessThanOrEqual);
  18216. if (isComparison)
  18217. mResult = mModule->GetDefaultTypedValue(mModule->GetPrimitiveType(BfTypeCode_Boolean), false, BfDefaultValueKind_Addr);
  18218. else if (mExpectingType != NULL)
  18219. mResult = mModule->GetDefaultTypedValue(mExpectingType, false, BfDefaultValueKind_Addr);
  18220. else
  18221. mResult = mModule->GetDefaultTypedValue(resultType, false, BfDefaultValueKind_Addr);
  18222. return;
  18223. }
  18224. if ((otherType->IsNull()) && (BfBinOpEqualityCheck(binaryOp)))
  18225. {
  18226. bool isEquality = (binaryOp == BfBinaryOp_Equality) || (binaryOp == BfBinaryOp_StrictEquality);
  18227. if ((resultType->IsValueType()) && (!resultType->IsFunction()))
  18228. {
  18229. auto boolType = mModule->GetPrimitiveType(BfTypeCode_Boolean);
  18230. if (resultType->IsNullable())
  18231. {
  18232. auto elementType = resultType->GetUnderlyingType();
  18233. mModule->PopulateType(elementType);
  18234. if (elementType->IsValuelessType())
  18235. {
  18236. mModule->mBfIRBuilder->PopulateType(resultType);
  18237. BfTypedValue nullableTypedVale = mModule->MakeAddressable(*resultTypedValue);
  18238. BfIRValue hasValuePtr = mModule->mBfIRBuilder->CreateInBoundsGEP(nullableTypedVale.mValue, 0, 1);
  18239. BfIRValue hasValueValue = mModule->mBfIRBuilder->CreateLoad(hasValuePtr);
  18240. if (isEquality)
  18241. hasValueValue = mModule->mBfIRBuilder->CreateNot(hasValueValue);
  18242. mResult = BfTypedValue(hasValueValue, boolType);
  18243. }
  18244. else
  18245. {
  18246. mModule->mBfIRBuilder->PopulateType(resultType);
  18247. BfTypedValue nullableTypedVale = mModule->MakeAddressable(*resultTypedValue);
  18248. BfIRValue hasValuePtr = mModule->mBfIRBuilder->CreateInBoundsGEP(nullableTypedVale.mValue, 0, 2);
  18249. BfIRValue hasValueValue = mModule->mBfIRBuilder->CreateLoad(hasValuePtr);
  18250. if (isEquality)
  18251. hasValueValue = mModule->mBfIRBuilder->CreateNot(hasValueValue);
  18252. mResult = BfTypedValue(hasValueValue, boolType);
  18253. }
  18254. return;
  18255. }
  18256. if (resultType->IsNull())
  18257. {
  18258. // Null always equals null
  18259. mResult = BfTypedValue(mModule->GetConstValue(isEquality ? 1 : 0, boolType), boolType);
  18260. return;
  18261. }
  18262. if (!mModule->IsInSpecializedSection())
  18263. {
  18264. //CS0472: The result of the expression is always 'true' since a value of type 'int' is never equal to 'null' of type '<null>'
  18265. mModule->Warn(BfWarning_CS0472_ValueTypeNullCompare,
  18266. StrFormat("The result of the expression is always '%s' since a value of type '%s' can never be null",
  18267. isEquality ? "false" : "true", mModule->TypeToString(resultType).c_str()), otherTypeSrc);
  18268. }
  18269. // Valuetypes never equal null
  18270. mResult = BfTypedValue(mModule->GetConstValue(isEquality ? 0 : 1, boolType), boolType);
  18271. return;
  18272. }
  18273. }
  18274. // Check for constant equality checks (mostly for strings)
  18275. if (BfBinOpEqualityCheck(binaryOp))
  18276. {
  18277. auto leftConstant = mModule->mBfIRBuilder->GetConstant(leftValue.mValue);
  18278. auto rightConstant = mModule->mBfIRBuilder->GetConstant(rightValue.mValue);
  18279. if ((leftConstant != NULL) && (rightConstant != NULL))
  18280. {
  18281. auto boolType = mModule->GetPrimitiveType(BfTypeCode_Boolean);
  18282. int leftStringPoolIdx = mModule->GetStringPoolIdx(leftValue.mValue, mModule->mBfIRBuilder);
  18283. if (leftStringPoolIdx != -1)
  18284. {
  18285. int rightStringPoolIdx = mModule->GetStringPoolIdx(rightValue.mValue, mModule->mBfIRBuilder);
  18286. if (rightStringPoolIdx != -1)
  18287. {
  18288. bool isEqual = leftStringPoolIdx == rightStringPoolIdx;
  18289. if ((binaryOp == BfBinaryOp_InEquality) || (binaryOp == BfBinaryOp_StrictInEquality))
  18290. isEqual = !isEqual;
  18291. mResult = BfTypedValue(mModule->GetConstValue(isEqual ? 1 : 0, boolType), boolType);
  18292. return;
  18293. }
  18294. }
  18295. int eqResult = mModule->mBfIRBuilder->CheckConstEquality(leftValue.mValue, rightValue.mValue);
  18296. if (eqResult != -1)
  18297. {
  18298. bool isEqual = eqResult == 1;
  18299. if ((binaryOp == BfBinaryOp_InEquality) || (binaryOp == BfBinaryOp_StrictInEquality))
  18300. isEqual = !isEqual;
  18301. mResult = BfTypedValue(mModule->GetConstValue(isEqual ? 1 : 0, boolType), boolType);
  18302. return;
  18303. }
  18304. }
  18305. // Valueless types always compare as 'equal'
  18306. if (leftValue.mType == rightValue.mType)
  18307. {
  18308. mModule->PopulateType(leftValue.mType);
  18309. if (leftValue.mType->IsValuelessType())
  18310. {
  18311. auto boolType = mModule->GetPrimitiveType(BfTypeCode_Boolean);
  18312. bool isEqual = (binaryOp == BfBinaryOp_Equality) || (binaryOp == BfBinaryOp_StrictEquality);
  18313. mResult = BfTypedValue(mModule->GetConstValue(isEqual ? 1 : 0, boolType), boolType);
  18314. return;
  18315. }
  18316. }
  18317. }
  18318. if ((leftValue.mType->IsTypeInstance()) || (leftValue.mType->IsGenericParam()) ||
  18319. (rightValue.mType->IsTypeInstance()) || (rightValue.mType->IsGenericParam()))
  18320. {
  18321. // As an optimization, we don't call user operator overloads for null checks
  18322. bool skipOpOverload = false;
  18323. if ((binaryOp == BfBinaryOp_StrictEquality) || (binaryOp == BfBinaryOp_StrictInEquality))
  18324. skipOpOverload = true;
  18325. else if (BfBinOpEqualityCheck(binaryOp))
  18326. {
  18327. if (!leftValue.IsAddr())
  18328. {
  18329. auto leftConstant = mModule->mBfIRBuilder->GetConstant(leftValue.mValue);
  18330. if ((leftConstant != NULL) && (leftConstant->IsNull()))
  18331. skipOpOverload = true;
  18332. }
  18333. if (!rightValue.IsAddr())
  18334. {
  18335. auto rightConstant = mModule->mBfIRBuilder->GetConstant(rightValue.mValue);
  18336. if ((rightConstant != NULL) && (rightConstant->IsNull()))
  18337. skipOpOverload = true;
  18338. }
  18339. }
  18340. if ((binaryOp == BfBinaryOp_Add) && (resultType->IsInstanceOf(mModule->mCompiler->mStringTypeDef)))
  18341. {
  18342. // Allow failover to constant string addition
  18343. if ((leftValue.mValue.IsConst()) && (rightValue.mValue.IsConst()))
  18344. skipOpOverload = true;
  18345. }
  18346. if (!skipOpOverload)
  18347. {
  18348. BfBinaryOp findBinaryOp = binaryOp;
  18349. bool isComparison = (binaryOp >= BfBinaryOp_Equality) && (binaryOp <= BfBinaryOp_LessThanOrEqual);
  18350. for (int pass = 0; pass < 2; pass++)
  18351. {
  18352. BfBinaryOp oppositeBinaryOp = BfGetOppositeBinaryOp(findBinaryOp);
  18353. bool foundOp = false;
  18354. BfResolvedArg leftArg;
  18355. leftArg.mExpression = leftExpression;
  18356. leftArg.mTypedValue = leftValue;
  18357. BfResolvedArg rightArg;
  18358. rightArg.mExpression = rightExpression;
  18359. rightArg.mTypedValue = rightValue;
  18360. if (deferRight)
  18361. {
  18362. BfResolvedArgs argValues;
  18363. SizedArray<BfExpression*, 2> argExprs;
  18364. argExprs.push_back(BfNodeDynCast<BfExpression>(rightExpression));
  18365. BfSizedArray<BfExpression*> sizedArgExprs(argExprs);
  18366. argValues.Init(&sizedArgExprs);
  18367. ResolveArgValues(argValues, BfResolveArgsFlag_DeferParamEval);
  18368. rightArg = argValues.mResolvedArgs[0];
  18369. }
  18370. SizedArray<BfResolvedArg, 2> args;
  18371. if (pass == 0)
  18372. {
  18373. args.push_back(leftArg);
  18374. args.push_back(rightArg);
  18375. }
  18376. else
  18377. {
  18378. args.push_back(rightArg);
  18379. args.push_back(leftArg);
  18380. }
  18381. auto checkLeftType = leftValue.mType;
  18382. auto checkRightType = rightValue.mType;
  18383. BfMethodMatcher methodMatcher(opToken, mModule, "", args, NULL);
  18384. methodMatcher.mAllowImplicitRef = true;
  18385. methodMatcher.mBfEvalExprFlags = BfEvalExprFlags_NoAutoComplete;
  18386. BfBaseClassWalker baseClassWalker(checkLeftType, checkRightType, mModule);
  18387. bool invertResult = false;
  18388. BfType* operatorConstraintReturnType = NULL;
  18389. bool wasTransformedUsage = pass == 1;
  18390. while (true)
  18391. {
  18392. auto entry = baseClassWalker.Next();
  18393. auto checkType = entry.mTypeInstance;
  18394. if (checkType == NULL)
  18395. break;
  18396. bool foundExactMatch = false;
  18397. SizedArray<BfOperatorDef*, 8> oppositeOperatorDefs;
  18398. for (auto operatorDef : checkType->mTypeDef->mOperators)
  18399. {
  18400. bool allowOp = operatorDef->mOperatorDeclaration->mBinOp == findBinaryOp;
  18401. if ((isComparison) && (operatorDef->mOperatorDeclaration->mBinOp == BfBinaryOp_Compare))
  18402. allowOp = true;
  18403. if (allowOp)
  18404. {
  18405. foundOp = true;
  18406. if (!methodMatcher.IsMemberAccessible(checkType, operatorDef->mDeclaringType))
  18407. continue;
  18408. if ((flags & BfBinOpFlag_IsConstraintCheck) != 0)
  18409. {
  18410. if (operatorDef->mGenericParams.IsEmpty())
  18411. {
  18412. // Fast check
  18413. auto returnType = mModule->CheckOperator(checkType, operatorDef, args[0].mTypedValue, args[1].mTypedValue);
  18414. if (returnType != NULL)
  18415. {
  18416. operatorConstraintReturnType = returnType;
  18417. methodMatcher.mBestMethodDef = operatorDef;
  18418. methodMatcher.mBestMethodTypeInstance = checkType;
  18419. foundExactMatch = true;
  18420. }
  18421. }
  18422. else
  18423. {
  18424. if (methodMatcher.CheckMethod(NULL, checkType, operatorDef, false))
  18425. {
  18426. auto rawMethodInstance = mModule->GetRawMethodInstance(checkType, operatorDef);
  18427. auto returnType = mModule->ResolveGenericType(rawMethodInstance->mReturnType, NULL, &methodMatcher.mBestMethodGenericArguments);
  18428. if (returnType != NULL)
  18429. {
  18430. operatorConstraintReturnType = returnType;
  18431. foundExactMatch = true;
  18432. }
  18433. }
  18434. }
  18435. }
  18436. else
  18437. {
  18438. if (methodMatcher.CheckMethod(NULL, checkType, operatorDef, false))
  18439. {
  18440. methodMatcher.mSelfType = entry.mSrcType;
  18441. if (operatorDef->mOperatorDeclaration->mBinOp == findBinaryOp)
  18442. foundExactMatch = true;
  18443. }
  18444. }
  18445. }
  18446. else if (operatorDef->mOperatorDeclaration->mBinOp == oppositeBinaryOp)
  18447. oppositeOperatorDefs.Add(operatorDef);
  18448. }
  18449. if ((((methodMatcher.mBestMethodDef == NULL) && (operatorConstraintReturnType == NULL)) || (!foundExactMatch)) && (!oppositeOperatorDefs.IsEmpty()))
  18450. {
  18451. foundOp = true;
  18452. for (auto oppositeOperatorDef : oppositeOperatorDefs)
  18453. {
  18454. if ((flags & BfBinOpFlag_IsConstraintCheck) != 0)
  18455. {
  18456. if (oppositeOperatorDef->mGenericParams.IsEmpty())
  18457. {
  18458. // Fast check
  18459. auto returnType = mModule->CheckOperator(checkType, oppositeOperatorDef, args[0].mTypedValue, args[1].mTypedValue);
  18460. if (returnType != NULL)
  18461. {
  18462. operatorConstraintReturnType = returnType;
  18463. methodMatcher.mBestMethodDef = oppositeOperatorDef;
  18464. methodMatcher.mBestMethodTypeInstance = checkType;
  18465. methodMatcher.mSelfType = entry.mSrcType;
  18466. wasTransformedUsage = true;
  18467. }
  18468. }
  18469. else
  18470. {
  18471. if (methodMatcher.CheckMethod(NULL, checkType, oppositeOperatorDef, false))
  18472. {
  18473. auto rawMethodInstance = mModule->GetRawMethodInstance(checkType, oppositeOperatorDef);
  18474. auto returnType = mModule->ResolveGenericType(rawMethodInstance->mReturnType, NULL, &methodMatcher.mBestMethodGenericArguments);
  18475. if (returnType != NULL)
  18476. {
  18477. operatorConstraintReturnType = returnType;
  18478. methodMatcher.mSelfType = entry.mSrcType;
  18479. wasTransformedUsage = true;
  18480. }
  18481. }
  18482. }
  18483. }
  18484. else
  18485. {
  18486. if (methodMatcher.CheckMethod(NULL, checkType, oppositeOperatorDef, false))
  18487. {
  18488. methodMatcher.mSelfType = entry.mSrcType;
  18489. wasTransformedUsage = true;
  18490. }
  18491. }
  18492. }
  18493. }
  18494. }
  18495. bool hadMatch = (methodMatcher.mBestMethodDef != NULL);
  18496. if ((methodMatcher.mBestMethodDef != NULL) && ((flags & BfBinOpFlag_IgnoreOperatorWithWrongResult) != 0))
  18497. {
  18498. auto matchedOp = ((BfOperatorDeclaration*)methodMatcher.mBestMethodDef->mMethodDeclaration)->mBinOp;
  18499. methodMatcher.mBestMethodInstance = GetSelectedMethod(methodMatcher.mTargetSrc, methodMatcher.mBestMethodTypeInstance, methodMatcher.mBestMethodDef, methodMatcher);
  18500. if ((methodMatcher.mBestMethodInstance.mMethodInstance->mReturnType != mExpectingType) &&
  18501. ((matchedOp == binaryOp) || (matchedOp == oppositeBinaryOp)))
  18502. {
  18503. if (binaryOp == BfBinaryOp_Equality)
  18504. binaryOp = BfBinaryOp_StrictEquality;
  18505. if (binaryOp == BfBinaryOp_InEquality)
  18506. binaryOp = BfBinaryOp_StrictEquality;
  18507. hadMatch = false;
  18508. break;
  18509. }
  18510. }
  18511. if (hadMatch)
  18512. {
  18513. methodMatcher.FlushAmbiguityError();
  18514. auto matchedOp = ((BfOperatorDeclaration*)methodMatcher.mBestMethodDef->mMethodDeclaration)->mBinOp;
  18515. bool invertResult = matchedOp == oppositeBinaryOp;
  18516. auto methodDef = methodMatcher.mBestMethodDef;
  18517. auto autoComplete = GetAutoComplete();
  18518. bool wasCapturingMethodInfo = false;
  18519. if ((autoComplete != NULL) && (autoComplete->IsAutocompleteNode(opToken)))
  18520. {
  18521. auto operatorDecl = BfNodeDynCast<BfOperatorDeclaration>(methodDef->mMethodDeclaration);
  18522. if ((operatorDecl != NULL) && (operatorDecl->mOpTypeToken != NULL))
  18523. autoComplete->SetDefinitionLocation(operatorDecl->mOpTypeToken);
  18524. }
  18525. if ((wasTransformedUsage) && (methodDef->mCommutableKind != BfCommutableKind_Operator))
  18526. {
  18527. auto error = mModule->Warn(BfWarning_BF4206_OperatorCommutableUsage, "Transformed operator usage requires 'Commutable' attribute to be added to the operator declaration", opToken);
  18528. if ((error != NULL) && (methodDef->GetRefNode() != NULL))
  18529. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("See operator declaration"), methodDef->GetRefNode());
  18530. }
  18531. if (opToken != NULL)
  18532. {
  18533. if ((opToken->IsA<BfTokenNode>()) && (!noClassify) && (!baseClassWalker.mMayBeFromInterface))
  18534. mModule->SetElementType(opToken, BfSourceElementType_Method);
  18535. }
  18536. if ((flags & BfBinOpFlag_IsConstraintCheck) != 0)
  18537. {
  18538. mResult = BfTypedValue(mModule->mBfIRBuilder->GetFakeVal(), operatorConstraintReturnType);
  18539. }
  18540. else
  18541. {
  18542. SetAndRestoreValue<BfEvalExprFlags> prevFlags(mBfEvalExprFlags, (BfEvalExprFlags)(mBfEvalExprFlags | BfEvalExprFlags_NoAutoComplete));
  18543. mResult = CreateCall(&methodMatcher, BfTypedValue());
  18544. }
  18545. if ((mResult.mType != NULL) && (methodMatcher.mSelfType != NULL) && (mResult.mType->IsSelf()))
  18546. {
  18547. BF_ASSERT(mModule->IsInGeneric());
  18548. mResult = mModule->GetDefaultTypedValue(methodMatcher.mSelfType, false, BfDefaultValueKind_Value);
  18549. }
  18550. if ((invertResult) && (mResult.mType == mModule->GetPrimitiveType(BfTypeCode_Boolean)))
  18551. mResult.mValue = mModule->mBfIRBuilder->CreateNot(mResult.mValue);
  18552. if (pass == 1)
  18553. {
  18554. if (findBinaryOp == BfBinaryOp_Compare)
  18555. {
  18556. mResult = mModule->LoadValue(mResult);
  18557. if (mResult.mType->IsIntegral())
  18558. mResult.mValue = mModule->mBfIRBuilder->CreateNeg(mResult.mValue);
  18559. }
  18560. }
  18561. if ((isComparison) && (matchedOp == BfBinaryOp_Compare))
  18562. {
  18563. auto intType = mModule->GetPrimitiveType(BfTypeCode_IntPtr);
  18564. mResult = mModule->LoadValue(mResult);
  18565. if (mResult.mType != intType)
  18566. mResult = mModule->GetDefaultTypedValue(intType);
  18567. auto zeroVal = mModule->mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, 0);
  18568. auto useBinaryOp = binaryOp;
  18569. if (pass == 1)
  18570. useBinaryOp = BfGetFlippedBinaryOp(useBinaryOp);
  18571. auto boolType = mModule->GetPrimitiveType(BfTypeCode_Boolean);
  18572. switch (useBinaryOp)
  18573. {
  18574. case BfBinaryOp_Equality:
  18575. case BfBinaryOp_StrictEquality:
  18576. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateCmpEQ(mResult.mValue, zeroVal), boolType);
  18577. break;
  18578. case BfBinaryOp_InEquality:
  18579. case BfBinaryOp_StrictInEquality:
  18580. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateCmpNE(mResult.mValue, zeroVal), boolType);
  18581. break;
  18582. case BfBinaryOp_GreaterThan:
  18583. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateCmpGT(mResult.mValue, zeroVal, true), boolType);
  18584. break;
  18585. case BfBinaryOp_LessThan:
  18586. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateCmpLT(mResult.mValue, zeroVal, true), boolType);
  18587. break;
  18588. case BfBinaryOp_GreaterThanOrEqual:
  18589. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateCmpGTE(mResult.mValue, zeroVal, true), boolType);
  18590. break;
  18591. case BfBinaryOp_LessThanOrEqual:
  18592. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateCmpLTE(mResult.mValue, zeroVal, true), boolType);
  18593. break;
  18594. default: break;
  18595. }
  18596. }
  18597. return;
  18598. }
  18599. auto _CheckBinaryOp = [&](BfGenericParamInstance* genericParam)
  18600. {
  18601. for (auto& opConstraint : genericParam->mOperatorConstraints)
  18602. {
  18603. BfType* returnType = genericParam->mExternType;
  18604. bool works = false;
  18605. if (opConstraint.mBinaryOp == findBinaryOp)
  18606. {
  18607. if ((mModule->CanCast(args[0].mTypedValue, opConstraint.mLeftType)) &&
  18608. (mModule->CanCast(args[1].mTypedValue, opConstraint.mRightType)))
  18609. {
  18610. works = true;
  18611. }
  18612. }
  18613. if ((isComparison) && (opConstraint.mBinaryOp == BfBinaryOp_Compare))
  18614. {
  18615. if ((mModule->CanCast(args[0].mTypedValue, opConstraint.mLeftType)) &&
  18616. (mModule->CanCast(args[1].mTypedValue, opConstraint.mRightType)))
  18617. {
  18618. works = true;
  18619. }
  18620. else if ((mModule->CanCast(args[0].mTypedValue, opConstraint.mRightType)) &&
  18621. (mModule->CanCast(args[1].mTypedValue, opConstraint.mLeftType)))
  18622. {
  18623. works = true;
  18624. }
  18625. if (works)
  18626. {
  18627. returnType = mModule->GetPrimitiveType(BfTypeCode_Boolean);
  18628. }
  18629. }
  18630. if (works)
  18631. {
  18632. BF_ASSERT(genericParam->mExternType != NULL);
  18633. mResult = BfTypedValue(mModule->mBfIRBuilder->GetFakeVal(), returnType);
  18634. return true;
  18635. }
  18636. }
  18637. return false;
  18638. };
  18639. // Check method generic constraints
  18640. if ((mModule->mCurMethodInstance != NULL) && (mModule->mCurMethodInstance->mIsUnspecialized) && (mModule->mCurMethodInstance->mMethodInfoEx != NULL))
  18641. {
  18642. for (int genericParamIdx = 0; genericParamIdx < mModule->mCurMethodInstance->mMethodInfoEx->mGenericParams.size(); genericParamIdx++)
  18643. {
  18644. auto genericParam = mModule->mCurMethodInstance->mMethodInfoEx->mGenericParams[genericParamIdx];
  18645. if (_CheckBinaryOp(genericParam))
  18646. return;
  18647. }
  18648. }
  18649. // Check type generic constraints
  18650. if ((mModule->mCurTypeInstance->IsGenericTypeInstance()) && (mModule->mCurTypeInstance->IsUnspecializedType()))
  18651. {
  18652. SizedArray<BfGenericParamInstance*, 4> genericParams;
  18653. mModule->GetActiveTypeGenericParamInstances(genericParams);
  18654. for (auto genericParam : genericParams)
  18655. {
  18656. if (_CheckBinaryOp(genericParam))
  18657. return;
  18658. }
  18659. }
  18660. if (pass == 1)
  18661. break;
  18662. auto flippedBinaryOp = BfGetFlippedBinaryOp(findBinaryOp);
  18663. if (flippedBinaryOp != BfBinaryOp_None)
  18664. findBinaryOp = flippedBinaryOp;
  18665. }
  18666. auto prevResultType = resultType;
  18667. if ((leftValue.mType->IsPrimitiveType()) && (!rightValue.mType->IsTypedPrimitive()))
  18668. resultType = leftValue.mType;
  18669. if ((rightValue.mType->IsPrimitiveType()) && (!leftValue.mType->IsTypedPrimitive()))
  18670. resultType = rightValue.mType;
  18671. }
  18672. }
  18673. if (deferRight)
  18674. {
  18675. auto expectedType = resultType;
  18676. if ((binaryOp == BfBinaryOp_LeftShift) || (binaryOp == BfBinaryOp_RightShift))
  18677. expectedType = mModule->GetPrimitiveType(BfTypeCode_IntPtr);
  18678. rightValue = mModule->CreateValueFromExpression(BfNodeDynCast<BfExpression>(rightExpression), expectedType, (BfEvalExprFlags)((mBfEvalExprFlags & BfEvalExprFlags_InheritFlags) | BfEvalExprFlags_AllowSplat | BfEvalExprFlags_NoCast));
  18679. if (rightValue)
  18680. PerformBinaryOperation(leftExpression, rightExpression, binaryOp, opToken, (BfBinOpFlags)(flags & ~BfBinOpFlag_DeferRight), leftValue, rightValue);
  18681. return;
  18682. }
  18683. if (mModule->IsUnboundGeneric(resultType))
  18684. {
  18685. mResult = mModule->GetDefaultTypedValue(mModule->GetPrimitiveType(BfTypeCode_Var));
  18686. return;
  18687. }
  18688. if (resultType->IsPointer() && otherType->IsPointer())
  18689. {
  18690. if ((binaryOp == BfBinaryOp_Add) && (resultType == otherType) &&
  18691. (resultType->GetUnderlyingType() == mModule->GetPrimitiveType(BfTypeCode_Char8)))
  18692. {
  18693. AddStrings(leftValue, rightValue, opToken);
  18694. return;
  18695. }
  18696. //TODO: Allow all pointer comparisons, but only allow SUBTRACTION between equal pointer types
  18697. if (binaryOp == BfBinaryOp_Subtract)
  18698. {
  18699. if (!mModule->CanCast(*otherTypedValue, resultType))
  18700. {
  18701. mModule->Fail(StrFormat("Operands '%s' and '%s' are not comparable types.",
  18702. mModule->TypeToString(leftValue.mType).c_str(), mModule->TypeToString(rightValue.mType).c_str()),
  18703. opToken);
  18704. return;
  18705. }
  18706. BfPointerType* resultPointerType = (BfPointerType*)resultType;
  18707. BfType* intPtrType = mModule->GetPrimitiveType(BfTypeCode_IntPtr);
  18708. convLeftValue = mModule->CastToValue(leftExpression, leftValue, intPtrType, (BfCastFlags)(BfCastFlags_Explicit | BfCastFlags_FromCompiler));
  18709. convRightValue = mModule->CastToValue(rightExpression, rightValue, intPtrType, (BfCastFlags)(BfCastFlags_Explicit | BfCastFlags_FromCompiler));
  18710. BfIRValue diffValue = mModule->mBfIRBuilder->CreateSub(convLeftValue, convRightValue);
  18711. diffValue = mModule->mBfIRBuilder->CreateDiv(diffValue, mModule->GetConstValue(resultPointerType->mElementType->mSize, intPtrType), true);
  18712. mResult = BfTypedValue(diffValue, intPtrType);
  18713. return;
  18714. }
  18715. else if ((binaryOp != BfBinaryOp_Equality) && (binaryOp != BfBinaryOp_StrictEquality) &&
  18716. (binaryOp != BfBinaryOp_InEquality) && (binaryOp != BfBinaryOp_StrictInEquality) &&
  18717. (binaryOp != BfBinaryOp_LessThan) && (binaryOp != BfBinaryOp_LessThanOrEqual) &&
  18718. (binaryOp != BfBinaryOp_GreaterThan) && (binaryOp != BfBinaryOp_GreaterThanOrEqual))
  18719. {
  18720. mModule->Fail("Invalid operation on pointers", opToken);
  18721. return;
  18722. }
  18723. if ((!BfBinOpEqualityCheck(binaryOp)) || (resultType != otherType))
  18724. {
  18725. resultType = mModule->GetPrimitiveType(BfTypeCode_UIntPtr);
  18726. explicitCast = true;
  18727. }
  18728. }
  18729. else if (resultType->IsPointer())
  18730. {
  18731. if (otherType->IsNull())
  18732. {
  18733. if (!BfBinOpEqualityCheck(binaryOp))
  18734. {
  18735. mModule->Fail(StrFormat("Invalid operation between '%s' and null", mModule->TypeToString(resultType).c_str()), opToken);
  18736. return;
  18737. }
  18738. if ((binaryOp == BfBinaryOp_Equality) || (binaryOp == BfBinaryOp_StrictEquality))
  18739. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateIsNull(resultTypedValue->mValue), mModule->GetPrimitiveType(BfTypeCode_Boolean));
  18740. else
  18741. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateIsNotNull(resultTypedValue->mValue), mModule->GetPrimitiveType(BfTypeCode_Boolean));
  18742. return;
  18743. }
  18744. // One pointer
  18745. if ((!otherType->IsIntegral()) ||
  18746. ((binaryOp != BfBinaryOp_Add) && (binaryOp != BfBinaryOp_Subtract)))
  18747. {
  18748. _OpFail();
  18749. return;
  18750. }
  18751. auto underlyingType = resultType->GetUnderlyingType();
  18752. BfIRValue addValue = otherTypedValue->mValue;
  18753. if ((!otherTypedValue->mType->IsSigned()) && (otherTypedValue->mType->mSize < mModule->mSystem->mPtrSize))
  18754. addValue = mModule->mBfIRBuilder->CreateNumericCast(addValue, false, BfTypeCode_UIntPtr);
  18755. if (binaryOp == BfBinaryOp_Subtract)
  18756. {
  18757. if (resultTypeSrc == rightExpression)
  18758. mModule->Fail("Cannot subtract a pointer from an integer", resultTypeSrc);
  18759. addValue = mModule->mBfIRBuilder->CreateNeg(addValue);
  18760. }
  18761. mModule->PopulateType(underlyingType);
  18762. if (underlyingType->IsValuelessType())
  18763. {
  18764. if (!mModule->IsInSpecializedSection())
  18765. {
  18766. mModule->Warn(0, "Adding to a pointer to a zero-sized element has no effect", opToken);
  18767. }
  18768. mResult = *resultTypedValue;
  18769. return;
  18770. }
  18771. mModule->mBfIRBuilder->PopulateType(underlyingType);
  18772. mResult = BfTypedValue(mModule->CreateIndexedValue(underlyingType, resultTypedValue->mValue, addValue), resultType);
  18773. return;
  18774. }
  18775. if ((resultType->IsFunction()) || (resultType->IsPointer()) || (resultType->IsObject()) || (resultType->IsInterface()) || (resultType->IsGenericParam()))
  18776. {
  18777. if ((binaryOp == BfBinaryOp_Add) &&
  18778. (resultType->IsInstanceOf(mModule->mCompiler->mStringTypeDef)) &&
  18779. (otherType->IsInstanceOf(mModule->mCompiler->mStringTypeDef)))
  18780. {
  18781. AddStrings(leftValue, rightValue, opToken);
  18782. return;
  18783. }
  18784. if (!BfGetBinaryOpPrecendence(binaryOp))
  18785. {
  18786. //mModule->Fail("Invalid operation for objects", opToken);
  18787. _OpFail();
  18788. return;
  18789. }
  18790. if ((binaryOp == BfBinaryOp_Equality) || (binaryOp == BfBinaryOp_StrictEquality) || (binaryOp == BfBinaryOp_InEquality) || (binaryOp == BfBinaryOp_StrictInEquality))
  18791. {
  18792. if (resultType->IsInterface())
  18793. {
  18794. // Compare as objects instead
  18795. resultType = mModule->mContext->mBfObjectType;
  18796. *resultTypedValue = mModule->Cast(resultTypeSrc, *resultTypedValue, resultType);
  18797. }
  18798. if (otherType->IsNull())
  18799. {
  18800. if (resultType->IsFunction())
  18801. {
  18802. if ((binaryOp == BfBinaryOp_Equality) || (binaryOp == BfBinaryOp_StrictEquality))
  18803. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateCmpEQ(mModule->mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, 0), resultTypedValue->mValue), mModule->GetPrimitiveType(BfTypeCode_Boolean));
  18804. else
  18805. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateCmpNE(mModule->mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, 0), resultTypedValue->mValue), mModule->GetPrimitiveType(BfTypeCode_Boolean));
  18806. }
  18807. else
  18808. {
  18809. if ((binaryOp == BfBinaryOp_Equality) || (binaryOp == BfBinaryOp_StrictEquality))
  18810. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateIsNull(resultTypedValue->mValue), mModule->GetPrimitiveType(BfTypeCode_Boolean));
  18811. else
  18812. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateIsNotNull(resultTypedValue->mValue), mModule->GetPrimitiveType(BfTypeCode_Boolean));
  18813. }
  18814. }
  18815. else
  18816. {
  18817. auto convertedValue = mModule->Cast(otherTypeSrc, *otherTypedValue, resultType, BfCastFlags_NoBox);
  18818. if (!convertedValue)
  18819. return;
  18820. convertedValue = mModule->LoadValue(convertedValue);
  18821. if ((binaryOp == BfBinaryOp_Equality) || (binaryOp == BfBinaryOp_StrictEquality))
  18822. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateCmpEQ(resultTypedValue->mValue, convertedValue.mValue), mModule->GetPrimitiveType(BfTypeCode_Boolean));
  18823. else
  18824. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateCmpNE(resultTypedValue->mValue, convertedValue.mValue), mModule->GetPrimitiveType(BfTypeCode_Boolean));
  18825. }
  18826. return;
  18827. }
  18828. }
  18829. if (resultType->IsTypedPrimitive())
  18830. {
  18831. bool needsOtherCast = true;
  18832. if (otherType != resultType)
  18833. {
  18834. if ((otherType->IsPrimitiveType()) && (!otherType->IsValuelessType()))
  18835. {
  18836. // Allow zero comparisons to match all typed primitives
  18837. if ((binaryOp == BfBinaryOp_Equality) || (binaryOp == BfBinaryOp_InEquality))
  18838. {
  18839. auto constant = mModule->mBfIRBuilder->GetConstant(otherTypedValue->mValue);
  18840. if ((constant != NULL) && (mModule->mBfIRBuilder->IsInt(constant->mTypeCode)) && (constant->mInt64 == 0))
  18841. needsOtherCast = false;
  18842. }
  18843. // Allow integer offsetting
  18844. if ((binaryOp == BfBinaryOp_Add) || (binaryOp == BfBinaryOp_Subtract))
  18845. {
  18846. if (otherType->IsIntegral())
  18847. needsOtherCast = false;
  18848. }
  18849. }
  18850. if (needsOtherCast)
  18851. {
  18852. // The only purpose of this cast is to potentially throw a casting error
  18853. BfIRValue otherCastResult = mModule->CastToValue(otherTypeSrc, *otherTypedValue, resultType, explicitCast ? BfCastFlags_Explicit : BfCastFlags_None);
  18854. if (!otherCastResult)
  18855. return;
  18856. }
  18857. }
  18858. auto underlyingType = resultType->GetUnderlyingType();
  18859. BfIRValue convResultValue = mModule->CastToValue(resultTypeSrc, *resultTypedValue, underlyingType, BfCastFlags_Explicit);
  18860. BfIRValue convOtherValue = mModule->CastToValue(otherTypeSrc, *otherTypedValue, underlyingType, BfCastFlags_Explicit);
  18861. if ((!underlyingType->IsValuelessType()) && ((!convResultValue) || (!convOtherValue)))
  18862. return;
  18863. if (resultTypedValue == &leftValue)
  18864. PerformBinaryOperation(underlyingType, convResultValue, convOtherValue, binaryOp, opToken);
  18865. else
  18866. PerformBinaryOperation(underlyingType, convOtherValue, convResultValue, binaryOp, opToken);
  18867. if (mResult.mType == underlyingType)
  18868. mResult.mType = resultType;
  18869. return;
  18870. }
  18871. auto _CallValueTypeEquals = [&]()
  18872. {
  18873. BfModuleMethodInstance moduleMethodInstance;
  18874. auto typeInst = leftValue.mType->ToTypeInstance();
  18875. if (typeInst != NULL)
  18876. {
  18877. if ((binaryOp == BfBinaryOp_StrictEquality) || (binaryOp == BfBinaryOp_StrictInEquality))
  18878. moduleMethodInstance = mModule->GetMethodByName(typeInst, BF_METHODNAME_DEFAULT_STRICT_EQUALS);
  18879. else
  18880. moduleMethodInstance = mModule->GetMethodByName(typeInst, BF_METHODNAME_DEFAULT_EQUALS);
  18881. }
  18882. else
  18883. {
  18884. BF_ASSERT(leftValue.mType->IsSizedArray() || leftValue.mType->IsMethodRef());
  18885. auto valueTypeInst = mModule->ResolveTypeDef(mModule->mCompiler->mValueTypeTypeDef)->ToTypeInstance();
  18886. BfMethodDef* equalsMethodDef = mModule->mCompiler->mValueTypeTypeDef->GetMethodByName("Equals");
  18887. BfTypeVector typeVec;
  18888. typeVec.push_back(leftValue.mType);
  18889. moduleMethodInstance = mModule->GetMethodInstance(valueTypeInst, equalsMethodDef, typeVec);
  18890. }
  18891. if (moduleMethodInstance)
  18892. {
  18893. if ((opToken != NULL) && (!noClassify))
  18894. mModule->SetElementType(opToken, BfSourceElementType_Method);
  18895. SizedArray<BfResolvedArg, 4> argValues;
  18896. BfResolvedArg resolvedArg;
  18897. resolvedArg.mTypedValue = leftValue;
  18898. argValues.push_back(resolvedArg);
  18899. resolvedArg.mTypedValue = rightValue;
  18900. argValues.push_back(resolvedArg);
  18901. mResult = CreateCall(opToken, BfTypedValue(), BfTypedValue(), moduleMethodInstance.mMethodInstance->mMethodDef, moduleMethodInstance, BfCreateFallFlags_None, argValues);
  18902. if ((mResult) &&
  18903. ((binaryOp == BfBinaryOp_InEquality) || (binaryOp == BfBinaryOp_StrictInEquality)))
  18904. mResult.mValue = mModule->mBfIRBuilder->CreateNot(mResult.mValue);
  18905. return true;
  18906. }
  18907. return false;
  18908. };
  18909. //if (((leftValue.mType->IsComposite()) || (leftValue.mType->IsObject())))
  18910. if (((resultType->IsComposite()) || (resultType->IsObject())))
  18911. {
  18912. bool areEquivalentTuples = false;
  18913. if ((leftValue.mType->IsTuple()) && (rightValue.mType->IsTuple()))
  18914. {
  18915. auto leftTupleType = (BfTypeInstance*)leftValue.mType;
  18916. auto rightTupleType = (BfTypeInstance*)rightValue.mType;
  18917. // We only do this for tuples, because we would allow an implicit struct
  18918. // truncation if we allow it for all structs, which would result in only
  18919. // the base class's fields being compared
  18920. if (mModule->CanCast(rightValue, leftValue.mType))
  18921. rightValue = mModule->Cast(opToken, rightValue, leftValue.mType, BfCastFlags_Explicit);
  18922. else if (mModule->CanCast(leftValue, rightValue.mType))
  18923. leftValue = mModule->Cast(opToken, leftValue, rightValue.mType, BfCastFlags_Explicit);
  18924. }
  18925. if (leftValue.mType == rightValue.mType)
  18926. {
  18927. if (BfBinOpEqualityCheck(binaryOp))
  18928. {
  18929. auto intCoercibleType = mModule->GetIntCoercibleType(leftValue.mType);
  18930. if (intCoercibleType != NULL)
  18931. {
  18932. auto intLHS = mModule->GetIntCoercible(leftValue);
  18933. auto intRHS = mModule->GetIntCoercible(rightValue);
  18934. auto boolType = mModule->GetPrimitiveType(BfTypeCode_Boolean);
  18935. if ((binaryOp == BfBinaryOp_Equality) || (binaryOp == BfBinaryOp_StrictEquality))
  18936. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateCmpEQ(intLHS.mValue, intRHS.mValue), boolType);
  18937. else
  18938. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateCmpNE(intLHS.mValue, intRHS.mValue), boolType);
  18939. return;
  18940. }
  18941. if (_CallValueTypeEquals())
  18942. return;
  18943. }
  18944. mModule->Fail(StrFormat("Operator '%s' cannot be applied to operands of type '%s'",
  18945. BfGetOpName(binaryOp),
  18946. mModule->TypeToString(leftValue.mType).c_str()), opToken);
  18947. return;
  18948. }
  18949. else
  18950. {
  18951. bool handled = false;
  18952. for (int pass = 0; pass < 2; pass++)
  18953. {
  18954. BfTypedValue& fromValue = (pass == 0) ? leftValue : rightValue;
  18955. BfType* toType = (pass == 0) ? rightValue.mType : leftValue.mType;
  18956. if (mModule->CanCast(fromValue, toType))
  18957. {
  18958. auto result = mModule->Cast(opToken, fromValue, toType);
  18959. if (result)
  18960. {
  18961. resultType = toType;
  18962. fromValue = result;
  18963. handled = true;
  18964. break;
  18965. }
  18966. }
  18967. }
  18968. if (!handled)
  18969. {
  18970. if ((leftValue.mType->IsUndefSizedArray()) || (rightValue.mType->IsUndefSizedArray()))
  18971. {
  18972. if ((leftValue.mType->IsSizedArray()) && (rightValue.mType->IsSizedArray() &&
  18973. (leftValue.mType->GetUnderlyingType() == rightValue.mType->GetUnderlyingType())))
  18974. {
  18975. if (BfBinOpEqualityCheck(binaryOp))
  18976. {
  18977. auto boolType = mModule->GetPrimitiveType(BfTypeCode_Boolean);
  18978. mResult = mModule->GetDefaultTypedValue(boolType, false, BfDefaultValueKind_Undef);
  18979. return;
  18980. }
  18981. }
  18982. }
  18983. mModule->Fail(StrFormat("Operator '%s' cannot be applied to operands of type '%s' and '%s'",
  18984. BfGetOpName(binaryOp),
  18985. mModule->TypeToString(leftValue.mType).c_str(),
  18986. mModule->TypeToString(rightValue.mType).c_str()), opToken);
  18987. return;
  18988. }
  18989. }
  18990. }
  18991. if (resultType->IsMethodRef() && otherType->IsMethodRef())
  18992. {
  18993. if (BfBinOpEqualityCheck(binaryOp))
  18994. {
  18995. auto boolType = mModule->GetPrimitiveType(BfTypeCode_Boolean);
  18996. BfMethodRefType* lhsMethodRefType = (BfMethodRefType*)leftValue.mType;
  18997. BfMethodRefType* rhsMethodRefType = (BfMethodRefType*)rightValue.mType;
  18998. if (lhsMethodRefType->mMethodRef != rhsMethodRefType->mMethodRef)
  18999. {
  19000. mResult = BfTypedValue(mModule->GetConstValue(((binaryOp == BfBinaryOp_Equality) || (binaryOp == BfBinaryOp_StrictEquality)) ? 0 : 1, boolType), boolType);
  19001. return;
  19002. }
  19003. if (_CallValueTypeEquals())
  19004. return;
  19005. }
  19006. }
  19007. if (resultType->IsIntegral())
  19008. {
  19009. if ((binaryOp == BfBinaryOp_LeftShift) || (binaryOp == BfBinaryOp_RightShift))
  19010. {
  19011. if (rightValue.mValue.IsConst())
  19012. {
  19013. auto constVal = mModule->mBfIRBuilder->GetConstant(rightValue.mValue);
  19014. if ((constVal->mInt64 < 0) || (constVal->mInt64 >= 8 * resultType->mSize))
  19015. {
  19016. mModule->Fail(StrFormat("Shift value '%lld' is out of range for type '%s'", constVal->mInt64, mModule->TypeToString(resultType).c_str()), opToken);
  19017. }
  19018. }
  19019. }
  19020. // We're trying a simplified scheme that doesn't always try to up-convert into an 'int'
  19021. if (leftValue.mType != rightValue.mType)
  19022. {
  19023. bool isBitwiseExpr =
  19024. (binaryOp == BfBinaryOp_BitwiseAnd) ||
  19025. (binaryOp == BfBinaryOp_BitwiseOr) ||
  19026. (binaryOp == BfBinaryOp_ExclusiveOr) ||
  19027. (binaryOp == BfBinaryOp_LeftShift) ||
  19028. (binaryOp == BfBinaryOp_RightShift) ||
  19029. (binaryOp == BfBinaryOp_Equality) ||
  19030. (binaryOp == BfBinaryOp_InEquality) ||
  19031. (binaryOp == BfBinaryOp_StrictEquality) ||
  19032. (binaryOp == BfBinaryOp_StrictInEquality);
  19033. if ((binaryOp == BfBinaryOp_LeftShift) || (binaryOp == BfBinaryOp_RightShift))
  19034. {
  19035. // For shifts we have more lenient rules - shifts are naturally limited so any int type is equally valid
  19036. if (rightValue.mType->IsIntegral())
  19037. explicitCast = true;
  19038. }
  19039. else if (((binaryOp == BfBinaryOp_Add) || (binaryOp == BfBinaryOp_Subtract)) && (resultType->IsChar()) && (otherType->IsInteger()))
  19040. {
  19041. // charVal += intVal;
  19042. explicitCast = true;
  19043. }
  19044. else if ((!resultType->IsSigned()) && (otherType->IsSigned()))
  19045. {
  19046. if (mModule->CanCast(*otherTypedValue, resultType))
  19047. {
  19048. // If we can convert the 'other' value implicitly then it's a convertible literal, leave as uint
  19049. }
  19050. else
  19051. {
  19052. mModule->Fail(StrFormat("Operator cannot be applied to operands of type '%s' and '%s'",
  19053. mModule->TypeToString(leftValue.mType).c_str(),
  19054. mModule->TypeToString(rightValue.mType).c_str()), opToken);
  19055. return;
  19056. }
  19057. }
  19058. else if ((isBitwiseExpr) && (otherType->IsIntegral()) && (resultType->mSize == otherType->mSize))
  19059. {
  19060. // Forget about signed/unsigned mismatches for bitwise operations
  19061. explicitCast = true;
  19062. }
  19063. else
  19064. {
  19065. if ((binaryOp == BfBinaryOp_Subtract) && (resultType->IsChar()) && (otherType->IsChar()))
  19066. {
  19067. // "wchar - char" subtraction will always fit into int32, because of unicode range
  19068. resultType = mModule->GetPrimitiveType(BfTypeCode_Int32);
  19069. explicitCast = true;
  19070. }
  19071. else if ((otherType->IsChar()) &&
  19072. ((binaryOp == BfBinaryOp_Add) || (binaryOp == BfBinaryOp_Subtract)))
  19073. {
  19074. mModule->Fail(StrFormat("Cannot perform operation between types '%s' and '%s'",
  19075. mModule->TypeToString(leftValue.mType).c_str(),
  19076. mModule->TypeToString(rightValue.mType).c_str()), opToken);
  19077. }
  19078. }
  19079. }
  19080. else if ((!resultType->IsSigned()) && (binaryOp == BfBinaryOp_Subtract) && (!forceLeftType))
  19081. {
  19082. if ((mExpectingType == NULL) || (mExpectingType->IsSigned()) || (resultType->IsChar()))
  19083. {
  19084. if ((resultType->IsChar()) && (resultType->mSize == 4))
  19085. {
  19086. // "wchar - wchar" subtraction will always fit into int32, because of unicode range
  19087. resultType = mModule->GetPrimitiveType(BfTypeCode_Int32);
  19088. }
  19089. else
  19090. {
  19091. // The result of uint8 - uint8 is int16 (for example)
  19092. switch (resultType->mSize)
  19093. {
  19094. case 1:
  19095. resultType = mModule->GetPrimitiveType(BfTypeCode_Int16);
  19096. break;
  19097. case 2:
  19098. resultType = mModule->GetPrimitiveType(BfTypeCode_Int32);
  19099. break;
  19100. case 4:
  19101. resultType = mModule->GetPrimitiveType(BfTypeCode_Int64);
  19102. break;
  19103. }
  19104. }
  19105. explicitCast = true;
  19106. }
  19107. }
  19108. else if (resultType->IsChar())
  19109. {
  19110. bool canDoOp =
  19111. (binaryOp == BfBinaryOp_BitwiseAnd) ||
  19112. (binaryOp == BfBinaryOp_BitwiseOr) ||
  19113. ((binaryOp >= BfBinaryOp_Equality) && (binaryOp <= BfBinaryOp_Compare));
  19114. if (!canDoOp)
  19115. {
  19116. mModule->Fail(StrFormat("Cannot perform operation on type '%s'", mModule->TypeToString(resultType).c_str()), opToken);
  19117. return;
  19118. }
  19119. }
  19120. }
  19121. if (!convLeftValue)
  19122. convLeftValue = mModule->CastToValue(leftExpression, leftValue, resultType,
  19123. explicitCast ? (BfCastFlags)(BfCastFlags_Explicit | BfCastFlags_FromCompiler) : BfCastFlags_None);
  19124. if (!convRightValue)
  19125. convRightValue = mModule->CastToValue(rightExpression, rightValue, resultType,
  19126. explicitCast ? (BfCastFlags)(BfCastFlags_Explicit | BfCastFlags_FromCompiler) : BfCastFlags_None);
  19127. PerformBinaryOperation(resultType, convLeftValue, convRightValue, binaryOp, opToken);
  19128. }
  19129. void BfExprEvaluator::PerformBinaryOperation(BfType* resultType, BfIRValue convLeftValue, BfIRValue convRightValue, BfBinaryOp binaryOp, BfAstNode* opToken)
  19130. {
  19131. if (resultType->IsValuelessType())
  19132. {
  19133. switch (binaryOp)
  19134. {
  19135. case BfBinaryOp_Equality:
  19136. case BfBinaryOp_StrictEquality:
  19137. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConst(BfTypeCode_Boolean, 1),
  19138. mModule->GetPrimitiveType(BfTypeCode_Boolean));
  19139. return;
  19140. case BfBinaryOp_InEquality:
  19141. case BfBinaryOp_StrictInEquality:
  19142. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConst(BfTypeCode_Boolean, 0),
  19143. mModule->GetPrimitiveType(BfTypeCode_Boolean));
  19144. return;
  19145. }
  19146. }
  19147. if ((!convLeftValue) || (!convRightValue))
  19148. return;
  19149. if (resultType->IsPrimitiveType())
  19150. {
  19151. auto primType = (BfPrimitiveType*)resultType;
  19152. if (primType->mTypeDef->mTypeCode == BfTypeCode_Boolean)
  19153. {
  19154. switch (binaryOp)
  19155. {
  19156. case BfBinaryOp_Equality:
  19157. case BfBinaryOp_StrictEquality:
  19158. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateCmpEQ(convLeftValue, convRightValue),
  19159. mModule->GetPrimitiveType(BfTypeCode_Boolean));
  19160. break;
  19161. case BfBinaryOp_InEquality:
  19162. case BfBinaryOp_StrictInEquality:
  19163. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateCmpNE(convLeftValue, convRightValue),
  19164. mModule->GetPrimitiveType(BfTypeCode_Boolean));
  19165. break;
  19166. case BfBinaryOp_BitwiseAnd:
  19167. case BfBinaryOp_ConditionalAnd:
  19168. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateAnd(convLeftValue, convRightValue),
  19169. mModule->GetPrimitiveType(BfTypeCode_Boolean));
  19170. break;
  19171. case BfBinaryOp_BitwiseOr:
  19172. case BfBinaryOp_ConditionalOr:
  19173. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateOr(convLeftValue, convRightValue),
  19174. mModule->GetPrimitiveType(BfTypeCode_Boolean));
  19175. break;
  19176. case BfBinaryOp_ExclusiveOr:
  19177. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateXor(convLeftValue, convRightValue),
  19178. mModule->GetPrimitiveType(BfTypeCode_Boolean));
  19179. break;
  19180. default:
  19181. mModule->Fail("Invalid operation for booleans", opToken);
  19182. break;
  19183. }
  19184. return;
  19185. }
  19186. }
  19187. if ((!resultType->IsIntegral()) && (!resultType->IsFloat()))
  19188. {
  19189. mModule->Fail(StrFormat("Cannot perform operation on type '%s'", mModule->TypeToString(resultType).c_str()), opToken);
  19190. return;
  19191. }
  19192. if (resultType->IsIntegral())
  19193. {
  19194. switch (binaryOp)
  19195. {
  19196. case BfBinaryOp_BitwiseAnd:
  19197. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateAnd(convLeftValue, convRightValue), resultType);
  19198. return;
  19199. case BfBinaryOp_BitwiseOr:
  19200. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateOr(convLeftValue, convRightValue), resultType);
  19201. return;
  19202. case BfBinaryOp_ExclusiveOr:
  19203. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateXor(convLeftValue, convRightValue), resultType);
  19204. return;
  19205. case BfBinaryOp_LeftShift:
  19206. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateShl(convLeftValue, convRightValue), resultType);
  19207. mModule->CheckRangeError(resultType, opToken);
  19208. return;
  19209. case BfBinaryOp_RightShift:
  19210. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateShr(convLeftValue, convRightValue, resultType->IsSigned()), resultType);
  19211. return;
  19212. default: break;
  19213. }
  19214. }
  19215. if ((resultType->IsChar()) &&
  19216. ((binaryOp == BfBinaryOp_Multiply) ||
  19217. (binaryOp == BfBinaryOp_Divide) ||
  19218. (binaryOp == BfBinaryOp_Modulus)))
  19219. {
  19220. mModule->Fail(StrFormat("Cannot perform operation on type '%s'", mModule->TypeToString(resultType).c_str()), opToken);
  19221. return;
  19222. }
  19223. switch (binaryOp)
  19224. {
  19225. case BfBinaryOp_Add:
  19226. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateAdd(convLeftValue, convRightValue), resultType);
  19227. mModule->CheckRangeError(resultType, opToken);
  19228. break;
  19229. case BfBinaryOp_Subtract:
  19230. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateSub(convLeftValue, convRightValue), resultType);
  19231. mModule->CheckRangeError(resultType, opToken);
  19232. break;
  19233. case BfBinaryOp_Multiply:
  19234. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateMul(convLeftValue, convRightValue), resultType);
  19235. mModule->CheckRangeError(resultType, opToken);
  19236. break;
  19237. case BfBinaryOp_Divide:
  19238. {
  19239. bool isZero = false;
  19240. if (convRightValue.IsConst())
  19241. {
  19242. auto constVal = mModule->mBfIRBuilder->GetConstant(convRightValue);
  19243. if (BfIRBuilder::IsInt(constVal->mTypeCode))
  19244. isZero = constVal->mInt64 == 0;
  19245. }
  19246. if (isZero)
  19247. {
  19248. mModule->Fail("Divide by zero", opToken);
  19249. mResult = mModule->GetDefaultTypedValue(resultType);
  19250. }
  19251. else
  19252. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateDiv(convLeftValue, convRightValue, resultType->IsSigned()), resultType);
  19253. }
  19254. break;
  19255. case BfBinaryOp_Modulus:
  19256. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateRem(convLeftValue, convRightValue, resultType->IsSigned()), resultType);
  19257. break;
  19258. case BfBinaryOp_Equality:
  19259. case BfBinaryOp_StrictEquality:
  19260. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateCmpEQ(convLeftValue, convRightValue),
  19261. mModule->GetPrimitiveType(BfTypeCode_Boolean));
  19262. break;
  19263. case BfBinaryOp_InEquality:
  19264. case BfBinaryOp_StrictInEquality:
  19265. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateCmpNE(convLeftValue, convRightValue),
  19266. mModule->GetPrimitiveType(BfTypeCode_Boolean));
  19267. break;
  19268. case BfBinaryOp_LessThan:
  19269. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateCmpLT(convLeftValue, convRightValue, resultType->IsSigned()),
  19270. mModule->GetPrimitiveType(BfTypeCode_Boolean));
  19271. break;
  19272. case BfBinaryOp_LessThanOrEqual:
  19273. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateCmpLTE(convLeftValue, convRightValue, resultType->IsSigned()),
  19274. mModule->GetPrimitiveType(BfTypeCode_Boolean));
  19275. break;
  19276. case BfBinaryOp_GreaterThan:
  19277. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateCmpGT(convLeftValue, convRightValue, resultType->IsSigned()),
  19278. mModule->GetPrimitiveType(BfTypeCode_Boolean));
  19279. break;
  19280. case BfBinaryOp_GreaterThanOrEqual:
  19281. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateCmpGTE(convLeftValue, convRightValue, resultType->IsSigned()),
  19282. mModule->GetPrimitiveType(BfTypeCode_Boolean));
  19283. break;
  19284. case BfBinaryOp_Compare:
  19285. {
  19286. auto intType = mModule->GetPrimitiveType(BfTypeCode_IntPtr);
  19287. if ((convLeftValue.IsConst()) && (convRightValue.IsConst()))
  19288. {
  19289. auto cmpLtVal = mModule->mBfIRBuilder->CreateCmpLT(convLeftValue, convRightValue, resultType->IsSigned());
  19290. auto ltConstant = mModule->mBfIRBuilder->GetConstant(cmpLtVal);
  19291. if (ltConstant->mBool)
  19292. {
  19293. mResult = BfTypedValue(mModule->GetConstValue(-1, mModule->GetPrimitiveType(BfTypeCode_IntPtr)), intType);
  19294. }
  19295. else
  19296. {
  19297. auto cmpGtVal = mModule->mBfIRBuilder->CreateCmpGT(convLeftValue, convRightValue, resultType->IsSigned());
  19298. auto rtConstant = mModule->mBfIRBuilder->GetConstant(cmpGtVal);
  19299. if (rtConstant->mBool)
  19300. mResult = BfTypedValue(mModule->GetConstValue(1, mModule->GetPrimitiveType(BfTypeCode_IntPtr)), intType);
  19301. else
  19302. mResult = BfTypedValue(mModule->GetConstValue(0, mModule->GetPrimitiveType(BfTypeCode_IntPtr)), intType);
  19303. }
  19304. }
  19305. else if ((resultType->IsIntegral()) && (resultType->mSize < intType->mSize))
  19306. {
  19307. auto leftIntValue = mModule->mBfIRBuilder->CreateNumericCast(convLeftValue, resultType->IsSigned(), BfTypeCode_IntPtr);
  19308. auto rightIntValue = mModule->mBfIRBuilder->CreateNumericCast(convRightValue, resultType->IsSigned(), BfTypeCode_IntPtr);
  19309. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateSub(leftIntValue, rightIntValue), intType);
  19310. }
  19311. else
  19312. {
  19313. BfIRBlock checkGtBlock = mModule->mBfIRBuilder->CreateBlock("cmpCheckGt");
  19314. BfIRBlock eqBlock = mModule->mBfIRBuilder->CreateBlock("cmpEq");
  19315. BfIRBlock endBlock = mModule->mBfIRBuilder->CreateBlock("cmpEnd");
  19316. auto startBlock = mModule->mBfIRBuilder->GetInsertBlock();
  19317. auto cmpLtVal = mModule->mBfIRBuilder->CreateCmpLT(convLeftValue, convRightValue, resultType->IsSigned());
  19318. mModule->mBfIRBuilder->CreateCondBr(cmpLtVal, endBlock, checkGtBlock);
  19319. mModule->mBfIRBuilder->AddBlock(checkGtBlock);
  19320. mModule->mBfIRBuilder->SetInsertPoint(checkGtBlock);
  19321. auto cmpGtVal = mModule->mBfIRBuilder->CreateCmpGT(convLeftValue, convRightValue, resultType->IsSigned());
  19322. mModule->mBfIRBuilder->CreateCondBr(cmpGtVal, endBlock, eqBlock);
  19323. mModule->mBfIRBuilder->AddBlock(eqBlock);
  19324. mModule->mBfIRBuilder->SetInsertPoint(eqBlock);
  19325. mModule->mBfIRBuilder->CreateBr(endBlock);
  19326. mModule->mBfIRBuilder->AddBlock(endBlock);
  19327. mModule->mBfIRBuilder->SetInsertPoint(endBlock);
  19328. auto phiVal = mModule->mBfIRBuilder->CreatePhi(mModule->mBfIRBuilder->MapType(intType), 3);
  19329. mModule->mBfIRBuilder->AddPhiIncoming(phiVal, mModule->mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, -1), startBlock);
  19330. mModule->mBfIRBuilder->AddPhiIncoming(phiVal, mModule->mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, 1), checkGtBlock);
  19331. mModule->mBfIRBuilder->AddPhiIncoming(phiVal, mModule->mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, 0), eqBlock);
  19332. mResult = BfTypedValue(phiVal, intType);
  19333. }
  19334. }
  19335. break;
  19336. default:
  19337. mModule->Fail("Invalid operation", opToken);
  19338. break;
  19339. }
  19340. }
  19341. void BfExprEvaluator::Visit(BfBinaryOperatorExpression* binOpExpr)
  19342. {
  19343. BfAutoParentNodeEntry autoParentNodeEntry(mModule, binOpExpr);
  19344. // There are a few binary operations that could actually be casts followed by an unary operation
  19345. // We can't determine that until we know whether the identifier in the parens is a typename or not
  19346. // (double)-1.0 (intptr)&val (BaseStruct)*val
  19347. BfUnaryOp unaryOp = BfUnaryOp_None;
  19348. switch (binOpExpr->mOp)
  19349. {
  19350. case BfBinaryOp_Add: unaryOp = BfUnaryOp_Positive; break;
  19351. case BfBinaryOp_Subtract: unaryOp = BfUnaryOp_Negate; break;
  19352. case BfBinaryOp_Multiply: unaryOp = BfUnaryOp_Dereference; break;
  19353. case BfBinaryOp_BitwiseAnd: unaryOp = BfUnaryOp_AddressOf; break;
  19354. default: break;
  19355. }
  19356. if (unaryOp != BfUnaryOp_None)
  19357. {
  19358. if (auto parenExpr = BfNodeDynCast<BfParenthesizedExpression>(binOpExpr->mLeft))
  19359. {
  19360. if (auto castTypeExpr = BfNodeDynCast<BfIdentifierNode>(parenExpr->mExpression))
  19361. {
  19362. SetAndRestoreValue<bool> prevIgnoreError(mModule->mIgnoreErrors, true);
  19363. auto resolvedType = mModule->ResolveTypeRef(castTypeExpr, NULL);
  19364. prevIgnoreError.Restore();
  19365. if (resolvedType != NULL)
  19366. {
  19367. if (auto rightBinOpExpr = BfNodeDynCast<BfBinaryOperatorExpression>(binOpExpr->mRight))
  19368. {
  19369. int leftPrecedence = BfGetBinaryOpPrecendence(binOpExpr->mOp);
  19370. int rightPrecedence = BfGetBinaryOpPrecendence(rightBinOpExpr->mOp);
  19371. // Do we have a precedence order issue due to mis-parsing this?
  19372. // An example is: "(int)-5.5 * 10"
  19373. if (rightPrecedence > leftPrecedence)
  19374. {
  19375. mModule->FailAfter("Cast target must be wrapped in parentheses", binOpExpr->mLeft);
  19376. }
  19377. }
  19378. PerformUnaryOperation(binOpExpr->mRight, unaryOp, binOpExpr->mOpToken, BfUnaryOpFlag_None);
  19379. if (mResult)
  19380. {
  19381. mResult = mModule->LoadValue(mResult);
  19382. mResult = mModule->Cast(binOpExpr, mResult, resolvedType, BfCastFlags_Explicit);
  19383. }
  19384. return;
  19385. }
  19386. }
  19387. }
  19388. }
  19389. if ((binOpExpr->mOp == BfBinaryOp_LeftShift) || (binOpExpr->mOp == BfBinaryOp_RightShift) ||
  19390. (binOpExpr->mOp == BfBinaryOp_BitwiseAnd) || (binOpExpr->mOp == BfBinaryOp_BitwiseOr) ||
  19391. (binOpExpr->mOp == BfBinaryOp_ExclusiveOr))
  19392. {
  19393. for (int side = 0; side < 2; side++)
  19394. {
  19395. if (auto innerBinOpExpr = BfNodeDynCast<BfBinaryOperatorExpression>((side == 0) ? binOpExpr->mLeft : binOpExpr->mRight))
  19396. {
  19397. if ((innerBinOpExpr->mOp == BfBinaryOp_Add) || (innerBinOpExpr->mOp == BfBinaryOp_Subtract))
  19398. {
  19399. mModule->Warn(BfWarning_C4554_PossiblePrecedenceError, "Check operator precedence for possible error. Consider using parentheses to clarify precedence", innerBinOpExpr);
  19400. }
  19401. }
  19402. }
  19403. }
  19404. if (binOpExpr->mRight == NULL)
  19405. {
  19406. // We visit the children for autocompletion only
  19407. if (binOpExpr->mLeft != NULL)
  19408. VisitChild(binOpExpr->mLeft);
  19409. if (mResult)
  19410. {
  19411. auto autoComplete = GetAutoComplete();
  19412. if (autoComplete != NULL)
  19413. autoComplete->CheckEmptyStart(binOpExpr->mOpToken, mResult.mType);
  19414. }
  19415. if (binOpExpr->mRight != NULL)
  19416. VisitChild(binOpExpr->mRight);
  19417. return;
  19418. }
  19419. PerformBinaryOperation(binOpExpr->mLeft, binOpExpr->mRight, binOpExpr->mOp, binOpExpr->mOpToken, BfBinOpFlag_None);
  19420. }