BfExprEvaluator.cpp 781 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908
  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->GetLatest() == wantGenericType->mTypeDef->GetLatest())
  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->IsInstanceOf(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->IsInstanceOf(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 = mModule->mCurMethodInstance->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. // For operators, prefer explicit comparison over '<=>' comparison operator
  931. if ((!isBetter) && (!isWorse))
  932. {
  933. if ((prevMethodDef->mIsOperator) && (newMethodDef->mIsOperator))
  934. {
  935. bool newIsComparison = ((BfOperatorDeclaration*)newMethodDef->mMethodDeclaration)->mBinOp == BfBinaryOp_Compare;
  936. bool prevIsComparison = ((BfOperatorDeclaration*)prevMethodDef->mMethodDeclaration)->mBinOp == BfBinaryOp_Compare;
  937. RETURN_BETTER_OR_WORSE(!newIsComparison, !prevIsComparison);
  938. }
  939. }
  940. if ((newMethodInstance->mMethodDef->mExternalConstraints.size() != 0) || (prevMethodInstance->mMethodDef->mExternalConstraints.size() != 0))
  941. {
  942. struct GenericParamPair
  943. {
  944. BfGenericMethodParamInstance* mParams[2];
  945. GenericParamPair()
  946. {
  947. mParams[0] = NULL;
  948. mParams[1] = NULL;
  949. }
  950. };
  951. Dictionary<BfType*, GenericParamPair> externConstraints;
  952. auto _GetParams = [&](int idx, BfMethodInstance* methodInstance)
  953. {
  954. for (int externConstraintIdx = 0; externConstraintIdx < (int)methodInstance->mMethodDef->mExternalConstraints.size(); externConstraintIdx++)
  955. {
  956. auto genericParam = methodInstance->mMethodInfoEx->mGenericParams[methodInstance->mMethodDef->mGenericParams.size() + externConstraintIdx];
  957. BF_ASSERT(genericParam->mExternType != NULL);
  958. GenericParamPair* pairPtr = NULL;
  959. externConstraints.TryAdd(genericParam->mExternType, NULL, &pairPtr);
  960. pairPtr->mParams[idx] = genericParam;
  961. }
  962. };
  963. _GetParams(0, newMethodInstance);
  964. _GetParams(1, prevMethodInstance);
  965. for (auto kv : externConstraints)
  966. {
  967. SET_BETTER_OR_WORSE(mModule->AreConstraintsSubset(kv.mValue.mParams[1], kv.mValue.mParams[0]), mModule->AreConstraintsSubset(kv.mValue.mParams[0], kv.mValue.mParams[1]));
  968. }
  969. if ((isBetter) || (isWorse))
  970. {
  971. RETURN_RESULTS;
  972. }
  973. }
  974. // Does one have a body and one doesn't? Obvious!
  975. isBetter = prevMethodDef->IsEmptyPartial();
  976. isWorse = newMethodDef->IsEmptyPartial();
  977. if ((isBetter) && (isWorse))
  978. {
  979. // If both are empty partials then just bind to either
  980. isWorse = true;
  981. RETURN_RESULTS;
  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. checkArgType = mModule->ResolveGenericMethodTypeRef(comptypeConstraint, methodInstance, genericParamInst, methodGenericArgs);
  1357. if (checkArgType == NULL)
  1358. return false;
  1359. }
  1360. }
  1361. if (checkArgType == NULL)
  1362. return false;
  1363. if (checkArgType->IsVar())
  1364. return false;
  1365. (*methodGenericArgs)[genericParamType->mGenericParamIdx] = checkArgType;
  1366. return true;
  1367. }
  1368. bool BfMethodMatcher::CheckMethod(BfTypeInstance* targetTypeInstance, BfTypeInstance* typeInstance, BfMethodDef* checkMethod, bool isFailurePass)
  1369. {
  1370. BP_ZONE("BfMethodMatcher::CheckMethod");
  1371. BackupMatchKind curMatchKind = BackupMatchKind_None;
  1372. bool hadMatch = false;
  1373. // Never consider overrides - they only get found at original method declaration
  1374. // mBypassVirtual gets set when we are doing an explicit "base" call, or when we are a struct --
  1375. // because on structs we know the exact type
  1376. if ((checkMethod->mIsOverride) && (!mBypassVirtual) && (!typeInstance->IsValueType()))
  1377. return false;
  1378. mMethodCheckCount++;
  1379. BfMethodInstance* methodInstance = mModule->GetRawMethodInstance(typeInstance, checkMethod);
  1380. if (methodInstance == NULL)
  1381. {
  1382. BFMODULE_FATAL(mModule, "Failed to get raw method in BfMethodMatcher::CheckMethod");
  1383. return false;
  1384. }
  1385. BfMethodInstance* typeUnspecMethodInstance = mModule->GetUnspecializedMethodInstance(methodInstance, true);
  1386. BfTypeVector* typeGenericArguments = NULL;
  1387. if (typeInstance->mGenericTypeInfo != NULL)
  1388. typeGenericArguments = &typeInstance->mGenericTypeInfo->mTypeGenericArguments;
  1389. if ((mInterfaceMethodInstance != NULL) && (methodInstance->GetExplicitInterface() != NULL))
  1390. {
  1391. BfTypeInstance* wantInterface = mInterfaceMethodInstance->mMethodInstanceGroup->mOwner;
  1392. if (wantInterface != methodInstance->GetExplicitInterface())
  1393. return false;
  1394. }
  1395. if ((checkMethod->mIsVirtual) && (!checkMethod->mIsOverride) && (!mBypassVirtual) &&
  1396. (targetTypeInstance != NULL) && (targetTypeInstance->IsObject()))
  1397. {
  1398. mModule->PopulateType(targetTypeInstance, BfPopulateType_DataAndMethods);
  1399. if ((methodInstance->mVirtualTableIdx < targetTypeInstance->mVirtualMethodTable.mSize) && (methodInstance->mVirtualTableIdx >= 0))
  1400. {
  1401. BfVirtualMethodEntry& vEntry = targetTypeInstance->mVirtualMethodTable[methodInstance->mVirtualTableIdx];
  1402. auto implMethod = (BfMethodInstance*)vEntry.mImplementingMethod;
  1403. if ((implMethod != methodInstance) && (implMethod != NULL))
  1404. {
  1405. SetAndRestoreValue<bool> prevBypassVirtual(mBypassVirtual, true);
  1406. return CheckMethod(targetTypeInstance, implMethod->GetOwner(), implMethod->mMethodDef, isFailurePass);
  1407. }
  1408. }
  1409. else
  1410. {
  1411. // Being in autocomplete mode is the only excuse for not having the virtual method table slotted
  1412. if ((!mModule->mCompiler->IsAutocomplete()) && (!targetTypeInstance->mTypeFailed) && (!targetTypeInstance->IsUnspecializedTypeVariation()))
  1413. {
  1414. mModule->AssertErrorState();
  1415. }
  1416. }
  1417. }
  1418. BfGenericInferContext genericInferContext;
  1419. genericInferContext.mModule = mModule;
  1420. genericInferContext.mCheckMethodGenericArguments = &mCheckMethodGenericArguments;
  1421. HashSet<int> allowEmptyGenericSet;
  1422. BfAutoComplete* autoComplete = NULL;
  1423. if ((mModule->mCompiler->mResolvePassData != NULL) && (!isFailurePass) && ((mBfEvalExprFlags & BfEvalExprFlags_NoAutoComplete) == 0))
  1424. autoComplete = mModule->mCompiler->mResolvePassData->mAutoComplete;
  1425. if (checkMethod->mMethodType != BfMethodType_Extension)
  1426. {
  1427. if (((checkMethod->mIsStatic) && (!mAllowStatic)) ||
  1428. ((!checkMethod->mIsStatic) && (!mAllowNonStatic)))
  1429. {
  1430. if (!typeInstance->IsFunction())
  1431. autoComplete = NULL;
  1432. }
  1433. }
  1434. if ((autoComplete != NULL) && (autoComplete->mIsCapturingMethodMatchInfo))
  1435. {
  1436. BfAutoComplete::MethodMatchEntry methodMatchEntry;
  1437. methodMatchEntry.mMethodDef = checkMethod;
  1438. methodMatchEntry.mTypeInstance = typeInstance;
  1439. methodMatchEntry.mCurMethodInstance = mModule->mCurMethodInstance;
  1440. autoComplete->mMethodMatchInfo->mInstanceList.push_back(methodMatchEntry);
  1441. }
  1442. BfTypeVector* genericArgumentsSubstitute = NULL;
  1443. int argIdx = 0;
  1444. int argMatchCount = 0;
  1445. bool needInferGenericParams = (checkMethod->mGenericParams.size() != 0) && (!mHadExplicitGenericArguments);
  1446. int paramIdx = 0;
  1447. BfType* paramsElementType = NULL;
  1448. if (checkMethod->mHasAppend)
  1449. paramIdx++;
  1450. int uniqueGenericStartIdx = mModule->GetLocalInferrableGenericArgCount(checkMethod);
  1451. if ((mHadExplicitGenericArguments) && (checkMethod->mGenericParams.size() != mExplicitMethodGenericArguments.size() + uniqueGenericStartIdx))
  1452. goto NoMatch;
  1453. for (auto& checkGenericArgRef : mCheckMethodGenericArguments)
  1454. checkGenericArgRef = NULL;
  1455. mCheckMethodGenericArguments.resize(checkMethod->mGenericParams.size());
  1456. for (auto& genericArgRef : mCheckMethodGenericArguments)
  1457. genericArgRef = NULL;
  1458. if (mHadExplicitGenericArguments)
  1459. {
  1460. if (uniqueGenericStartIdx > 0)
  1461. {
  1462. genericArgumentsSubstitute = &mCheckMethodGenericArguments;
  1463. mCheckMethodGenericArguments.clear();
  1464. mCheckMethodGenericArguments.reserve(mExplicitMethodGenericArguments.size() + uniqueGenericStartIdx);
  1465. for (int i = 0; i < uniqueGenericStartIdx; i++)
  1466. mCheckMethodGenericArguments.Add(NULL);
  1467. for (int i = 0; i < (int)mExplicitMethodGenericArguments.size(); i++)
  1468. mCheckMethodGenericArguments.Add(mExplicitMethodGenericArguments[i]);
  1469. }
  1470. else
  1471. {
  1472. genericArgumentsSubstitute = &mExplicitMethodGenericArguments;
  1473. }
  1474. }
  1475. else if (needInferGenericParams)
  1476. genericArgumentsSubstitute = &mCheckMethodGenericArguments;
  1477. if ((checkMethod->mIsMutating) && (targetTypeInstance != NULL) && (targetTypeInstance->IsValueType()) &&
  1478. ((mTarget.IsReadOnly()) || (!mTarget.IsAddr())) &&
  1479. (!targetTypeInstance->IsValuelessType()))
  1480. {
  1481. goto NoMatch;
  1482. }
  1483. if (mSkipImplicitParams)
  1484. {
  1485. //paramOfs = methodInstance->GetImplicitParamCount();
  1486. //paramIdx += paramOfs;
  1487. }
  1488. if (needInferGenericParams)
  1489. {
  1490. genericInferContext.mPrevArgValues.resize(checkMethod->mGenericParams.size());
  1491. int paramOfs = methodInstance->GetImplicitParamCount();
  1492. int paramCount = methodInstance->GetParamCount();
  1493. SizedArray<int, 8> deferredArgs;
  1494. int argIdx = 0;
  1495. int paramIdx = 0;
  1496. if (checkMethod->mHasAppend)
  1497. paramIdx++;
  1498. if (checkMethod->mMethodType == BfMethodType_Extension)
  1499. {
  1500. argIdx--;
  1501. }
  1502. paramIdx += paramOfs;
  1503. bool hadInferFailure = false;
  1504. int inferParamOffset = paramOfs - argIdx;
  1505. enum ResultKind
  1506. {
  1507. ResultKind_Ok,
  1508. ResultKind_Failed,
  1509. ResultKind_Deferred,
  1510. };
  1511. auto _CheckArg = [&](int argIdx)
  1512. {
  1513. paramIdx = argIdx + inferParamOffset;
  1514. auto wantType = methodInstance->GetParamType(paramIdx);
  1515. auto checkType = wantType;
  1516. auto origCheckType = checkType;
  1517. if (checkType->IsGenericParam())
  1518. {
  1519. BfGenericParamInstance* genericParamInstance = NULL;
  1520. auto genericParamType = (BfGenericParamType*)checkType;
  1521. checkType = NULL;
  1522. if (genericParamType->mGenericParamKind == BfGenericParamKind_Method)
  1523. {
  1524. if ((genericArgumentsSubstitute != NULL) && (genericParamType->mGenericParamIdx < (int)genericArgumentsSubstitute->size()))
  1525. checkType = (*genericArgumentsSubstitute)[genericParamType->mGenericParamIdx];
  1526. genericParamInstance = methodInstance->mMethodInfoEx->mGenericParams[genericParamType->mGenericParamIdx];
  1527. }
  1528. else
  1529. genericParamInstance = mModule->GetGenericParamInstance(genericParamType);
  1530. if (checkType == NULL)
  1531. {
  1532. checkType = genericParamInstance->mTypeConstraint;
  1533. origCheckType = checkType; // We can do "ResolveGenericType" on this type
  1534. }
  1535. }
  1536. bool attemptedGenericResolve = false;
  1537. if ((checkType != NULL) && (genericArgumentsSubstitute != NULL) && (checkType->IsUnspecializedType()))
  1538. {
  1539. attemptedGenericResolve = true;
  1540. checkType = mModule->ResolveGenericType(origCheckType, NULL, genericArgumentsSubstitute);
  1541. }
  1542. if (wantType->IsUnspecializedType())
  1543. {
  1544. BfTypedValue argTypedValue;
  1545. if (argIdx == -1)
  1546. {
  1547. if (mOrigTarget)
  1548. argTypedValue = mOrigTarget;
  1549. else
  1550. argTypedValue = mTarget;
  1551. }
  1552. else
  1553. {
  1554. BfResolveArgFlags flags = BfResolveArgFlag_FromGeneric;
  1555. if (wantType->IsGenericParam())
  1556. flags = (BfResolveArgFlags)(flags | BfResolveArgFlag_FromGenericParam);
  1557. argTypedValue = ResolveArgTypedValue(mArguments[argIdx], checkType, genericArgumentsSubstitute, origCheckType, flags);
  1558. }
  1559. if (!argTypedValue.IsUntypedValue())
  1560. {
  1561. auto type = argTypedValue.mType;
  1562. if (!argTypedValue)
  1563. {
  1564. if ((checkType == NULL) && (attemptedGenericResolve) && (genericInferContext.GetUnresolvedCount() >= 2))
  1565. {
  1566. deferredArgs.Add(argIdx);
  1567. return ResultKind_Deferred;
  1568. }
  1569. return ResultKind_Failed;
  1570. }
  1571. if (type->IsVar())
  1572. mHasVarArguments = true;
  1573. genericInferContext.mCheckedTypeSet.Clear();
  1574. if (!genericInferContext.InferGenericArgument(methodInstance, type, wantType, argTypedValue.mValue))
  1575. return ResultKind_Failed;
  1576. }
  1577. }
  1578. return ResultKind_Ok;
  1579. };
  1580. for (; argIdx < (int)mArguments.size(); argIdx++)
  1581. {
  1582. paramIdx = argIdx + inferParamOffset;
  1583. if (paramIdx >= paramCount)
  1584. break; // Possible for delegate 'params' type methods
  1585. auto resultKind = _CheckArg(argIdx);
  1586. if (resultKind == ResultKind_Failed)
  1587. goto NoMatch;
  1588. }
  1589. if (!deferredArgs.IsEmpty())
  1590. {
  1591. genericInferContext.InferGenericArguments(methodInstance);
  1592. }
  1593. while (!deferredArgs.IsEmpty())
  1594. {
  1595. int prevDeferredSize = (int)deferredArgs.size();
  1596. for (int i = 0; i < prevDeferredSize; i++)
  1597. {
  1598. auto resultKind = _CheckArg(deferredArgs[i]);
  1599. if (resultKind == ResultKind_Failed)
  1600. goto NoMatch;
  1601. }
  1602. deferredArgs.RemoveRange(0, prevDeferredSize);
  1603. if (prevDeferredSize == deferredArgs.size())
  1604. {
  1605. // No progress
  1606. goto NoMatch;
  1607. }
  1608. }
  1609. //
  1610. {
  1611. int paramIdx = (int)mArguments.size() + paramOfs;
  1612. while (paramIdx < checkMethod->mParams.size())
  1613. {
  1614. if ((paramIdx < methodInstance->mDefaultValues.size()) && (methodInstance->mDefaultValues[paramIdx]))
  1615. {
  1616. auto wantType = methodInstance->GetParamType(paramIdx);
  1617. auto checkType = wantType;
  1618. if (checkType->IsGenericParam())
  1619. {
  1620. BfGenericParamInstance* genericParamInstance = NULL;
  1621. auto genericParamType = (BfGenericParamType*)checkType;
  1622. if (genericParamType->mGenericParamKind == BfGenericParamKind_Method)
  1623. {
  1624. if ((genericArgumentsSubstitute != NULL) && (genericParamType->mGenericParamIdx < (int)genericArgumentsSubstitute->size()))
  1625. checkType = (*genericArgumentsSubstitute)[genericParamType->mGenericParamIdx];
  1626. genericParamInstance = methodInstance->mMethodInfoEx->mGenericParams[genericParamType->mGenericParamIdx];
  1627. if ((genericParamInstance->mGenericParamFlags & BfGenericParamFlag_Const) != 0)
  1628. {
  1629. if (mCheckMethodGenericArguments[genericParamType->mGenericParamIdx] == NULL)
  1630. allowEmptyGenericSet.Add(genericParamType->mGenericParamIdx);
  1631. }
  1632. }
  1633. }
  1634. }
  1635. paramIdx++;
  1636. }
  1637. }
  1638. // while (true)
  1639. // {
  1640. //
  1641. // }
  1642. //
  1643. bool failed = false;
  1644. bool inferredAllGenericArguments = false;
  1645. for (int pass = 0; true; pass++)
  1646. {
  1647. bool madeProgress = false;
  1648. bool hasUninferred = false;
  1649. failed = false;
  1650. for (int genericArgIdx = uniqueGenericStartIdx; genericArgIdx < (int)checkMethod->mGenericParams.size(); genericArgIdx++)
  1651. {
  1652. auto& genericArg = mCheckMethodGenericArguments[genericArgIdx];
  1653. if (genericArg == NULL)
  1654. {
  1655. auto genericParam = methodInstance->mMethodInfoEx->mGenericParams[genericArgIdx];
  1656. InferFromGenericConstraints(methodInstance, genericParam, &mCheckMethodGenericArguments);
  1657. if (genericArg != NULL)
  1658. {
  1659. if (inferredAllGenericArguments)
  1660. genericInferContext.InferGenericArguments(methodInstance, genericArgIdx);
  1661. madeProgress = true;
  1662. }
  1663. hasUninferred = true;
  1664. if (!allowEmptyGenericSet.Contains(genericArgIdx))
  1665. failed = true;
  1666. }
  1667. }
  1668. if (!hasUninferred)
  1669. break;
  1670. if (inferredAllGenericArguments)
  1671. {
  1672. if (!madeProgress)
  1673. break;
  1674. }
  1675. genericInferContext.InferGenericArguments(methodInstance);
  1676. inferredAllGenericArguments = true;
  1677. }
  1678. if (failed)
  1679. goto NoMatch;
  1680. }
  1681. if (checkMethod->mMethodType == BfMethodType_Extension)
  1682. argIdx--;
  1683. // Iterate through params
  1684. while (true)
  1685. {
  1686. // Too many arguments
  1687. if (paramIdx >= (int)methodInstance->GetParamCount())
  1688. {
  1689. break;
  1690. }
  1691. bool isDeferredEval = false;
  1692. if ((argIdx >= 0) && (methodInstance->GetParamKind(paramIdx) == BfParamKind_Params) && (paramsElementType == NULL))
  1693. {
  1694. if (argIdx >= (int) mArguments.size())
  1695. break; // No params
  1696. BfTypedValue argTypedValue = ResolveArgTypedValue(mArguments[argIdx], NULL, genericArgumentsSubstitute);
  1697. if (!argTypedValue)
  1698. goto NoMatch;
  1699. if ((!argTypedValue.HasType()) && (!mArguments[argIdx].IsDeferredEval()))
  1700. goto NoMatch;
  1701. auto paramsArrayType = methodInstance->GetParamType(paramIdx);
  1702. paramsArrayType = mModule->ResolveGenericType(paramsArrayType, NULL, genericArgumentsSubstitute);
  1703. if ((mArguments[argIdx].mArgFlags & BfArgFlag_ParamsExpr) != 0)
  1704. {
  1705. // Direct-pass params
  1706. if ((argTypedValue.IsUntypedValue()) || (mModule->CanCast(argTypedValue, paramsArrayType)))
  1707. {
  1708. argIdx++;
  1709. argMatchCount++;
  1710. paramIdx++;
  1711. break;
  1712. }
  1713. goto NoMatch;
  1714. }
  1715. if ((paramsArrayType->IsArray()) || (paramsArrayType->IsInstanceOf(mModule->mCompiler->mSpanTypeDef)))
  1716. {
  1717. paramsElementType = paramsArrayType->GetUnderlyingType();
  1718. while (argIdx < (int)mArguments.size())
  1719. {
  1720. argTypedValue = ResolveArgTypedValue(mArguments[argIdx], paramsElementType, genericArgumentsSubstitute);
  1721. if (!argTypedValue.HasType())
  1722. goto NoMatch;
  1723. if (!mModule->CanCast(argTypedValue, paramsElementType))
  1724. goto NoMatch;
  1725. argIdx++;
  1726. argMatchCount++;
  1727. }
  1728. }
  1729. else
  1730. goto NoMatch;
  1731. break;
  1732. }
  1733. if (methodInstance->IsImplicitCapture(paramIdx))
  1734. {
  1735. paramIdx++;
  1736. continue;
  1737. }
  1738. if (argIdx >= (int) mArguments.size())
  1739. {
  1740. // We have defaults the rest of the way, so that's cool
  1741. if (methodInstance->GetParamInitializer(paramIdx) != NULL)
  1742. break;
  1743. // We have unused params left over
  1744. goto NoMatch;
  1745. }
  1746. auto wantType = methodInstance->GetParamType(paramIdx);
  1747. if ((genericArgumentsSubstitute != NULL) && (wantType->IsUnspecializedType()))
  1748. {
  1749. wantType = typeUnspecMethodInstance->GetParamType(paramIdx);
  1750. auto resolvedType = mModule->ResolveGenericType(wantType, typeGenericArguments, genericArgumentsSubstitute, false);
  1751. if (resolvedType == NULL)
  1752. goto NoMatch;
  1753. wantType = resolvedType;
  1754. }
  1755. if (wantType->IsSelf())
  1756. wantType = typeInstance;
  1757. if ((argIdx >= 0) && ((mArguments[argIdx].mArgFlags & BfArgFlag_ParamsExpr) != 0))
  1758. {
  1759. // We had a 'params' expression but this method didn't have a params slot in this parameter
  1760. goto NoMatch;
  1761. }
  1762. BfTypedValue argTypedValue;
  1763. if (argIdx == -1)
  1764. argTypedValue = mTarget;
  1765. else
  1766. argTypedValue = ResolveArgTypedValue(mArguments[argIdx], wantType, genericArgumentsSubstitute);
  1767. if (!argTypedValue.IsUntypedValue())
  1768. {
  1769. if (!argTypedValue.HasType())
  1770. {
  1771. // Check to see if this is the last argument and that it's a potential enum match
  1772. if ((wantType->IsEnum()) && (argIdx == mArguments.size() - 1))
  1773. {
  1774. if (auto memberRefExpr = BfNodeDynCast<BfMemberReferenceExpression>(mArguments[argIdx].mExpression))
  1775. {
  1776. if (memberRefExpr->mTarget == NULL)
  1777. {
  1778. // Is dot expression
  1779. curMatchKind = BackupMatchKind_PartialLastArgMatch;
  1780. }
  1781. }
  1782. }
  1783. goto NoMatch;
  1784. }
  1785. else
  1786. {
  1787. if ((wantType->IsRef()) && (!argTypedValue.mType->IsRef()) &&
  1788. ((mAllowImplicitRef) || (wantType->IsIn())))
  1789. wantType = wantType->GetUnderlyingType();
  1790. if (!mModule->CanCast(argTypedValue, wantType))
  1791. goto NoMatch;
  1792. }
  1793. }
  1794. paramIdx++;
  1795. argIdx++;
  1796. argMatchCount++;
  1797. if ((autoComplete != NULL) && (autoComplete->mIsCapturingMethodMatchInfo))
  1798. {
  1799. auto methodMatchInfo = autoComplete->mMethodMatchInfo;
  1800. if (!methodMatchInfo->mHadExactMatch)
  1801. {
  1802. bool isBetter = false;
  1803. bool isWorse = false;
  1804. int methodIdx = (int)methodMatchInfo->mInstanceList.size() - 1;
  1805. if ((methodMatchInfo->mBestIdx != -1) && (methodMatchInfo->mBestIdx < (int)methodMatchInfo->mInstanceList.size()))
  1806. {
  1807. auto prevMethodMatchEntry = &methodMatchInfo->mInstanceList[methodMatchInfo->mBestIdx];
  1808. if (checkMethod->mParams.size() < mArguments.size())
  1809. {
  1810. isWorse = true;
  1811. }
  1812. else if ((prevMethodMatchEntry->mMethodDef != NULL) && (prevMethodMatchEntry->mMethodDef->mParams.size() < (int) mArguments.size()))
  1813. {
  1814. isBetter = true;
  1815. }
  1816. }
  1817. }
  1818. }
  1819. }
  1820. // Too many arguments (not all incoming arguments processed)
  1821. if (argIdx < (int)mArguments.size())
  1822. {
  1823. if (!methodInstance->IsVarArgs())
  1824. goto NoMatch;
  1825. }
  1826. if ((genericArgumentsSubstitute != NULL) && (genericArgumentsSubstitute->size() != 0))
  1827. {
  1828. for (int checkGenericIdx = uniqueGenericStartIdx; checkGenericIdx < (int)genericArgumentsSubstitute->size(); checkGenericIdx++)
  1829. {
  1830. auto& genericParams = methodInstance->mMethodInfoEx->mGenericParams;
  1831. auto genericArg = (*genericArgumentsSubstitute)[checkGenericIdx];
  1832. if (genericArg == NULL)
  1833. {
  1834. if (allowEmptyGenericSet.Contains(checkGenericIdx))
  1835. continue;
  1836. goto NoMatch;
  1837. }
  1838. if (genericArg == NULL)
  1839. goto NoMatch;
  1840. if (!mModule->CheckGenericConstraints(BfGenericParamSource(methodInstance), genericArg, NULL, genericParams[checkGenericIdx], genericArgumentsSubstitute, NULL))
  1841. goto NoMatch;
  1842. }
  1843. }
  1844. for (int externConstraintIdx = 0; externConstraintIdx < (int)checkMethod->mExternalConstraints.size(); externConstraintIdx++)
  1845. {
  1846. auto genericParam = methodInstance->mMethodInfoEx->mGenericParams[checkMethod->mGenericParams.size() + externConstraintIdx];
  1847. BF_ASSERT(genericParam->mExternType != NULL);
  1848. auto externType = genericParam->mExternType;
  1849. BfTypeVector* externGenericArgumentsSubstitute = genericArgumentsSubstitute;
  1850. if (externType->IsVar())
  1851. {
  1852. auto& externConstraint = checkMethod->mExternalConstraints[externConstraintIdx];
  1853. if (externConstraint.mTypeRef != NULL)
  1854. {
  1855. externType = mModule->ResolveGenericMethodTypeRef(externConstraint.mTypeRef, methodInstance, genericParam, genericArgumentsSubstitute);
  1856. if (externType == NULL)
  1857. goto NoMatch;
  1858. }
  1859. }
  1860. if (!mModule->CheckGenericConstraints(BfGenericParamSource(methodInstance), externType, NULL, genericParam, externGenericArgumentsSubstitute, NULL))
  1861. goto NoMatch;
  1862. }
  1863. // Method is applicable, check to see which method is better
  1864. if (mBestMethodDef != NULL)
  1865. {
  1866. bool isBetter = false;
  1867. bool isWorse = false;
  1868. BfMethodInstance* prevMethodInstance = mModule->GetRawMethodInstance(mBestMethodTypeInstance, mBestMethodDef);
  1869. bool allowSpecializeFail = mModule->mCurTypeInstance->IsUnspecializedType();
  1870. if (mModule->mCurMethodInstance != NULL)
  1871. allowSpecializeFail = mModule->mCurMethodInstance->mIsUnspecialized;
  1872. // if (mModule->mModuleName == "BeefTest_TestProgram")
  1873. // {
  1874. // OutputDebugStrF("?Prv: %s\n %s\n?New: %s\n %s\n\n",
  1875. // mModule->MethodToString(prevMethodInstance, BfMethodNameFlag_None, &mBestMethodGenericArguments).c_str(),
  1876. // mModule->MethodToString(prevMethodInstance, BfMethodNameFlag_None).c_str(),
  1877. // mModule->MethodToString(methodInstance, BfMethodNameFlag_None, genericArgumentsSubstitute).c_str(),
  1878. // mModule->MethodToString(methodInstance, BfMethodNameFlag_None).c_str());
  1879. // }
  1880. CompareMethods(prevMethodInstance, &mBestMethodGenericArguments, methodInstance, genericArgumentsSubstitute, &isBetter, &isWorse, allowSpecializeFail);
  1881. // if (mModule->mModuleName == "BeefTest_TestProgram")
  1882. // {
  1883. // OutputDebugStrF("%sPrv: %s\n %s\n%sNew: %s\n %s\n\n",
  1884. // isWorse ? "*" : " ", mModule->MethodToString(prevMethodInstance, BfMethodNameFlag_None, &mBestMethodGenericArguments).c_str(),
  1885. // mModule->MethodToString(prevMethodInstance, BfMethodNameFlag_None).c_str(),
  1886. // isBetter ? "*" : " ", mModule->MethodToString(methodInstance, BfMethodNameFlag_None, genericArgumentsSubstitute).c_str(),
  1887. // mModule->MethodToString(methodInstance, BfMethodNameFlag_None).c_str());
  1888. // }
  1889. // If we had both a 'better' and 'worse', that's ambiguous because the methods are each better in different ways (not allowed)
  1890. // And if neither better nor worse then they are equally good, which is not allowed either
  1891. if (((!isBetter) && (!isWorse)) || ((isBetter) && (isWorse)))
  1892. {
  1893. if (!mHasVarArguments)
  1894. {
  1895. // If we are ambiguous based on a subset of an extern 'var' constraint then don't throw an error
  1896. auto _CheckMethodInfo = [&](BfMethodInstance* checkMethodInstance)
  1897. {
  1898. if (checkMethodInstance->mMethodInfoEx == NULL)
  1899. return;
  1900. for (auto genericParam : checkMethodInstance->mMethodInfoEx->mGenericParams)
  1901. {
  1902. if ((genericParam->mExternType == NULL) || (!genericParam->mExternType->IsGenericParam()))
  1903. continue;
  1904. auto genericParamType = (BfGenericParamType*)genericParam->mExternType;
  1905. if (genericParamType->mGenericParamKind != BfGenericParamKind_Type)
  1906. continue;
  1907. auto externGenericParam = mModule->GetGenericParamInstance(genericParamType);
  1908. if ((externGenericParam->mGenericParamFlags & BfGenericParamFlag_Var) != 0)
  1909. mHasVarArguments = true;
  1910. }
  1911. };
  1912. _CheckMethodInfo(methodInstance);
  1913. _CheckMethodInfo(prevMethodInstance);
  1914. }
  1915. if (mHasVarArguments)
  1916. {
  1917. if (methodInstance->mReturnType != prevMethodInstance->mReturnType)
  1918. mHadVarConflictingReturnType = true;
  1919. }
  1920. else
  1921. {
  1922. BfAmbiguousEntry ambiguousEntry;
  1923. ambiguousEntry.mMethodInstance = methodInstance;
  1924. if (genericArgumentsSubstitute != NULL)
  1925. ambiguousEntry.mBestMethodGenericArguments = *genericArgumentsSubstitute;
  1926. if (methodInstance->mMethodDef->mGenericParams.size() != 0)
  1927. {
  1928. BF_ASSERT(!ambiguousEntry.mBestMethodGenericArguments.empty());
  1929. }
  1930. mAmbiguousEntries.push_back(ambiguousEntry);
  1931. goto Done;
  1932. }
  1933. }
  1934. if (!isBetter)
  1935. goto Done;
  1936. }
  1937. if ((autoComplete != NULL) && (autoComplete->mIsCapturingMethodMatchInfo))
  1938. {
  1939. auto methodMatchInfo = autoComplete->mMethodMatchInfo;
  1940. // Try to persist with previous partial match, if we have one - this keeps us from locking onto
  1941. // an incorrect method just because it had the current number of params that we've typed so far
  1942. if (methodMatchInfo->mPrevBestIdx == -1)
  1943. {
  1944. methodMatchInfo->mHadExactMatch = true;
  1945. methodMatchInfo->mBestIdx = (int) methodMatchInfo->mInstanceList.size() - 1;
  1946. }
  1947. }
  1948. mAmbiguousEntries.Clear();
  1949. hadMatch = true;
  1950. mBestMethodDef = checkMethod;
  1951. mBestRawMethodInstance = methodInstance;
  1952. for (auto& arg : mArguments)
  1953. arg.mBestBoundType = arg.mTypedValue.mType;
  1954. NoMatch:
  1955. if (!hadMatch)
  1956. {
  1957. if (mBestMethodDef != NULL)
  1958. return false;
  1959. if (checkMethod->mMethodType == BfMethodType_Extension)
  1960. {
  1961. auto thisParam = methodInstance->GetParamType(0);
  1962. auto resolveThisParam = mModule->ResolveGenericType(thisParam, NULL, &mCheckMethodGenericArguments);
  1963. if (resolveThisParam == NULL)
  1964. return false;
  1965. if (!mModule->CanCast(mTarget, resolveThisParam, BfCastFlags_Explicit))
  1966. return false;
  1967. }
  1968. if (mBackupMethodDef != NULL)
  1969. {
  1970. int prevParamDiff = (int)mBackupMethodDef->GetExplicitParamCount() - (int)mArguments.size();
  1971. int paramDiff = (int)checkMethod->GetExplicitParamCount() - (int)mArguments.size();
  1972. if ((prevParamDiff < 0) && (prevParamDiff > paramDiff))
  1973. return false;
  1974. if ((prevParamDiff >= 0) && (paramDiff < 0))
  1975. return false;
  1976. if (argMatchCount < mBackupArgMatchCount)
  1977. return false;
  1978. else if (argMatchCount == mBackupArgMatchCount)
  1979. {
  1980. if (curMatchKind < mBackupMatchKind)
  1981. return false;
  1982. // We search from the most specific type, so don't prefer a less specific type
  1983. if (mBestMethodTypeInstance != typeInstance)
  1984. return false;
  1985. }
  1986. }
  1987. if ((autoComplete != NULL) && (autoComplete->mIsCapturingMethodMatchInfo))
  1988. {
  1989. auto methodMatchInfo = autoComplete->mMethodMatchInfo;
  1990. if ((methodMatchInfo->mPrevBestIdx == -1) && (!methodMatchInfo->mHadExactMatch))
  1991. {
  1992. methodMatchInfo->mBestIdx = (int)methodMatchInfo->mInstanceList.size() - 1;
  1993. }
  1994. }
  1995. mBackupMatchKind = curMatchKind;
  1996. mBackupMethodDef = checkMethod;
  1997. mBackupArgMatchCount = argMatchCount;
  1998. // Lie temporarily to store at least one candidate (but mBestMethodDef is still NULL)
  1999. hadMatch = true;
  2000. }
  2001. if (hadMatch)
  2002. {
  2003. mBestMethodTypeInstance = typeInstance;
  2004. if (genericArgumentsSubstitute != &mBestMethodGenericArguments)
  2005. {
  2006. if (genericArgumentsSubstitute != NULL)
  2007. {
  2008. for (auto& genericArg : *genericArgumentsSubstitute)
  2009. genericArg = mModule->FixIntUnknown(genericArg);
  2010. mBestMethodGenericArguments = *genericArgumentsSubstitute;
  2011. // #ifdef _DEBUG
  2012. // for (auto arg : mBestMethodGenericArguments)
  2013. // BF_ASSERT((arg == NULL) || (!arg->IsVar()));
  2014. // #endif
  2015. }
  2016. else
  2017. mBestMethodGenericArguments.clear();
  2018. }
  2019. }
  2020. Done:
  2021. if ((autoComplete != NULL) && (autoComplete->mIsCapturingMethodMatchInfo) && (genericArgumentsSubstitute != NULL))
  2022. {
  2023. auto methodMatchInfo = autoComplete->mMethodMatchInfo;
  2024. if (!methodMatchInfo->mInstanceList.IsEmpty())
  2025. {
  2026. methodMatchInfo->mInstanceList[methodMatchInfo->mInstanceList.size() - 1].mGenericArguments = *genericArgumentsSubstitute;
  2027. }
  2028. }
  2029. return mBestMethodDef == checkMethod;
  2030. }
  2031. void BfMethodMatcher::FlushAmbiguityError()
  2032. {
  2033. if (!mAmbiguousEntries.empty())
  2034. {
  2035. if (mModule->PreFail())
  2036. {
  2037. BfError* error;
  2038. if (!mMethodName.empty())
  2039. error = mModule->Fail(StrFormat("Ambiguous method call for '%s'", mMethodName.c_str()), mTargetSrc);
  2040. else
  2041. error = mModule->Fail("Ambiguous method call", mTargetSrc);
  2042. if (error != NULL)
  2043. {
  2044. auto unspecializedType = mModule->GetUnspecializedTypeInstance(mBestMethodTypeInstance);
  2045. BfMethodInstance* bestMethodInstance = mModule->GetRawMethodInstance(unspecializedType, mBestMethodDef);
  2046. BfTypeVector* typeGenericArguments = NULL;
  2047. if (mBestMethodTypeInstance->mGenericTypeInfo != NULL)
  2048. typeGenericArguments = &mBestMethodTypeInstance->mGenericTypeInfo->mTypeGenericArguments;
  2049. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("'%s' is a candidate", mModule->MethodToString(bestMethodInstance, BfMethodNameFlag_ResolveGenericParamNames,
  2050. typeGenericArguments, mBestMethodGenericArguments.empty() ? NULL : &mBestMethodGenericArguments).c_str()),
  2051. bestMethodInstance->mMethodDef->GetRefNode());
  2052. for (auto& ambiguousEntry : mAmbiguousEntries)
  2053. {
  2054. auto typeInstance = ambiguousEntry.mMethodInstance->GetOwner();
  2055. auto unspecTypeMethodInstance = mModule->GetUnspecializedMethodInstance(ambiguousEntry.mMethodInstance, true);
  2056. BfTypeVector* typeGenericArguments = NULL;
  2057. if (typeInstance->mGenericTypeInfo != NULL)
  2058. typeGenericArguments = &typeInstance->mGenericTypeInfo->mTypeGenericArguments;
  2059. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("'%s' is a candidate", mModule->MethodToString(unspecTypeMethodInstance, BfMethodNameFlag_ResolveGenericParamNames,
  2060. typeGenericArguments, ambiguousEntry.mBestMethodGenericArguments.empty() ? NULL : &ambiguousEntry.mBestMethodGenericArguments).c_str()),
  2061. ambiguousEntry.mMethodInstance->mMethodDef->GetRefNode());
  2062. }
  2063. }
  2064. }
  2065. mAmbiguousEntries.Clear();
  2066. }
  2067. }
  2068. bool BfMethodMatcher::IsType(BfTypedValue& typedVal, BfType* type)
  2069. {
  2070. if (typedVal.mType == type)
  2071. return true;
  2072. if (!typedVal)
  2073. return false;
  2074. if (!typedVal.mType->IsPrimitiveType())
  2075. return false;
  2076. if (!type->IsPrimitiveType())
  2077. return false;
  2078. auto fromPrimType = typedVal.mType->ToPrimitiveType();
  2079. if ((fromPrimType->mTypeDef->mTypeCode != BfTypeCode_IntUnknown) &&
  2080. (fromPrimType->mTypeDef->mTypeCode != BfTypeCode_UIntUnknown))
  2081. return false;
  2082. auto constant = mModule->mBfIRBuilder->GetConstant(typedVal.mValue);
  2083. if (constant == NULL)
  2084. return false;
  2085. auto toPrimType = type->ToPrimitiveType();
  2086. if (!mModule->mBfIRBuilder->IsInt(toPrimType->mTypeDef->mTypeCode))
  2087. return false;
  2088. if (type->mSize == 8)
  2089. return false;
  2090. int64 minVal = -(1LL << (8 * type->mSize - 1));
  2091. int64 maxVal = (1LL << (8 * type->mSize - 1)) - 1;
  2092. if ((constant->mInt64 >= minVal) && (constant->mInt64 <= maxVal))
  2093. return true;
  2094. return false;
  2095. }
  2096. // This method checks all base classes before checking interfaces. Is that correct?
  2097. bool BfMethodMatcher::CheckType(BfTypeInstance* typeInstance, BfTypedValue target, bool isFailurePass, bool forceOuterCheck)
  2098. {
  2099. BfMethodDef* prevBesstMethodDef = mBestMethodDef;
  2100. auto curTypeInst = typeInstance;
  2101. auto curTypeDef = typeInstance->mTypeDef;
  2102. int checkInterfaceIdx = 0;
  2103. bool targetIsBase = target.IsBase();
  2104. bool checkExtensionBase = false;
  2105. if (targetIsBase)
  2106. {
  2107. if ((curTypeInst == mModule->mCurTypeInstance) && (curTypeInst->mTypeDef->mIsCombinedPartial))
  2108. {
  2109. checkExtensionBase = true;
  2110. }
  2111. else
  2112. {
  2113. curTypeInst = curTypeInst->mBaseType;
  2114. }
  2115. }
  2116. BfTypeInstance* targetTypeInstance = NULL;
  2117. if (target.mType != NULL)
  2118. targetTypeInstance = target.mType->ToTypeInstance();
  2119. while (true)
  2120. {
  2121. bool doSearch = true;
  2122. if ((mMethodType == BfMethodType_Extension) && (!curTypeDef->mHasExtensionMethods))
  2123. doSearch = false;
  2124. BfMethodDef* nextMethodDef = NULL;
  2125. if (doSearch)
  2126. {
  2127. curTypeDef->PopulateMemberSets();
  2128. BfMemberSetEntry* entry;
  2129. if (curTypeDef->mMethodSet.TryGetWith(mMethodName, &entry))
  2130. nextMethodDef = (BfMethodDef*)entry->mMemberDef;
  2131. }
  2132. BfProtectionCheckFlags protectionCheckFlags = BfProtectionCheckFlag_None;
  2133. if (target)
  2134. {
  2135. if (mBypassVirtual)
  2136. {
  2137. // Not an "instance lookup"
  2138. }
  2139. else
  2140. {
  2141. protectionCheckFlags = (BfProtectionCheckFlags)(protectionCheckFlags | BfProtectionCheckFlag_InstanceLookup);
  2142. }
  2143. }
  2144. while (nextMethodDef != NULL)
  2145. {
  2146. bool allowExplicitInterface = curTypeInst->IsInterface() && mBypassVirtual;
  2147. auto activeTypeDef = mModule->GetActiveTypeDef();
  2148. auto visibleProjectSet = mModule->GetVisibleProjectSet();
  2149. bool isDelegate = typeInstance->IsDelegate();
  2150. auto checkMethod = nextMethodDef;
  2151. nextMethodDef = nextMethodDef->mNextWithSameName;
  2152. if (mModule->mContext->mResolvingVarField)
  2153. {
  2154. bool isResolvingVarField = false;
  2155. auto checkTypeState = mModule->mContext->mCurTypeState;
  2156. while (checkTypeState != NULL)
  2157. {
  2158. if ((checkTypeState->mResolveKind == BfTypeState::ResolveKind_ResolvingVarType) &&
  2159. (checkTypeState->mType == typeInstance))
  2160. isResolvingVarField = true;
  2161. checkTypeState = checkTypeState->mPrevState;
  2162. }
  2163. if (isResolvingVarField)
  2164. {
  2165. // Don't even consider - we can't do method calls on ourselves when we are resolving var fields, because
  2166. // we are not allowed to generate methods when our field types are unknown. We may fix this in the future,
  2167. // but currently it breaks out expected order of operations. One issue is that our call signatures change
  2168. // depending on whether we are valueless or splattable, which depend on underlying type information
  2169. break;
  2170. }
  2171. }
  2172. if ((checkExtensionBase) && (curTypeInst == mModule->mCurTypeInstance))
  2173. {
  2174. // Accept either a method in the same project but that's the root definition, OR a method that's in a dependent project
  2175. bool accept = false;
  2176. if (activeTypeDef->mProject == checkMethod->mDeclaringType->mProject)
  2177. accept = (activeTypeDef->IsExtension()) && (!checkMethod->mDeclaringType->IsExtension());
  2178. else
  2179. accept = activeTypeDef->mProject->ContainsReference(checkMethod->mDeclaringType->mProject);
  2180. if (!accept)
  2181. continue;
  2182. }
  2183. if ((!allowExplicitInterface) && (checkMethod->mExplicitInterface != NULL) && (mInterfaceMethodInstance == NULL))
  2184. {
  2185. continue;
  2186. }
  2187. if (checkMethod->mMethodType != mMethodType)
  2188. continue;
  2189. // if (checkMethod->mName != mMethodName)
  2190. // continue;
  2191. if ((checkMethod->mDeclaringType->IsExtension()) && (mModule->mAttributeState != NULL) && (mModule->mAttributeState->mCustomAttributes != NULL) &&
  2192. (mModule->mAttributeState->mCustomAttributes->Contains(mModule->mCompiler->mNoExtensionAttributeTypeDef)))
  2193. {
  2194. mModule->mAttributeState->mUsed = true;
  2195. continue;
  2196. }
  2197. if (!isDelegate)
  2198. {
  2199. if ((!curTypeInst->IsTypeMemberIncluded(checkMethod->mDeclaringType, activeTypeDef, mModule)) ||
  2200. (!curTypeInst->IsTypeMemberAccessible(checkMethod->mDeclaringType, visibleProjectSet)))
  2201. continue;
  2202. }
  2203. MatchFailKind matchFailKind = MatchFailKind_None;
  2204. if (!mModule->CheckProtection(protectionCheckFlags, curTypeInst, checkMethod->mDeclaringType->mProject, checkMethod->mProtection, typeInstance))
  2205. {
  2206. if ((mBypassVirtual) &&
  2207. ((checkMethod->mProtection == BfProtection_Protected) || (checkMethod->mProtection == BfProtection_ProtectedInternal)) &&
  2208. (mModule->TypeIsSubTypeOf(mModule->mCurTypeInstance, typeInstance)))
  2209. {
  2210. // Allow explicit 'base' call
  2211. }
  2212. else
  2213. {
  2214. if (!isFailurePass)
  2215. continue;
  2216. matchFailKind = MatchFailKind_Protection;
  2217. }
  2218. }
  2219. if (mCheckedKind != checkMethod->mCheckedKind)
  2220. {
  2221. bool passes = true;
  2222. if (mCheckedKind != BfCheckedKind_NotSet)
  2223. {
  2224. passes = false;
  2225. }
  2226. else
  2227. {
  2228. auto defaultCheckedKind = mModule->GetDefaultCheckedKind();
  2229. if (defaultCheckedKind != checkMethod->mCheckedKind)
  2230. passes = false;
  2231. }
  2232. if (!passes)
  2233. {
  2234. if (!isFailurePass)
  2235. continue;
  2236. matchFailKind = MatchFailKind_CheckedMismatch;
  2237. }
  2238. }
  2239. CheckMethod(targetTypeInstance, curTypeInst, checkMethod, isFailurePass);
  2240. if ((isFailurePass) &&
  2241. ((mBestMethodDef == checkMethod) || (mBackupMethodDef == checkMethod)))
  2242. mMatchFailKind = matchFailKind;
  2243. }
  2244. if ((mBestMethodDef != NULL) && (mMethodType != BfMethodType_Extension))
  2245. {
  2246. if (mAutoFlushAmbiguityErrors)
  2247. FlushAmbiguityError();
  2248. return true;
  2249. }
  2250. auto baseType = curTypeInst->mBaseType;
  2251. if (baseType == NULL)
  2252. {
  2253. //TODO: Why were we doing the interface checking?
  2254. if ((curTypeInst->IsInterface()) && (curTypeInst == target.mType))
  2255. {
  2256. // When we are directly calling on interfaces rather than indirectly matching through binding
  2257. baseType = mModule->mContext->mBfObjectType;
  2258. }
  2259. else if ((curTypeInst != mModule->mContext->mBfObjectType) && (!curTypeInst->IsInterface()))
  2260. {
  2261. // This can happen for structs
  2262. baseType = mModule->mContext->mBfObjectType;
  2263. }
  2264. else if ((typeInstance->IsInterface()) && (checkInterfaceIdx < (int)typeInstance->mInterfaces.size()))
  2265. {
  2266. baseType = typeInstance->mInterfaces[checkInterfaceIdx].mInterfaceType;
  2267. checkInterfaceIdx++;
  2268. }
  2269. else
  2270. {
  2271. break;
  2272. }
  2273. }
  2274. curTypeDef = baseType->mTypeDef;
  2275. curTypeInst = baseType;
  2276. if ((isFailurePass) && (mBackupMethodDef != NULL))
  2277. break;
  2278. }
  2279. if (mBestMethodDef == NULL)
  2280. {
  2281. // FAILED, but select the first method which will fire an actual error on param type matching
  2282. mBestMethodDef = mBackupMethodDef;
  2283. }
  2284. if (((mBestMethodDef == NULL) && (!target) && (mAllowImplicitThis)) ||
  2285. (forceOuterCheck))
  2286. {
  2287. // No explicit target - maybe this was a static call in the outer type?
  2288. auto outerType = mModule->GetOuterType(typeInstance);
  2289. if (outerType != NULL)
  2290. CheckOuterTypeStaticMethods(outerType, isFailurePass);
  2291. }
  2292. if (mAutoFlushAmbiguityErrors)
  2293. FlushAmbiguityError();
  2294. return mBestMethodDef != prevBesstMethodDef;
  2295. }
  2296. void BfMethodMatcher::TryDevirtualizeCall(BfTypedValue target, BfTypedValue* origTarget, BfTypedValue* staticResult)
  2297. {
  2298. if ((mBestMethodDef == NULL) || (target.mType == NULL))
  2299. return;
  2300. if ((mModule->mCompiler->IsAutocomplete()) || (mModule->mContext->mResolvingVarField))
  2301. return;
  2302. if ((mModule->mBfIRBuilder->mIgnoreWrites) && (!mBestMethodDef->mIsConcrete))
  2303. return;
  2304. if (mBestMethodTypeInstance->IsInterface())
  2305. {
  2306. mModule->PopulateType(mBestMethodTypeInstance, BfPopulateType_DataAndMethods);
  2307. auto activeTypeDef = mModule->GetActiveTypeDef();
  2308. // Statically map this call
  2309. auto checkType = target.mType;
  2310. if (checkType->IsPointer())
  2311. checkType = ((BfPointerType*)checkType)->mElementType;
  2312. if (checkType->IsWrappableType())
  2313. checkType = mModule->GetWrappedStructType(checkType);
  2314. if ((checkType != NULL) && (checkType->IsTypeInstance()) && (!checkType->IsInterface()))
  2315. {
  2316. BfTypeInterfaceEntry* bestIFaceEntry = NULL;
  2317. auto checkTypeInst = checkType->ToTypeInstance();
  2318. if (mBestMethodTypeInstance->IsInstanceOf(mModule->mCompiler->mIHashableTypeDef))
  2319. {
  2320. if ((origTarget != NULL) && (origTarget->mType->IsPointer()) && (staticResult != NULL))
  2321. {
  2322. BfTypedValue ptrVal = mModule->LoadValue(*origTarget);
  2323. *staticResult = BfTypedValue(mModule->mBfIRBuilder->CreatePtrToInt(ptrVal.mValue, BfTypeCode_IntPtr), mModule->GetPrimitiveType(BfTypeCode_IntPtr));
  2324. return;
  2325. }
  2326. }
  2327. while (checkTypeInst != NULL)
  2328. {
  2329. mModule->PopulateType(checkTypeInst, BfPopulateType_DataAndMethods);
  2330. for (auto&& iface : checkTypeInst->mInterfaces)
  2331. {
  2332. //TODO: Why did we have this check? This caused Dictionary to not be able to devirtualize
  2333. // calls to TKey GetHashCode when TKey was from a user's project...
  2334. /*if (!checkTypeInst->IsTypeMemberAccessible(iface.mDeclaringType, activeTypeDef))
  2335. continue;*/
  2336. if (iface.mInterfaceType == mBestMethodTypeInstance)
  2337. {
  2338. if (bestIFaceEntry == NULL)
  2339. {
  2340. bestIFaceEntry = &iface;
  2341. continue;
  2342. }
  2343. bool isBetter;
  2344. bool isWorse;
  2345. mModule->CompareDeclTypes(iface.mDeclaringType, bestIFaceEntry->mDeclaringType, isBetter, isWorse);
  2346. if (isBetter == isWorse)
  2347. {
  2348. // Failed
  2349. }
  2350. else
  2351. {
  2352. if (isBetter)
  2353. bestIFaceEntry = &iface;
  2354. }
  2355. }
  2356. }
  2357. if (bestIFaceEntry != NULL)
  2358. break;
  2359. checkTypeInst = checkTypeInst->mBaseType;
  2360. if ((checkTypeInst == NULL) && (checkType->HasWrappedRepresentation()))
  2361. {
  2362. auto underlyingType = checkType->GetUnderlyingType();
  2363. if ((underlyingType != NULL) && (underlyingType->IsWrappableType()))
  2364. checkTypeInst = mModule->GetWrappedStructType(underlyingType);
  2365. }
  2366. }
  2367. if (bestIFaceEntry != NULL)
  2368. {
  2369. auto ifaceMethodEntry = checkTypeInst->mInterfaceMethodTable[bestIFaceEntry->mStartInterfaceTableIdx + mBestMethodDef->mIdx];
  2370. BfMethodInstance* bestMethodInstance = ifaceMethodEntry.mMethodRef;
  2371. if (bestMethodInstance != NULL)
  2372. {
  2373. bool isMissingArg = false;
  2374. for (auto genericArg : mBestMethodGenericArguments)
  2375. {
  2376. if (genericArg == NULL)
  2377. isMissingArg = true;
  2378. }
  2379. if (!isMissingArg)
  2380. {
  2381. // Assert error state?
  2382. mBestMethodTypeInstance = ifaceMethodEntry.mMethodRef.mTypeInstance;
  2383. mBestMethodDef = bestMethodInstance->mMethodDef;
  2384. mBestMethodInstance = mModule->GetMethodInstance(mBestMethodTypeInstance, bestMethodInstance->mMethodDef, mBestMethodGenericArguments,
  2385. bestMethodInstance->mIsForeignMethodDef ? BfGetMethodInstanceFlag_ForeignMethodDef : BfGetMethodInstanceFlag_None,
  2386. bestMethodInstance->GetForeignType());
  2387. }
  2388. }
  2389. else
  2390. {
  2391. // Failed
  2392. mFakeConcreteTarget = true;
  2393. }
  2394. }
  2395. }
  2396. }
  2397. if ((target.mType->IsValueType()) && (mBestMethodTypeInstance->IsObject()) && (mBestMethodDef->mIsVirtual))
  2398. {
  2399. auto structType = target.mType->ToTypeInstance();
  2400. auto virtualMethodInstance = mModule->GetMethodInstance(mBestMethodTypeInstance, mBestMethodDef, BfTypeVector());
  2401. BF_ASSERT(virtualMethodInstance.mMethodInstance->mVirtualTableIdx != -1);
  2402. BfTypeInstance* boxedType;
  2403. if (structType->HasOverrideMethods())
  2404. {
  2405. // We don't actually need this boxed type, so just resolve it unreified
  2406. auto useModule = mModule->mContext->mUnreifiedModule;
  2407. boxedType = useModule->CreateBoxedType(target.mType);
  2408. useModule->PopulateType(boxedType, BfPopulateType_DataAndMethods);
  2409. useModule->AddDependency(boxedType, mModule->mCurTypeInstance, BfDependencyMap::DependencyFlag_WeakReference);
  2410. }
  2411. else
  2412. {
  2413. boxedType = mModule->mContext->mBfObjectType;
  2414. }
  2415. auto methodRef = boxedType->mVirtualMethodTable[virtualMethodInstance.mMethodInstance->mVirtualTableIdx];
  2416. if (methodRef.mImplementingMethod.mTypeInstance->IsBoxed())
  2417. {
  2418. auto useModule = mModule->mContext->mUnreifiedModule;
  2419. auto boxedMethodInstance = useModule->ReferenceExternalMethodInstance(methodRef.mImplementingMethod);
  2420. BfBoxedType* vBoxedType = (BfBoxedType*)methodRef.mImplementingMethod.mTypeInstance;
  2421. mBestMethodTypeInstance = vBoxedType->mElementType->ToTypeInstance();
  2422. mBestMethodInstance = mModule->GetMethodInstance(mBestMethodTypeInstance, boxedMethodInstance.mMethodInstance->mMethodDef, BfTypeVector());
  2423. mBestMethodDef = mBestMethodInstance.mMethodInstance->mMethodDef;
  2424. }
  2425. else
  2426. {
  2427. mBestMethodTypeInstance = methodRef.mImplementingMethod.mTypeInstance;
  2428. mBestMethodInstance = mModule->ReferenceExternalMethodInstance(methodRef.mImplementingMethod);
  2429. mBestMethodDef = mBestMethodInstance.mMethodInstance->mMethodDef;
  2430. }
  2431. mBypassVirtual = true;
  2432. }
  2433. }
  2434. bool BfMethodMatcher::HasVarGenerics()
  2435. {
  2436. for (auto genericArg : mBestMethodGenericArguments)
  2437. if (genericArg->IsVar())
  2438. return true;
  2439. for (auto genericArg : mExplicitMethodGenericArguments)
  2440. if (genericArg->IsVar())
  2441. return true;
  2442. return false;
  2443. }
  2444. void BfMethodMatcher::CheckOuterTypeStaticMethods(BfTypeInstance* typeInstance, bool isFailurePass)
  2445. {
  2446. bool allowPrivate = true;
  2447. bool allowProtected = true;
  2448. auto curTypeInst = typeInstance;
  2449. auto curTypeDef = typeInstance->mTypeDef;
  2450. while (true)
  2451. {
  2452. curTypeDef->PopulateMemberSets();
  2453. BfMethodDef* nextMethodDef = NULL;
  2454. BfMemberSetEntry* entry;
  2455. if (curTypeDef->mMethodSet.TryGetWith(mMethodName, &entry))
  2456. nextMethodDef = (BfMethodDef*)entry->mMemberDef;
  2457. while (nextMethodDef != NULL)
  2458. {
  2459. auto checkMethod = nextMethodDef;
  2460. nextMethodDef = nextMethodDef->mNextWithSameName;
  2461. // These can only be invoked when the target itself is the interface
  2462. if (checkMethod->mExplicitInterface != NULL)
  2463. continue;
  2464. if ((checkMethod->mMethodType != mMethodType) || (!checkMethod->mIsStatic))
  2465. continue;
  2466. if (checkMethod->mName != mMethodName)
  2467. continue;
  2468. if ((!isFailurePass) && (!mModule->CheckProtection(checkMethod->mProtection, NULL, allowProtected, allowPrivate)))
  2469. continue;
  2470. CheckMethod(typeInstance, curTypeInst, checkMethod, isFailurePass);
  2471. }
  2472. if (mBestMethodDef != NULL)
  2473. return;
  2474. auto baseType = curTypeInst->mBaseType;
  2475. if (baseType == NULL)
  2476. break;
  2477. curTypeDef = baseType->mTypeDef;
  2478. curTypeInst = baseType;
  2479. allowPrivate = false;
  2480. if ((isFailurePass) && (mBackupMethodDef != NULL))
  2481. break;
  2482. }
  2483. if (mBestMethodDef == NULL)
  2484. {
  2485. // FAILED, but select the first method which will fire an actual error on param type matching
  2486. mBestMethodDef = mBackupMethodDef;
  2487. }
  2488. if (mBestMethodDef == NULL)
  2489. {
  2490. // No explicit target - maybe this was a static call in the outer type?
  2491. auto outerType = mModule->GetOuterType(typeInstance);
  2492. if (outerType != NULL)
  2493. CheckOuterTypeStaticMethods(outerType, isFailurePass);
  2494. }
  2495. }
  2496. //////////////////////////////////////////////////////////////////////////
  2497. void BfResolvedArgs::HandleFixits(BfModule* module)
  2498. {
  2499. auto compiler = module->mCompiler;
  2500. if ((!compiler->IsAutocomplete()) || (compiler->mResolvePassData->mResolveType != BfResolveType_GetFixits))
  2501. return;
  2502. SetAndRestoreValue<bool> ignoreErrors(module->mIgnoreErrors, true);
  2503. for (int argIdx = 0; argIdx < (int)mResolvedArgs.size(); argIdx++)
  2504. {
  2505. auto& resolvedArg = mResolvedArgs[argIdx];
  2506. auto expr = BfNodeDynCast<BfExpression>(resolvedArg.mExpression);
  2507. if (expr != NULL)
  2508. {
  2509. module->CreateValueFromExpression(expr, resolvedArg.mExpectedType);
  2510. }
  2511. }
  2512. }
  2513. //////////////////////////////////////////////////////////////////////////
  2514. BfExprEvaluator::BfExprEvaluator(BfModule* module)
  2515. {
  2516. mBfEvalExprFlags = BfEvalExprFlags_None;
  2517. mModule = module;
  2518. mPropDef = NULL;
  2519. mPropSrc = NULL;
  2520. mPropGetMethodFlags = BfGetMethodInstanceFlag_None;
  2521. mPropCheckedKind = BfCheckedKind_NotSet;
  2522. mUsedAsStatement = false;
  2523. mPropDefBypassVirtual = false;
  2524. mExpectingType = NULL;
  2525. mFunctionBindResult = NULL;
  2526. mExplicitCast = false;
  2527. mDeferCallRef = NULL;
  2528. mDeferScopeAlloc = NULL;
  2529. mPrefixedAttributeState = NULL;
  2530. mResolveGenericParam = true;
  2531. mNoBind = false;
  2532. mResultLocalVar = NULL;
  2533. mResultFieldInstance = NULL;
  2534. mResultLocalVarField = 0;
  2535. mResultLocalVarFieldCount = 0;
  2536. mResultLocalVarRefNode = NULL;
  2537. mIsVolatileReference = false;
  2538. mIsHeapReference = false;
  2539. mResultIsTempComposite = false;
  2540. mAllowReadOnlyReference = false;
  2541. mInsidePendingNullable = false;
  2542. mReceivingValue = NULL;
  2543. }
  2544. BfExprEvaluator::~BfExprEvaluator()
  2545. {
  2546. }
  2547. BfAutoComplete* BfExprEvaluator::GetAutoComplete()
  2548. {
  2549. if (mModule->mCompiler->mResolvePassData == NULL)
  2550. return NULL;
  2551. if ((mBfEvalExprFlags & BfEvalExprFlags_NoAutoComplete) != 0)
  2552. return NULL;
  2553. // For local methods- only process autocomplete on capture phase
  2554. if ((mModule->mCurMethodState != NULL) && (mModule->mCurMethodState->mClosureState != NULL) && (!mModule->mCurMethodState->mClosureState->mCapturing))
  2555. return NULL;
  2556. // if ((mModule->mCurMethodInstance != NULL) && (mModule->mCurMethodInstance->mMethodDef->mIsLocalMethod))
  2557. // return NULL;
  2558. return mModule->mCompiler->mResolvePassData->mAutoComplete;
  2559. }
  2560. bool BfExprEvaluator::IsComptime()
  2561. {
  2562. return (mModule->mIsComptimeModule) || ((mBfEvalExprFlags & BfEvalExprFlags_Comptime) != 0);
  2563. }
  2564. bool BfExprEvaluator::IsComptimeEntry()
  2565. {
  2566. if (mModule->mIsComptimeModule)
  2567. return false;
  2568. return ((mBfEvalExprFlags & BfEvalExprFlags_Comptime) != 0);
  2569. }
  2570. int BfExprEvaluator::GetStructRetIdx(BfMethodInstance* methodInstance, bool forceStatic)
  2571. {
  2572. if (IsComptime())
  2573. return -1;
  2574. return methodInstance->GetStructRetIdx(forceStatic);
  2575. }
  2576. BfType* BfExprEvaluator::BindGenericType(BfAstNode* node, BfType* bindType)
  2577. {
  2578. if ((mModule->mCurMethodState == NULL) || (mModule->mCurMethodInstance == NULL) || (bindType == NULL))
  2579. return bindType;
  2580. if ((mModule->mCurMethodState->mClosureState != NULL) && (mModule->mCurMethodState->mClosureState->mCapturing))
  2581. return bindType;
  2582. if ((mBfEvalExprFlags & BfEvalExprFlags_DeclType) != 0)
  2583. return bindType;
  2584. BF_ASSERT(!mModule->mCurMethodInstance->mIsUnspecializedVariation);
  2585. auto parser = node->GetSourceData()->ToParserData();
  2586. if (parser == NULL)
  2587. return bindType;
  2588. int64 nodeId = ((int64)parser->mDataId << 32) + node->GetSrcStart();
  2589. auto genericTypeBindings = mModule->mCurMethodState->GetRootMethodState()->mGenericTypeBindings;
  2590. if (mModule->mCurMethodInstance->mIsUnspecialized)
  2591. {
  2592. if (!bindType->IsGenericParam())
  2593. return bindType;
  2594. if (genericTypeBindings == NULL)
  2595. return bindType;
  2596. (*genericTypeBindings)[nodeId] = bindType;
  2597. return bindType;
  2598. }
  2599. else
  2600. {
  2601. if (genericTypeBindings == NULL)
  2602. return bindType;
  2603. BfType** typePtr = NULL;
  2604. if (genericTypeBindings->TryGetValue(nodeId, &typePtr))
  2605. return *typePtr;
  2606. return bindType;
  2607. }
  2608. }
  2609. BfType * BfExprEvaluator::ResolveTypeRef(BfTypeReference* typeRef, BfPopulateType populateType, BfResolveTypeRefFlags resolveFlags)
  2610. {
  2611. if (mExpectingType != NULL)
  2612. {
  2613. if (auto namedTypeRef = BfNodeDynCastExact<BfNamedTypeReference>(typeRef))
  2614. {
  2615. if (namedTypeRef->ToString() == "ExpectedType")
  2616. {
  2617. return mModule->ResolveTypeResult(typeRef, mExpectingType, populateType, resolveFlags);
  2618. }
  2619. }
  2620. }
  2621. return mModule->ResolveTypeRef(typeRef, populateType, resolveFlags);
  2622. }
  2623. void BfExprEvaluator::ResolveGenericType()
  2624. {
  2625. if (mResult)
  2626. {
  2627. if (mModule->IsUnboundGeneric(mResult.mType))
  2628. mResult.mType = mModule->GetPrimitiveType(BfTypeCode_Var);
  2629. //mResult.mType = mModule->ResolveGenericType(mResult.mType, true);
  2630. }
  2631. }
  2632. void BfExprEvaluator::Evaluate(BfAstNode* astNode, bool propogateNullConditional, bool ignoreNullConditional, bool allowSplat)
  2633. {
  2634. BP_ZONE("BfExprEvaluator::Evaluate");
  2635. // ParenthesizedExpression breaks null conditional chain
  2636. if (astNode->IsExact<BfParenthesizedExpression>())
  2637. propogateNullConditional = false;
  2638. bool scopeWasConditional = false;
  2639. BfPendingNullConditional* pendingNullCond = NULL;
  2640. mInsidePendingNullable = false;
  2641. if (mModule->mCurMethodState != NULL)
  2642. {
  2643. scopeWasConditional = mModule->mCurMethodState->mCurScope->mIsConditional;
  2644. pendingNullCond = mModule->mCurMethodState->mPendingNullConditional;
  2645. if (!propogateNullConditional)
  2646. mModule->mCurMethodState->mPendingNullConditional = NULL;
  2647. if (pendingNullCond != NULL)
  2648. {
  2649. mInsidePendingNullable = true;
  2650. mModule->mCurMethodState->mCurScope->mIsConditional = true;
  2651. }
  2652. }
  2653. astNode->Accept(this);
  2654. GetResult();
  2655. if ((mResultIsTempComposite) && (mResult.IsAddr()))
  2656. mResult.mKind = BfTypedValueKind_TempAddr;
  2657. if ((!allowSplat) && (mResult.IsSplat()))
  2658. mResult = mModule->AggregateSplat(mResult);
  2659. if ((mBfEvalExprFlags & BfEvalExprFlags_AllowIntUnknown) == 0)
  2660. mModule->FixIntUnknown(mResult);
  2661. if (!mModule->mBfIRBuilder->mIgnoreWrites)
  2662. {
  2663. if (mResult.mValue.IsConst())
  2664. {
  2665. auto constant = mModule->mBfIRBuilder->GetConstant(mResult.mValue);
  2666. if (constant->mConstType == BfConstType_TypeOf)
  2667. {
  2668. auto typeOfConst = (BfTypeOf_Const*)constant;
  2669. mResult.mValue = mModule->CreateTypeDataRef(typeOfConst->mType);
  2670. }
  2671. }
  2672. }
  2673. if (mModule->mCurMethodState != NULL)
  2674. {
  2675. if (mInsidePendingNullable)
  2676. mModule->mCurMethodState->mCurScope->mIsConditional = scopeWasConditional;
  2677. if (!propogateNullConditional)
  2678. {
  2679. if (mModule->mCurMethodState->mPendingNullConditional != NULL)
  2680. mResult = mModule->FlushNullConditional(mResult, ignoreNullConditional);
  2681. mModule->mCurMethodState->mPendingNullConditional = pendingNullCond;
  2682. }
  2683. }
  2684. }
  2685. void BfExprEvaluator::Visit(BfErrorNode* errorNode)
  2686. {
  2687. mModule->Fail("Invalid token", errorNode);
  2688. auto autoComplete = GetAutoComplete();
  2689. if (autoComplete != NULL)
  2690. {
  2691. if (auto tokenNode = BfNodeDynCast<BfTokenNode>(errorNode->mRefNode))
  2692. return;
  2693. autoComplete->CheckIdentifier(errorNode->mRefNode, true);
  2694. }
  2695. }
  2696. void BfExprEvaluator::Visit(BfTypeReference* typeRef)
  2697. {
  2698. mResult.mType = ResolveTypeRef(typeRef, BfPopulateType_Declaration);
  2699. }
  2700. void BfExprEvaluator::Visit(BfAttributedExpression* attribExpr)
  2701. {
  2702. BfAttributeState attributeState;
  2703. attributeState.mSrc = attribExpr->mAttributes;
  2704. attributeState.mTarget = (BfAttributeTargets)(BfAttributeTargets_Invocation | BfAttributeTargets_MemberAccess);
  2705. if (auto block = BfNodeDynCast<BfBlock>(attribExpr->mExpression))
  2706. attributeState.mTarget = BfAttributeTargets_Block;
  2707. attributeState.mCustomAttributes = mModule->GetCustomAttributes(attribExpr->mAttributes, attributeState.mTarget);
  2708. SetAndRestoreValue<BfAttributeState*> prevAttributeState(mModule->mAttributeState, &attributeState);
  2709. if (auto ignoreErrorsAttrib = attributeState.mCustomAttributes->Get(mModule->mCompiler->mIgnoreErrorsAttributeTypeDef))
  2710. {
  2711. SetAndRestoreValue<bool> ignoreErrors(mModule->mIgnoreErrors, true);
  2712. if (!ignoreErrorsAttrib->mCtorArgs.IsEmpty())
  2713. {
  2714. auto constant = mModule->mCurTypeInstance->mConstHolder->GetConstant(ignoreErrorsAttrib->mCtorArgs[0]);
  2715. if (constant->mBool)
  2716. attributeState.mFlags = BfAttributeState::Flag_StopOnError;
  2717. }
  2718. VisitChild(attribExpr->mExpression);
  2719. attributeState.mUsed = true;
  2720. if ((!mResult) ||
  2721. ((mResult) && (mResult.mType->IsVar())))
  2722. {
  2723. if (!mResult)
  2724. mModule->Fail("Expression did not result in a value", attribExpr->mExpression);
  2725. // Make empty or 'var' resolve as 'false' because var is only valid if we threw errors
  2726. mResult = mModule->GetDefaultTypedValue(mModule->GetPrimitiveType(BfTypeCode_Boolean));
  2727. }
  2728. }
  2729. else
  2730. {
  2731. VisitChild(attribExpr->mExpression);
  2732. }
  2733. mModule->FinishAttributeState(&attributeState);
  2734. }
  2735. void BfExprEvaluator::Visit(BfBlock* blockExpr)
  2736. {
  2737. if (mModule->mCurMethodState == NULL)
  2738. {
  2739. mModule->Fail("Illegal use of block expression", blockExpr);
  2740. return;
  2741. }
  2742. auto autoComplete = GetAutoComplete();
  2743. if ((autoComplete != NULL) && (autoComplete->mMethodMatchInfo != NULL) && (autoComplete->IsAutocompleteNode(blockExpr)))
  2744. {
  2745. // Don't show outer method match info when our cursor is inside a block (being passed as a parameter)
  2746. autoComplete->RemoveMethodMatchInfo();
  2747. }
  2748. if (blockExpr->mChildArr.IsEmpty())
  2749. {
  2750. mModule->Fail("An empty block cannot be used as an expression", blockExpr);
  2751. return;
  2752. }
  2753. bool lastWasResultExpr = false;
  2754. if (auto lastExpr = BfNodeDynCast<BfExpressionStatement>(blockExpr->mChildArr.GetLast()))
  2755. {
  2756. if (!lastExpr->IsMissingSemicolon())
  2757. mModule->Fail("Expression blocks must end in an expression which is missing its terminating semicolon", lastExpr->mTrailingSemicolon);
  2758. }
  2759. else if (blockExpr->mChildArr.GetLast()->IsExpression())
  2760. {
  2761. // Expression
  2762. }
  2763. else
  2764. {
  2765. mModule->Fail("Expression blocks must end with an expression", blockExpr);
  2766. }
  2767. mModule->VisitEmbeddedStatement(blockExpr, this, BfNodeIsA<BfUnscopedBlock>(blockExpr) ? BfEmbeddedStatementFlags_Unscoped : BfEmbeddedStatementFlags_None);
  2768. }
  2769. bool BfExprEvaluator::CheckVariableDeclaration(BfAstNode* checkNode, bool requireSimpleIfExpr, bool exprMustBeTrue, bool silentFail)
  2770. {
  2771. BfAstNode* checkChild = checkNode;
  2772. bool childWasAndRHS = false;
  2773. bool foundIf = false;
  2774. auto parentNodeEntry = mModule->mParentNodeEntry;
  2775. if (parentNodeEntry != NULL)
  2776. {
  2777. if (BfNodeIsA<BfInvocationExpression>(parentNodeEntry->mNode))
  2778. {
  2779. checkChild = parentNodeEntry->mNode;
  2780. parentNodeEntry = parentNodeEntry->mPrev;
  2781. }
  2782. }
  2783. auto _Fail = [&](const StringImpl& errorStr, BfAstNode* node)
  2784. {
  2785. if (!silentFail)
  2786. {
  2787. auto error = mModule->Fail(errorStr, node);
  2788. if ((error != NULL) && (node != checkNode))
  2789. {
  2790. mModule->mCompiler->mPassInstance->MoreInfo("See variable declaration", checkNode);
  2791. }
  2792. }
  2793. return false;
  2794. };
  2795. while (parentNodeEntry != NULL)
  2796. {
  2797. BfAstNode* checkParent = parentNodeEntry->mNode;
  2798. if (auto binOpExpr = BfNodeDynCastExact<BfBinaryOperatorExpression>(checkParent))
  2799. {
  2800. if (binOpExpr->mOp == BfBinaryOp_ConditionalAnd)
  2801. {
  2802. // This is always okay
  2803. childWasAndRHS = (binOpExpr->mRight != NULL) && (binOpExpr->mRight->Contains(checkChild));
  2804. }
  2805. else if ((binOpExpr->mOp == BfBinaryOp_ConditionalOr) && (!exprMustBeTrue))
  2806. {
  2807. if ((binOpExpr->mRight != NULL) && (binOpExpr->mRight->Contains(checkChild)))
  2808. {
  2809. return _Fail("Conditional short-circuiting may skip variable initialization", binOpExpr->mOpToken);
  2810. }
  2811. }
  2812. else
  2813. {
  2814. if (exprMustBeTrue)
  2815. {
  2816. return _Fail("Operator cannot be used with variable initialization", binOpExpr->mOpToken);
  2817. }
  2818. }
  2819. }
  2820. else if (auto parenExpr = BfNodeDynCast<BfParenthesizedExpression>(checkParent))
  2821. {
  2822. // This is okay
  2823. }
  2824. else if (auto unaryOp = BfNodeDynCast<BfUnaryOperatorExpression>(checkParent))
  2825. {
  2826. if (exprMustBeTrue)
  2827. {
  2828. return _Fail("Operator cannot be used with variable initialization", unaryOp->mOpToken);
  2829. return false;
  2830. }
  2831. if (childWasAndRHS)
  2832. {
  2833. return _Fail("Operator may allow conditional short-circuiting to skip variable initialization", unaryOp->mOpToken);
  2834. }
  2835. }
  2836. else if (auto ifStmt = BfNodeDynCast<BfIfStatement>(checkParent))
  2837. {
  2838. // Done
  2839. foundIf = true;
  2840. break;
  2841. }
  2842. else
  2843. {
  2844. if (requireSimpleIfExpr)
  2845. {
  2846. return _Fail("Variable declaration expression can only be contained in simple 'if' expressions", checkNode);
  2847. }
  2848. break;
  2849. }
  2850. checkChild = parentNodeEntry->mNode;
  2851. parentNodeEntry = parentNodeEntry->mPrev;
  2852. }
  2853. return foundIf;
  2854. }
  2855. bool BfExprEvaluator::HasVariableDeclaration(BfAstNode* checkNode)
  2856. {
  2857. BfVarDeclChecker checker;
  2858. checker.VisitChild(checkNode);
  2859. return checker.mHasVarDecl;
  2860. }
  2861. void BfExprEvaluator::Visit(BfVariableDeclaration* varDecl)
  2862. {
  2863. mModule->UpdateExprSrcPos(varDecl);
  2864. if ((mModule->mCurMethodState == NULL) || (!mModule->mCurMethodState->mCurScope->mAllowVariableDeclarations))
  2865. {
  2866. mModule->Fail("Variable declarations are not allowed in this context", varDecl);
  2867. if (varDecl->mInitializer != NULL)
  2868. {
  2869. VisitChild(varDecl->mInitializer);
  2870. }
  2871. return;
  2872. }
  2873. CheckVariableDeclaration(varDecl, true, false, false);
  2874. if (varDecl->mInitializer == NULL)
  2875. {
  2876. mModule->Fail("Variable declarations used as expressions must have an initializer", varDecl);
  2877. }
  2878. BfTupleExpression* tupleVariableDeclaration = BfNodeDynCast<BfTupleExpression>(varDecl->mNameNode);
  2879. if (tupleVariableDeclaration != NULL)
  2880. {
  2881. mModule->Fail("Tuple variable declarations cannot be used as expressions", varDecl);
  2882. mModule->HandleTupleVariableDeclaration(varDecl);
  2883. }
  2884. else
  2885. mModule->HandleVariableDeclaration(varDecl, this);
  2886. }
  2887. void BfExprEvaluator::Visit(BfCaseExpression* caseExpr)
  2888. {
  2889. if (caseExpr->mEqualsNode != NULL)
  2890. {
  2891. mModule->Warn(0, "Deprecated case syntax", caseExpr->mEqualsNode);
  2892. }
  2893. BfTypedValue caseValAddr;
  2894. if (caseExpr->mValueExpression != NULL)
  2895. caseValAddr = mModule->CreateValueFromExpression(caseExpr->mValueExpression, NULL, (BfEvalExprFlags)(mBfEvalExprFlags & BfEvalExprFlags_InheritFlags));
  2896. if ((caseValAddr.mType != NULL) && (caseValAddr.mType->IsPointer()))
  2897. {
  2898. caseValAddr = mModule->LoadValue(caseValAddr);
  2899. caseValAddr = BfTypedValue(caseValAddr.mValue, caseValAddr.mType->GetUnderlyingType(), true);
  2900. }
  2901. if (caseValAddr.mType != NULL)
  2902. mModule->mBfIRBuilder->PopulateType(caseValAddr.mType);
  2903. if ((mModule->mCurMethodState != NULL) && (mModule->mCurMethodState->mDeferredLocalAssignData != NULL))
  2904. mModule->mCurMethodState->mDeferredLocalAssignData->BreakExtendChain();
  2905. if (auto bindExpr = BfNodeDynCast<BfEnumCaseBindExpression>(caseExpr->mCaseExpression))
  2906. {
  2907. if (caseValAddr)
  2908. {
  2909. BfTypedValue enumTagVal;
  2910. if (caseValAddr.mType->IsPayloadEnum())
  2911. {
  2912. int dscrDataIdx;
  2913. auto dscrType = caseValAddr.mType->ToTypeInstance()->GetDiscriminatorType(&dscrDataIdx);
  2914. enumTagVal = BfTypedValue(mModule->ExtractValue(caseValAddr, dscrDataIdx), dscrType);
  2915. }
  2916. else
  2917. enumTagVal = mModule->GetDefaultTypedValue(mModule->GetPrimitiveType(BfTypeCode_Int32));
  2918. mResult = mModule->HandleCaseBind(caseValAddr, enumTagVal, bindExpr);
  2919. return;
  2920. }
  2921. }
  2922. bool isPayloadEnum = (caseValAddr.mType != NULL) && (caseValAddr.mType->IsPayloadEnum());
  2923. auto tupleExpr = BfNodeDynCast<BfTupleExpression>(caseExpr->mCaseExpression);
  2924. if ((caseValAddr) &&
  2925. ((isPayloadEnum) || (tupleExpr != NULL)))
  2926. {
  2927. bool hasVariable = false;
  2928. bool hasOut = false;
  2929. bool clearOutOnMismatch = false;
  2930. if (auto invocateExpr = BfNodeDynCast<BfInvocationExpression>(caseExpr->mCaseExpression))
  2931. {
  2932. for (auto arg : invocateExpr->mArguments)
  2933. {
  2934. if (auto varDecl = BfNodeDynCast<BfVariableDeclaration>(arg))
  2935. {
  2936. hasVariable = true;
  2937. }
  2938. else if (auto unaryOpExpr = BfNodeDynCast<BfUnaryOperatorExpression>(arg))
  2939. {
  2940. if (unaryOpExpr->mOpToken->mToken == BfToken_Out)
  2941. {
  2942. hasOut = true;
  2943. }
  2944. }
  2945. }
  2946. }
  2947. if (hasVariable)
  2948. {
  2949. CheckVariableDeclaration(caseExpr, false, true, false);
  2950. }
  2951. // We can avoid clearing on mismatch if we can be sure we ONLY enter the true block on a match.
  2952. // An example of requiring clearing is: if ((result case .Ok(out val)) || (force))
  2953. if (hasOut)
  2954. clearOutOnMismatch = !CheckVariableDeclaration(caseExpr, true, true, true);
  2955. bool hadConditional = false;
  2956. if (isPayloadEnum)
  2957. {
  2958. int dscrDataIdx;
  2959. auto dscrType = caseValAddr.mType->ToTypeInstance()->GetDiscriminatorType(&dscrDataIdx);
  2960. auto enumTagVal = mModule->LoadValue(mModule->ExtractValue(caseValAddr, NULL, 2));
  2961. int uncondTagId = -1;
  2962. mResult = mModule->TryCaseEnumMatch(caseValAddr, enumTagVal, caseExpr->mCaseExpression, NULL, NULL, NULL, uncondTagId, hadConditional, clearOutOnMismatch);
  2963. }
  2964. else
  2965. {
  2966. mResult = mModule->TryCaseTupleMatch(caseValAddr, tupleExpr, NULL, NULL, NULL, hadConditional, clearOutOnMismatch);
  2967. }
  2968. if (mResult)
  2969. return;
  2970. }
  2971. if ((caseValAddr) && (caseValAddr.mType->IsVar()))
  2972. {
  2973. auto invocationExpr = BfNodeDynCast<BfInvocationExpression>(caseExpr->mCaseExpression);
  2974. if (invocationExpr != NULL)
  2975. {
  2976. for (auto expr : invocationExpr->mArguments)
  2977. {
  2978. if (expr == NULL)
  2979. continue;
  2980. if (auto varDecl = BfNodeDynCast<BfVariableDeclaration>(expr))
  2981. {
  2982. auto localVar = mModule->HandleVariableDeclaration(varDecl, BfTypedValue());
  2983. if (localVar != NULL)
  2984. localVar->mReadFromId = 0;
  2985. }
  2986. }
  2987. }
  2988. auto boolType = mModule->GetPrimitiveType(BfTypeCode_Boolean);
  2989. mResult = mModule->GetDefaultTypedValue(boolType);
  2990. return;
  2991. }
  2992. auto boolType = mModule->GetPrimitiveType(BfTypeCode_Boolean);
  2993. BfTypedValue caseMatch;
  2994. if (caseExpr->mCaseExpression != NULL)
  2995. caseMatch = mModule->CreateValueFromExpression(caseExpr->mCaseExpression, caseValAddr.mType, BfEvalExprFlags_AllowEnumId);
  2996. if ((!caseMatch) || (!caseValAddr))
  2997. {
  2998. mResult = mModule->GetDefaultTypedValue(boolType);
  2999. return;
  3000. }
  3001. if (caseValAddr.mType == caseMatch.mType)
  3002. {
  3003. if (((caseValAddr.mType->IsEnum()) && (caseValAddr.mType->IsStruct())) &&
  3004. ((caseMatch) && (caseMatch.mType->IsPayloadEnum()) && (caseMatch.mValue.IsConst())))
  3005. {
  3006. BfTypedValue enumTagVal = mModule->LoadValue(mModule->ExtractValue(caseValAddr, NULL, 2));
  3007. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateCmpEQ(enumTagVal.mValue, caseMatch.mValue), boolType);
  3008. return;
  3009. }
  3010. }
  3011. else
  3012. {
  3013. // We need to get rid of the int-const for the 'scalar match'. We get a full payload enum value so we can
  3014. // possibly use it in a user-defined comparison operator
  3015. if ((caseMatch.mType->IsStruct()) && (caseMatch.mValue.IsConst()))
  3016. {
  3017. // Is it possible this could throw an error twice? Hope not.
  3018. caseMatch = mModule->CreateValueFromExpression(caseExpr->mCaseExpression, NULL, (BfEvalExprFlags)(mBfEvalExprFlags & BfEvalExprFlags_InheritFlags));
  3019. }
  3020. }
  3021. PerformBinaryOperation(caseExpr->mCaseExpression, caseExpr->mValueExpression, BfBinaryOp_Equality, caseExpr->mEqualsNode, BfBinOpFlag_None, caseValAddr, caseMatch);
  3022. }
  3023. void BfExprEvaluator::Visit(BfTypedValueExpression* typedValueExpr)
  3024. {
  3025. mResult = typedValueExpr->mTypedValue;
  3026. }
  3027. static bool IsCharType(BfTypeCode typeCode)
  3028. {
  3029. switch (typeCode)
  3030. {
  3031. case BfTypeCode_Char8:
  3032. case BfTypeCode_Char16:
  3033. case BfTypeCode_Char32:
  3034. return true;
  3035. default:
  3036. return false;
  3037. }
  3038. }
  3039. void BfExprEvaluator::GetLiteral(BfAstNode* refNode, const BfVariant& variant)
  3040. {
  3041. switch (variant.mTypeCode)
  3042. {
  3043. case BfTypeCode_NullPtr:
  3044. {
  3045. auto nullType = mModule->ResolveTypeDef(mModule->mSystem->mTypeNullPtr);
  3046. /*mResult = BfTypedValue(ConstantPointerNull::get((PointerType*) nullType->mIRType), nullType);*/
  3047. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConstNull(), nullType);
  3048. }
  3049. break;
  3050. case BfTypeCode_CharPtr:
  3051. {
  3052. if ((mExpectingType != NULL) && (mExpectingType->IsSizedArray()))
  3053. {
  3054. auto sizedArray = (BfSizedArrayType*)mExpectingType;
  3055. if (sizedArray->mElementType == mModule->GetPrimitiveType(BfTypeCode_Char8))
  3056. {
  3057. if (variant.mString->GetLength() > sizedArray->mElementCount)
  3058. {
  3059. mModule->Fail(StrFormat("String literal is too long to fit into '%s'", mModule->TypeToString(sizedArray).c_str()), refNode);
  3060. }
  3061. Array<BfIRValue> charValues;
  3062. for (int i = 0; i < (int)BF_MIN(variant.mString->GetLength(), sizedArray->mElementCount); i++)
  3063. {
  3064. char c = (*variant.mString)[i];
  3065. charValues.Add(mModule->mBfIRBuilder->CreateConst(BfTypeCode_Char8, (int)(uint8)c));
  3066. }
  3067. if (sizedArray->mElementCount > charValues.size())
  3068. charValues.Add(mModule->mBfIRBuilder->CreateConst(BfTypeCode_Char8, 0));
  3069. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConstAgg(mModule->mBfIRBuilder->MapType(sizedArray), charValues), sizedArray);
  3070. return;
  3071. }
  3072. }
  3073. if ((mExpectingType == NULL) || (!mExpectingType->IsPointer()))
  3074. {
  3075. mResult = BfTypedValue(mModule->GetStringObjectValue(*variant.mString),
  3076. mModule->ResolveTypeDef(mModule->mCompiler->mStringTypeDef));
  3077. }
  3078. else
  3079. {
  3080. auto charType = mModule->GetPrimitiveType(BfTypeCode_Char8);
  3081. auto charPtrType = mModule->CreatePointerType(charType);
  3082. mResult = BfTypedValue(mModule->GetStringCharPtr(*variant.mString),
  3083. charPtrType);
  3084. }
  3085. }
  3086. break;
  3087. case BfTypeCode_Boolean:
  3088. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConst(variant.mTypeCode, variant.mUInt64), mModule->GetPrimitiveType(variant.mTypeCode));
  3089. break;
  3090. case BfTypeCode_Char8:
  3091. case BfTypeCode_Char16:
  3092. case BfTypeCode_Char32:
  3093. case BfTypeCode_Int8:
  3094. case BfTypeCode_UInt8:
  3095. case BfTypeCode_Int16:
  3096. case BfTypeCode_UInt16:
  3097. case BfTypeCode_Int32:
  3098. case BfTypeCode_UInt32:
  3099. case BfTypeCode_Int64:
  3100. case BfTypeCode_UInt64:
  3101. case BfTypeCode_IntPtr:
  3102. case BfTypeCode_UIntPtr:
  3103. case BfTypeCode_IntUnknown:
  3104. case BfTypeCode_UIntUnknown:
  3105. if ((mExpectingType != NULL) && (mExpectingType->IsIntegral()) && (mExpectingType->IsChar() == IsCharType(variant.mTypeCode)))
  3106. {
  3107. auto primType = (BfPrimitiveType*)mExpectingType;
  3108. if (mModule->mSystem->DoesLiteralFit(primType->mTypeDef->mTypeCode, variant.mUInt64))
  3109. {
  3110. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConst(primType->mTypeDef->mTypeCode, variant.mUInt64), mExpectingType);
  3111. break;
  3112. }
  3113. }
  3114. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConst(variant.mTypeCode, variant.mUInt64), mModule->GetPrimitiveType(variant.mTypeCode));
  3115. break;
  3116. case BfTypeCode_Float:
  3117. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConst(variant.mTypeCode, variant.mSingle), mModule->GetPrimitiveType(variant.mTypeCode));
  3118. break;
  3119. case BfTypeCode_Double:
  3120. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConst(variant.mTypeCode, variant.mDouble), mModule->GetPrimitiveType(variant.mTypeCode));
  3121. break;
  3122. default:
  3123. mModule->Fail("Invalid literal", refNode);
  3124. break;
  3125. }
  3126. }
  3127. void BfExprEvaluator::Visit(BfLiteralExpression* literalExpr)
  3128. {
  3129. switch (literalExpr->mValue.mWarnType)
  3130. {
  3131. case BfWarning_BF4201_Only7Hex:
  3132. mModule->Warn(BfWarning_BF4201_Only7Hex, "Only 7 hex digits specified. Add a leading zero to clarify intention.", literalExpr);
  3133. break;
  3134. case BfWarning_BF4202_TooManyHexForInt:
  3135. 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);
  3136. break;
  3137. }
  3138. GetLiteral(literalExpr, literalExpr->mValue);
  3139. }
  3140. void BfExprEvaluator::Visit(BfStringInterpolationExpression* stringInterpolationExpression)
  3141. {
  3142. if (IsComptimeEntry())
  3143. {
  3144. mModule->Fail("Const evaluation of string interpolation not allowed", stringInterpolationExpression);
  3145. }
  3146. if ((mBfEvalExprFlags & BfEvalExprFlags_StringInterpolateFormat) != 0)
  3147. {
  3148. BfVariant variant;
  3149. variant.mTypeCode = BfTypeCode_CharPtr;
  3150. variant.mString = stringInterpolationExpression->mString;
  3151. GetLiteral(stringInterpolationExpression, variant);
  3152. return;
  3153. }
  3154. if (stringInterpolationExpression->mAllocNode != NULL)
  3155. {
  3156. auto stringType = mModule->ResolveTypeDef(mModule->mCompiler->mStringTypeDef)->ToTypeInstance();
  3157. BfTokenNode* newToken = NULL;
  3158. BfAllocTarget allocTarget = ResolveAllocTarget(stringInterpolationExpression->mAllocNode, newToken);
  3159. CreateObject(NULL, stringInterpolationExpression->mAllocNode, stringType);
  3160. BfTypedValue newString = mResult;
  3161. BF_ASSERT(newString);
  3162. SizedArray<BfExpression*, 2> argExprs;
  3163. argExprs.Add(stringInterpolationExpression);
  3164. BfSizedArray<BfExpression*> sizedArgExprs(argExprs);
  3165. BfResolvedArgs argValues(&sizedArgExprs);
  3166. ResolveArgValues(argValues, BfResolveArgsFlag_InsideStringInterpolationAlloc);
  3167. MatchMethod(stringInterpolationExpression, NULL, newString, false, false, "AppendF", argValues, NULL);
  3168. mResult = newString;
  3169. return;
  3170. }
  3171. mModule->Fail("Invalid use of string interpolation expression. Consider adding an allocation specifier such as 'scope'.", stringInterpolationExpression);
  3172. for (auto block : stringInterpolationExpression->mExpressions)
  3173. {
  3174. VisitChild(block);
  3175. }
  3176. }
  3177. BfTypedValue BfExprEvaluator::LoadLocal(BfLocalVariable* varDecl, bool allowRef)
  3178. {
  3179. if (!mModule->mIsInsideAutoComplete)
  3180. varDecl->mReadFromId = mModule->mCurMethodState->GetRootMethodState()->mCurAccessId++;
  3181. // The Beef backend prefers readonly addrs since that reduces register pressure, whereas
  3182. // LLVM prefers values to avoid memory loads. This only applies to primitive types...
  3183. bool preferValue = (varDecl->mResolvedType->IsPrimitiveType()) && (!mModule->IsTargetingBeefBackend());
  3184. BfTypedValue localResult;
  3185. if (varDecl->mIsThis)
  3186. {
  3187. return mModule->GetThis();
  3188. }
  3189. else if (varDecl->mConstValue)
  3190. {
  3191. localResult = BfTypedValue(varDecl->mConstValue, varDecl->mResolvedType, false);
  3192. }
  3193. else if (varDecl->mIsSplat)
  3194. {
  3195. if ((!preferValue) && (varDecl->mAddr))
  3196. localResult = BfTypedValue(varDecl->mAddr, varDecl->mResolvedType, BfTypedValueKind_SplatHead);
  3197. else if (!varDecl->mResolvedType->IsValuelessType())
  3198. localResult = BfTypedValue(varDecl->mValue, varDecl->mResolvedType, BfTypedValueKind_SplatHead);
  3199. else if ((varDecl->mResolvedType->IsRef()) && (!allowRef))
  3200. {
  3201. BF_ASSERT(varDecl->mResolvedType->IsValuelessType());
  3202. localResult = BfTypedValue(varDecl->mValue, varDecl->mResolvedType->GetUnderlyingType());
  3203. }
  3204. else
  3205. localResult = BfTypedValue(varDecl->mValue, varDecl->mResolvedType);
  3206. //BF_ASSERT(varDecl->mValue.IsArg());
  3207. }
  3208. else if ((varDecl->mValue) && ((varDecl->mIsReadOnly && preferValue) || (!varDecl->mAddr)))
  3209. {
  3210. if ((varDecl->mResolvedType->IsRef()) && (!allowRef))
  3211. {
  3212. BfRefType* refType = (BfRefType*)varDecl->mResolvedType;
  3213. BfType* innerType = refType->mElementType;
  3214. if (innerType->IsGenericParam())
  3215. {
  3216. if (refType->mRefKind == BfRefType::RefKind_Mut)
  3217. {
  3218. localResult = BfTypedValue(varDecl->mValue, innerType, BfTypedValueKind_MutableValue);
  3219. return localResult;
  3220. }
  3221. else
  3222. {
  3223. localResult = BfTypedValue(varDecl->mValue, innerType, BfTypedValueKind_Addr);
  3224. return localResult;
  3225. }
  3226. }
  3227. localResult = BfTypedValue(varDecl->mValue, innerType, varDecl->mIsReadOnly ? BfTypedValueKind_ReadOnlyAddr : BfTypedValueKind_Addr);
  3228. }
  3229. else
  3230. {
  3231. BfTypedValueKind kind;
  3232. if ((varDecl->mResolvedType->IsComposite()) && (varDecl->mValue.IsArg()))
  3233. {
  3234. kind = varDecl->mIsReadOnly ? BfTypedValueKind_ReadOnlyAddr : BfTypedValueKind_Addr;
  3235. }
  3236. else
  3237. kind = BfTypedValueKind_Value;
  3238. localResult = BfTypedValue(varDecl->mValue, varDecl->mResolvedType, kind);
  3239. }
  3240. }
  3241. else if (varDecl->mAddr)
  3242. {
  3243. if ((varDecl->mResolvedType->IsRef()) && (!allowRef))
  3244. {
  3245. BfRefType* refType = (BfRefType*)varDecl->mResolvedType;
  3246. BfType* innerType = refType->mElementType;
  3247. if (innerType->IsValuelessType())
  3248. {
  3249. if (refType->mRefKind == BfRefType::RefKind_Mut)
  3250. return BfTypedValue(mModule->mBfIRBuilder->GetFakeVal(), innerType, BfTypedValueKind_MutableValue);
  3251. return BfTypedValue(mModule->mBfIRBuilder->GetFakeVal(), innerType, varDecl->mIsReadOnly ? BfTypedValueKind_ReadOnlyAddr : BfTypedValueKind_Addr);
  3252. }
  3253. if (refType->mRefKind == BfRefType::RefKind_Mut)
  3254. {
  3255. if (innerType->IsGenericParam())
  3256. {
  3257. localResult = BfTypedValue(mModule->mBfIRBuilder->CreateAlignedLoad(varDecl->mAddr, varDecl->mResolvedType->mAlign), innerType, BfTypedValueKind_MutableValue);
  3258. return localResult;
  3259. }
  3260. }
  3261. localResult = BfTypedValue(mModule->mBfIRBuilder->CreateAlignedLoad(varDecl->mAddr, varDecl->mResolvedType->mAlign), innerType, varDecl->mIsReadOnly ? BfTypedValueKind_ReadOnlyAddr : BfTypedValueKind_Addr);
  3262. }
  3263. else if (varDecl->mHasLocalStructBacking)
  3264. {
  3265. // varDecl->mAddr is a "struct**"
  3266. localResult = BfTypedValue(mModule->mBfIRBuilder->CreateAlignedLoad(varDecl->mAddr, varDecl->mResolvedType->mAlign), varDecl->mResolvedType, varDecl->mIsReadOnly ? BfTypedValueKind_ReadOnlyAddr : BfTypedValueKind_Addr);
  3267. }
  3268. else
  3269. localResult = BfTypedValue(varDecl->mAddr, varDecl->mResolvedType, varDecl->mIsReadOnly ? BfTypedValueKind_ReadOnlyAddr : BfTypedValueKind_Addr);
  3270. }
  3271. else if (varDecl->mResolvedType->IsValuelessType())
  3272. {
  3273. if ((varDecl->mResolvedType->IsRef()) && (!allowRef))
  3274. {
  3275. BfRefType* refType = (BfRefType*)varDecl->mResolvedType;
  3276. BfType* innerType = refType->mElementType;
  3277. localResult = BfTypedValue(mModule->mBfIRBuilder->GetFakeVal(), innerType, true);
  3278. return localResult;
  3279. }
  3280. localResult = BfTypedValue(mModule->mBfIRBuilder->GetFakeVal(), varDecl->mResolvedType, true);
  3281. }
  3282. else if (varDecl->mCompositeCount >= 0)
  3283. {
  3284. localResult = BfTypedValue(BfIRValue(), mModule->GetPrimitiveType(BfTypeCode_None));
  3285. }
  3286. else
  3287. {
  3288. BF_ASSERT((mModule->mCurMethodState->mClosureState != NULL) || (mModule->mBfIRBuilder->mIgnoreWrites));
  3289. // Just temporary
  3290. auto varType = varDecl->mResolvedType;
  3291. auto allocType = varType;
  3292. if (varType->IsRef())
  3293. {
  3294. BfRefType* refType = (BfRefType*)varType;
  3295. allocType = refType->mElementType;
  3296. }
  3297. auto declType = varDecl->mResolvedType;
  3298. if (declType->IsRef())
  3299. {
  3300. BfRefType* refType = (BfRefType*)declType;
  3301. declType = refType->mElementType;
  3302. }
  3303. mModule->PopulateType(allocType);
  3304. varDecl->mAddr = mModule->mBfIRBuilder->CreateAlloca(mModule->mBfIRBuilder->MapType(allocType));
  3305. localResult = BfTypedValue(varDecl->mAddr, declType, true);
  3306. return localResult;
  3307. }
  3308. if ((varDecl->mIsThis) && (localResult.mKind == BfTypedValueKind_Value))
  3309. localResult.mKind = BfTypedValueKind_ThisValue;
  3310. return localResult;
  3311. }
  3312. BfTypedValue BfExprEvaluator::LookupIdentifier(BfAstNode* refNode, const StringImpl& findName, bool ignoreInitialError, bool* hadError)
  3313. {
  3314. auto identifierNode = BfNodeDynCast<BfIdentifierNode>(refNode);
  3315. if (mModule->mCurMethodState != NULL)
  3316. {
  3317. auto rootMethodState = mModule->mCurMethodState->GetRootMethodState();
  3318. auto checkMethodState = mModule->mCurMethodState;
  3319. bool isMixinOuterVariablePass = false;
  3320. while (checkMethodState != NULL)
  3321. {
  3322. BP_ZONE("LookupIdentifier:LocalVar");
  3323. BfTypeInstance* closureTypeInst = NULL;
  3324. if ((checkMethodState->mClosureState != NULL) && (checkMethodState->mClosureState->mClosureType != NULL) && (!checkMethodState->mClosureState->mCapturing))
  3325. {
  3326. closureTypeInst = mModule->mCurMethodState->mClosureState->mClosureType;
  3327. }
  3328. int varSkipCount = 0;
  3329. StringT<128> wantName;
  3330. wantName.Reference(findName);
  3331. if (findName.StartsWith('@'))
  3332. {
  3333. wantName = findName;
  3334. while (wantName.StartsWith("@"))
  3335. {
  3336. if (wantName != "@return")
  3337. varSkipCount++;
  3338. wantName.Remove(0);
  3339. }
  3340. }
  3341. if (wantName.IsEmpty())
  3342. {
  3343. mModule->Fail("Shadowed variable name expected after '@'", refNode);
  3344. }
  3345. BfLocalVarEntry* entry;
  3346. if (checkMethodState->mLocalVarSet.TryGetWith<StringImpl&>(wantName, &entry))
  3347. {
  3348. auto varDecl = entry->mLocalVar;
  3349. if (varDecl != NULL)
  3350. varSkipCount -= varDecl->mNamePrefixCount;
  3351. while ((varSkipCount > 0) && (varDecl != NULL))
  3352. {
  3353. varDecl = varDecl->mShadowedLocal;
  3354. varSkipCount--;
  3355. }
  3356. if ((varDecl != NULL) && (varDecl->mNotCaptured))
  3357. {
  3358. mModule->Fail("Local variable is not captured", refNode);
  3359. }
  3360. if ((varSkipCount == 0) && (varDecl != NULL))
  3361. {
  3362. if ((closureTypeInst != NULL) && (wantName == "this"))
  3363. break;
  3364. if ((varDecl->mCompositeCount >= 0) && ((mBfEvalExprFlags & BfEvalExprFlags_AllowParamsExpr) == 0))
  3365. {
  3366. mModule->Fail("Invalid use of 'params' parameter", refNode);
  3367. }
  3368. if (varDecl->mResolvedType->IsVoid())
  3369. {
  3370. if ((varDecl->mIsReadOnly) && (varDecl->mParamIdx == -2) && (varDecl->mParamFailed))
  3371. {
  3372. BF_ASSERT(mModule->mCurMethodInstance->mMethodDef->mMethodType == BfMethodType_CtorCalcAppend);
  3373. 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);
  3374. }
  3375. }
  3376. BfTypedValue localResult = LoadLocal(varDecl);
  3377. auto autoComplete = GetAutoComplete();
  3378. if (identifierNode != NULL)
  3379. {
  3380. if (autoComplete != NULL)
  3381. autoComplete->CheckLocalRef(identifierNode, varDecl);
  3382. if (((mModule->mCurMethodState->mClosureState == NULL) || (mModule->mCurMethodState->mClosureState->mCapturing)) &&
  3383. (mModule->mCompiler->mResolvePassData != NULL) && (mModule->mCurMethodInstance != NULL) && (!mModule->mCurMethodState->IsTemporary()))
  3384. mModule->mCompiler->mResolvePassData->HandleLocalReference(identifierNode, varDecl->mNameNode, mModule->mCurTypeInstance->mTypeDef, rootMethodState->mMethodInstance->mMethodDef, varDecl->mLocalVarId);
  3385. }
  3386. if (!isMixinOuterVariablePass)
  3387. {
  3388. mResultLocalVar = varDecl;
  3389. mResultFieldInstance = NULL;
  3390. mResultLocalVarRefNode = identifierNode;
  3391. }
  3392. return localResult;
  3393. }
  3394. }
  3395. // Check for the captured locals. It's important we do it here so we get local-first precedence still
  3396. if (closureTypeInst != NULL)
  3397. {
  3398. int varSkipCount = 0;
  3399. StringT<128> wantName;
  3400. wantName.Reference(findName);
  3401. closureTypeInst->mTypeDef->PopulateMemberSets();
  3402. BfMemberSetEntry* memberSetEntry = NULL;
  3403. if (closureTypeInst->mTypeDef->mFieldSet.TryGetWith((StringImpl&)wantName, &memberSetEntry))
  3404. {
  3405. auto fieldDef = (BfFieldDef*)memberSetEntry->mMemberDef;
  3406. while ((varSkipCount > 0) && (fieldDef != NULL))
  3407. {
  3408. fieldDef = fieldDef->mNextWithSameName;
  3409. varSkipCount--;
  3410. }
  3411. auto& field = closureTypeInst->mFieldInstances[fieldDef->mIdx];
  3412. if (!field.mResolvedType->IsValuelessType())
  3413. {
  3414. if (mModule->mCurMethodState->mClosureState->mCapturing)
  3415. {
  3416. mModule->mCurMethodState->mClosureState->mReferencedOuterClosureMembers.Add(&field);
  3417. return mModule->GetDefaultTypedValue(field.mResolvedType);
  3418. }
  3419. auto localVar = mModule->mCurMethodState->mLocals[0];
  3420. auto thisValue = localVar->mValue;
  3421. mModule->mBfIRBuilder->PopulateType(localVar->mResolvedType);
  3422. BfTypedValue result = BfTypedValue(mModule->mBfIRBuilder->CreateInBoundsGEP(thisValue, 0, field.mDataIdx), field.mResolvedType, true);
  3423. if (field.mResolvedType->IsRef())
  3424. {
  3425. auto refType = (BfRefType*)field.mResolvedType;
  3426. auto underlyingType = refType->GetUnderlyingType();
  3427. result = BfTypedValue(mModule->mBfIRBuilder->CreateLoad(result.mValue), underlyingType, true);
  3428. }
  3429. else if (fieldDef->mIsReadOnly)
  3430. result = mModule->LoadValue(result);
  3431. mResultLocalVar = localVar;
  3432. mResultFieldInstance = &field;
  3433. mResultLocalVarField = -(field.mMergedDataIdx + 1);
  3434. return result;
  3435. }
  3436. }
  3437. }
  3438. if ((checkMethodState->mClosureState != NULL) && (checkMethodState->mClosureState->mCapturing) /*&& (checkMethodState->mClosureState->mIsLocalMethod)*/)
  3439. {
  3440. checkMethodState = checkMethodState->mPrevMethodState;
  3441. continue;
  3442. }
  3443. // Allow local mixin to see outside variables during its processing -- since we don't actually "capture" those into params
  3444. bool isLocalMixinProcessing = false;
  3445. if ((checkMethodState->mClosureState != NULL) && (!checkMethodState->mClosureState->mCapturing) && (closureTypeInst == NULL) &&
  3446. (mModule->mCurMethodInstance->mMethodDef->mMethodType == BfMethodType_Mixin))
  3447. isLocalMixinProcessing = true;
  3448. if (!isLocalMixinProcessing)
  3449. break;
  3450. isMixinOuterVariablePass = true;
  3451. checkMethodState = checkMethodState->mPrevMethodState;
  3452. }
  3453. }
  3454. if ((mModule->mCurMethodInstance == NULL) && (mModule->mCurTypeInstance != NULL) && (mModule->mCurTypeInstance->IsEnum()))
  3455. {
  3456. if (findName == "_")
  3457. {
  3458. BfFieldDef* resolvingFieldDef = NULL;
  3459. auto checkTypeState = mModule->mContext->mCurTypeState;
  3460. while (checkTypeState != NULL)
  3461. {
  3462. if (checkTypeState->mCurFieldDef != NULL)
  3463. {
  3464. if (checkTypeState->mType == mModule->mCurTypeInstance)
  3465. resolvingFieldDef = checkTypeState->mCurFieldDef;
  3466. }
  3467. checkTypeState = checkTypeState->mPrevState;
  3468. }
  3469. if ((resolvingFieldDef != NULL) &&
  3470. (mModule->mCompiler->mResolvePassData != NULL) &&
  3471. (mModule->mCompiler->mResolvePassData->mParser == resolvingFieldDef->mFieldDeclaration->GetParser()) &&
  3472. (GetAutoComplete() != NULL))
  3473. {
  3474. return mModule->GetDefaultTypedValue(mModule->mCurTypeInstance);
  3475. }
  3476. else if ((resolvingFieldDef != NULL) && (resolvingFieldDef->mIdx > 0))
  3477. {
  3478. auto enumType = mModule->mCurTypeInstance;
  3479. if (!enumType->mFieldInstances.IsEmpty())
  3480. {
  3481. auto fieldInstance = &mModule->mCurTypeInstance->mFieldInstances[resolvingFieldDef->mIdx - 1];
  3482. if ((fieldInstance->mConstIdx != -1) &&
  3483. (fieldInstance->mResolvedType == mModule->mCurTypeInstance))
  3484. {
  3485. auto foreignConst = enumType->mConstHolder->GetConstantById(fieldInstance->mConstIdx);
  3486. auto retVal = mModule->ConstantToCurrent(foreignConst, enumType->mConstHolder, enumType);
  3487. return BfTypedValue(retVal, enumType);
  3488. }
  3489. }
  3490. }
  3491. }
  3492. }
  3493. BfTypedValue thisValue = mModule->GetThis();
  3494. bool forcedIFaceLookup = false;
  3495. if ((mModule->mCurMethodInstance != NULL) && (mModule->mCurMethodInstance->mIsForeignMethodDef))
  3496. {
  3497. thisValue.mType = mModule->mCurMethodInstance->GetForeignType();
  3498. forcedIFaceLookup = true;
  3499. }
  3500. if (thisValue)
  3501. {
  3502. if (findName == "this")
  3503. return thisValue;
  3504. if (findName == "base")
  3505. {
  3506. auto baseValue = thisValue;
  3507. if (baseValue.IsThis())
  3508. baseValue.ToBase();
  3509. if (mModule->GetActiveTypeDef()->mTypeCode != BfTypeCode_Extension)
  3510. {
  3511. MakeBaseConcrete(baseValue);
  3512. }
  3513. return baseValue;
  3514. }
  3515. if (!mModule->mCurMethodState->HasNonStaticMixin())
  3516. {
  3517. mResultLocalVar = mModule->GetThisVariable();
  3518. mResultFieldInstance = NULL;
  3519. mResultLocalVarRefNode = identifierNode;
  3520. }
  3521. }
  3522. if (!thisValue.HasType())
  3523. {
  3524. if ((mModule->mContext->mCurTypeState != NULL) && (mModule->mContext->mCurTypeState->mType == mModule->mCurTypeInstance) &&
  3525. (mModule->mContext->mCurTypeState->mResolveKind == BfTypeState::ResolveKind_Attributes))
  3526. {
  3527. // Can't do static lookups yet
  3528. }
  3529. else
  3530. thisValue = BfTypedValue(mModule->mCurTypeInstance);
  3531. }
  3532. BfTypedValue result;
  3533. if (thisValue.HasType())
  3534. {
  3535. result = LookupField(identifierNode, thisValue, findName, BfLookupFieldFlag_IsImplicitThis);
  3536. if (mResultFieldInstance == NULL)
  3537. {
  3538. mResultLocalVar = NULL;
  3539. mResultLocalVarRefNode = NULL;
  3540. }
  3541. }
  3542. if (mPropDef != NULL)
  3543. {
  3544. if (forcedIFaceLookup)
  3545. {
  3546. if (mPropTarget == thisValue)
  3547. {
  3548. mPropDefBypassVirtual = true;
  3549. mOrigPropTarget = mModule->GetThis();
  3550. }
  3551. }
  3552. }
  3553. if ((!result) && (mPropDef == NULL))
  3554. {
  3555. if (mModule->mContext->mCurTypeState != NULL)
  3556. {
  3557. // This is not necessarily true since we changed ConstResolver
  3558. //BF_ASSERT(mModule->mCurTypeInstance == mModule->mContext->mCurTypeState->mTypeInstance);
  3559. BfGlobalLookup globalLookup;
  3560. globalLookup.mKind = BfGlobalLookup::Kind_Field;
  3561. globalLookup.mName = findName;
  3562. mModule->PopulateGlobalContainersList(globalLookup);
  3563. for (auto& globalContainer : mModule->mContext->mCurTypeState->mGlobalContainers)
  3564. {
  3565. if (globalContainer.mTypeInst == NULL)
  3566. continue;
  3567. thisValue = BfTypedValue(globalContainer.mTypeInst);
  3568. result = LookupField(identifierNode, thisValue, findName);
  3569. if ((result) || (mPropDef != NULL))
  3570. return result;
  3571. }
  3572. }
  3573. auto staticSearch = mModule->GetStaticSearch();
  3574. if (staticSearch != NULL)
  3575. {
  3576. for (auto typeInst : staticSearch->mStaticTypes)
  3577. {
  3578. thisValue = BfTypedValue(typeInst);
  3579. result = LookupField(identifierNode, thisValue, findName);
  3580. if ((result) || (mPropDef != NULL))
  3581. return result;
  3582. }
  3583. }
  3584. }
  3585. if ((!result) && (identifierNode != NULL))
  3586. result = mModule->TryLookupGenericConstVaue(identifierNode, mExpectingType);
  3587. return result;
  3588. }
  3589. BfTypedValue BfExprEvaluator::LookupIdentifier(BfIdentifierNode* identifierNode, bool ignoreInitialError, bool* hadError)
  3590. {
  3591. auto qualifiedNameNode = BfNodeDynCast<BfQualifiedNameNode>(identifierNode);
  3592. if (qualifiedNameNode != NULL)
  3593. {
  3594. LookupQualifiedName(qualifiedNameNode, ignoreInitialError, hadError);
  3595. auto qualifiedResult = mResult;
  3596. mResult = BfTypedValue();
  3597. return qualifiedResult;
  3598. }
  3599. StringT<128> identifierStr;
  3600. identifierNode->ToString(identifierStr);
  3601. return LookupIdentifier(identifierNode, identifierStr, ignoreInitialError, hadError);
  3602. }
  3603. void BfExprEvaluator::Visit(BfIdentifierNode* identifierNode)
  3604. {
  3605. auto autoComplete = GetAutoComplete();
  3606. if (autoComplete != NULL)
  3607. autoComplete->CheckIdentifier(identifierNode, true);
  3608. mResult = LookupIdentifier(identifierNode);
  3609. if ((!mResult) && (mPropDef == NULL))
  3610. {
  3611. mModule->CheckTypeRefFixit(identifierNode);
  3612. if ((autoComplete != NULL) && (autoComplete->CheckFixit(identifierNode)))
  3613. {
  3614. if (mModule->mCurMethodInstance != NULL)
  3615. {
  3616. BfType* fieldType = mExpectingType;
  3617. if (fieldType == NULL)
  3618. fieldType = mModule->mContext->mBfObjectType;
  3619. autoComplete->FixitAddMember(mModule->mCurTypeInstance, fieldType, identifierNode->ToString(), true, mModule->mCurTypeInstance);
  3620. if (!mModule->mCurMethodInstance->mMethodDef->mIsStatic)
  3621. autoComplete->FixitAddMember(mModule->mCurTypeInstance, fieldType, identifierNode->ToString(), false, mModule->mCurTypeInstance);
  3622. for (auto typeDef : mModule->mSystem->mTypeDefs)
  3623. {
  3624. if (!typeDef->mIsCombinedPartial)
  3625. continue;
  3626. if (!typeDef->IsGlobalsContainer())
  3627. continue;
  3628. typeDef->PopulateMemberSets();
  3629. String findName = identifierNode->ToString();
  3630. BfMemberSetEntry* memberSetEntry;
  3631. if ((typeDef->mMethodSet.TryGetWith(findName, &memberSetEntry)) ||
  3632. (typeDef->mFieldSet.TryGetWith(findName, &memberSetEntry)) ||
  3633. (typeDef->mPropertySet.TryGetWith(findName, &memberSetEntry)))
  3634. {
  3635. if (mModule->GetActiveTypeDef()->mProject->ContainsReference(typeDef->mProject))
  3636. autoComplete->FixitAddNamespace(identifierNode, typeDef->mNamespace.ToString());
  3637. }
  3638. }
  3639. }
  3640. }
  3641. if ((mBfEvalExprFlags & BfEvalExprFlags_NoLookupError) == 0)
  3642. mModule->Fail("Identifier not found", identifierNode);
  3643. }
  3644. }
  3645. void BfExprEvaluator::Visit(BfAttributedIdentifierNode* attrIdentifierNode)
  3646. {
  3647. if ((mModule->mAttributeState != NULL))
  3648. {
  3649. mModule->mAttributeState->mCustomAttributes = mModule->GetCustomAttributes(attrIdentifierNode->mAttributes, mModule->mAttributeState->mTarget);
  3650. VisitChild(attrIdentifierNode->mIdentifier);
  3651. }
  3652. else
  3653. {
  3654. BfAttributeState attributeState;
  3655. attributeState.mTarget = (BfAttributeTargets)(BfAttributeTargets_MemberAccess);
  3656. SetAndRestoreValue<BfAttributeState*> prevAttributeState(mModule->mAttributeState, &attributeState);
  3657. mModule->mAttributeState->mCustomAttributes = mModule->GetCustomAttributes(attrIdentifierNode->mAttributes, mModule->mAttributeState->mTarget);
  3658. VisitChild(attrIdentifierNode->mIdentifier);
  3659. }
  3660. }
  3661. static int gPropIdx = 0;
  3662. void BfExprEvaluator::FixitAddMember(BfTypeInstance* typeInst, BfType* fieldType, const StringImpl& fieldName, bool isStatic)
  3663. {
  3664. if (fieldType == NULL)
  3665. {
  3666. fieldType = mExpectingType;
  3667. }
  3668. if (fieldType != NULL)
  3669. {
  3670. if (fieldType->IsRef())
  3671. fieldType = fieldType->GetUnderlyingType();
  3672. }
  3673. mModule->mCompiler->mResolvePassData->mAutoComplete->FixitAddMember(typeInst, fieldType, fieldName, isStatic, mModule->mCurTypeInstance);
  3674. }
  3675. BfTypedValue BfExprEvaluator::LookupField(BfAstNode* targetSrc, BfTypedValue target, const StringImpl& fieldName, BfLookupFieldFlags flags)
  3676. {
  3677. if ((target.mType != NULL && (target.mType->IsGenericParam())))
  3678. {
  3679. auto genericParamInst = mModule->GetGenericParamInstance((BfGenericParamType*)target.mType);
  3680. if (target.mValue)
  3681. {
  3682. for (auto iface : genericParamInst->mInterfaceConstraints)
  3683. {
  3684. auto result = LookupField(targetSrc, BfTypedValue(target.mValue, iface), fieldName, flags);
  3685. if ((result) || (mPropDef != NULL))
  3686. {
  3687. return result;
  3688. }
  3689. }
  3690. }
  3691. if ((mModule->mCurMethodInstance != NULL) && (mModule->mCurMethodInstance->mIsUnspecialized))
  3692. {
  3693. if (genericParamInst->mTypeConstraint != NULL)
  3694. target.mType = genericParamInst->mTypeConstraint;
  3695. else
  3696. target.mType = mModule->mContext->mBfObjectType;
  3697. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_Var) != 0)
  3698. {
  3699. target.mType = mModule->GetPrimitiveType(BfTypeCode_Var);
  3700. }
  3701. }
  3702. else
  3703. {
  3704. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_Var) != 0)
  3705. {
  3706. //target.mType = mModule->ResolveGenericType(mResult.mType);
  3707. }
  3708. else if (genericParamInst->mTypeConstraint != NULL)
  3709. {
  3710. target = mModule->Cast(targetSrc, target, genericParamInst->mTypeConstraint);
  3711. BF_ASSERT(target);
  3712. }
  3713. else
  3714. {
  3715. // This shouldn't occur - this would infer that we are accessing a member of Object or something...
  3716. //target.mType = mModule->ResolveGenericType(mResult.mType);
  3717. }
  3718. }
  3719. }
  3720. if ((target.mType != NULL) && (target.mType->IsVar()))
  3721. return BfTypedValue(mModule->GetDefaultValue(target.mType), target.mType, true);
  3722. BfTypeInstance* startCheckType = mModule->mCurTypeInstance;
  3723. mPropDef = NULL;
  3724. mPropDefBypassVirtual = false;
  3725. if (target)
  3726. {
  3727. if ((!target.mType->IsValueType()) && (target.IsAddr()))
  3728. target = mModule->LoadValue(target);
  3729. if (target.mType->IsPrimitiveType())
  3730. {
  3731. auto primType = (BfPrimitiveType*)target.mType;
  3732. startCheckType = mModule->GetPrimitiveStructType(primType->mTypeDef->mTypeCode);
  3733. }
  3734. else
  3735. {
  3736. startCheckType = target.mType->ToTypeInstance();
  3737. if ((startCheckType == NULL) && (target.mType->IsPointer()))
  3738. {
  3739. startCheckType = ((BfPointerType*)target.mType)->mElementType->ToTypeInstance();
  3740. if ((startCheckType != NULL) && (!startCheckType->IsValueType()))
  3741. return BfTypedValue();
  3742. }
  3743. }
  3744. //BF_ASSERT(startCheckType != NULL);
  3745. }
  3746. else if (target.mType != NULL)
  3747. {
  3748. startCheckType = target.mType->ToTypeInstance();
  3749. }
  3750. if ((startCheckType != NULL) && (startCheckType->mBaseType == NULL))
  3751. {
  3752. if (startCheckType->mDefineState == BfTypeDefineState_ResolvingBaseType)
  3753. {
  3754. // Fixes cases where we have something like 'Base[Value]' as a base typeref
  3755. return BfTypedValue();
  3756. }
  3757. mModule->PopulateType(startCheckType, BfPopulateType_BaseType);
  3758. }
  3759. if ((startCheckType != NULL) && (mModule->mContext->mCurTypeState != NULL))
  3760. {
  3761. // Don't allow lookups yet
  3762. if ((mModule->mContext->mCurTypeState->mResolveKind == BfTypeState::ResolveKind_Attributes) &&
  3763. (startCheckType == mModule->mContext->mCurTypeState->mType))
  3764. return BfTypedValue();
  3765. }
  3766. String findName;
  3767. int varSkipCount = 0;
  3768. if (fieldName.StartsWith('@'))
  3769. {
  3770. findName = fieldName;
  3771. while (findName.StartsWith('@'))
  3772. {
  3773. findName.Remove(0);
  3774. varSkipCount++;
  3775. }
  3776. }
  3777. else
  3778. findName.Reference(fieldName);
  3779. auto activeTypeDef = mModule->GetActiveTypeDef();
  3780. for (int pass = 0; pass < 2; pass++)
  3781. {
  3782. auto curCheckType = startCheckType;
  3783. bool isFailurePass = pass == 1;
  3784. bool isBaseLookup = false;
  3785. while (curCheckType != NULL)
  3786. {
  3787. curCheckType->mTypeDef->PopulateMemberSets();
  3788. BfFieldDef* nextField = NULL;
  3789. BfMemberSetEntry* entry;
  3790. if (curCheckType->mTypeDef->mFieldSet.TryGetWith(findName, &entry))
  3791. nextField = (BfFieldDef*)entry->mMemberDef;
  3792. if (nextField != NULL)
  3793. varSkipCount -= nextField->mNamePrefixCount;
  3794. while ((varSkipCount > 0) && (nextField != NULL))
  3795. {
  3796. nextField = nextField->mNextWithSameName;
  3797. varSkipCount--;
  3798. }
  3799. BfProtectionCheckFlags protectionCheckFlags = BfProtectionCheckFlag_None;
  3800. if (target)
  3801. {
  3802. if ((flags & (BfLookupFieldFlag_IsImplicitThis | BfLookupFieldFlag_BaseLookup)) != 0)
  3803. {
  3804. // Not an "instance lookup"
  3805. }
  3806. else
  3807. {
  3808. protectionCheckFlags = (BfProtectionCheckFlags)(protectionCheckFlags | BfProtectionCheckFlag_InstanceLookup);
  3809. }
  3810. }
  3811. BfFieldDef* matchedField = NULL;
  3812. while (nextField != NULL)
  3813. {
  3814. if ((flags & BfLookupFieldFlag_BindOnly) != 0)
  3815. break;
  3816. auto field = nextField;
  3817. nextField = nextField->mNextWithSameName;
  3818. if (((flags & BfLookupFieldFlag_IgnoreProtection) == 0) && (!isFailurePass) &&
  3819. (!mModule->CheckProtection(protectionCheckFlags, curCheckType, field->mDeclaringType->mProject, field->mProtection, startCheckType)))
  3820. {
  3821. continue;
  3822. }
  3823. bool isResolvingFields = curCheckType->mResolvingConstField || curCheckType->mResolvingVarField;
  3824. if (curCheckType->mFieldInstances.IsEmpty())
  3825. {
  3826. mModule->PopulateType(curCheckType, BfPopulateType_Data);
  3827. }
  3828. BF_ASSERT(field->mIdx < (int)curCheckType->mFieldInstances.size());
  3829. auto fieldInstance = &curCheckType->mFieldInstances[field->mIdx];
  3830. if (!fieldInstance->mFieldIncluded)
  3831. continue;
  3832. if (curCheckType->IsUnspecializedType())
  3833. {
  3834. // The check for non-unspecialized types is already handled in mFieldIncluded
  3835. if (!curCheckType->IsTypeMemberIncluded(field->mDeclaringType, activeTypeDef, mModule))
  3836. continue;
  3837. }
  3838. if (!curCheckType->IsTypeMemberAccessible(field->mDeclaringType, activeTypeDef))
  3839. continue;
  3840. if (matchedField != NULL)
  3841. {
  3842. auto error = mModule->Fail(StrFormat("Ambiguous reference to field '%s.%s'", mModule->TypeToString(curCheckType).c_str(), fieldName.c_str()), targetSrc);
  3843. if (error != NULL)
  3844. {
  3845. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("See field declaration in project '%s'", matchedField->mDeclaringType->mProject->mName.c_str()), matchedField->mFieldDeclaration);
  3846. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("See field declaration in project '%s'", field->mDeclaringType->mProject->mName.c_str()), field->mFieldDeclaration);
  3847. break;
  3848. }
  3849. }
  3850. matchedField = field;
  3851. }
  3852. if (matchedField != NULL)
  3853. {
  3854. auto field = matchedField;
  3855. auto fieldInstance = &curCheckType->mFieldInstances[field->mIdx];
  3856. bool isResolvingFields = curCheckType->mResolvingConstField || curCheckType->mResolvingVarField;
  3857. if (field->mIsVolatile)
  3858. mIsVolatileReference = true;
  3859. if (isFailurePass)
  3860. {
  3861. mModule->Fail(StrFormat("'%s.%s' is inaccessible due to its protection level", mModule->TypeToString(curCheckType).c_str(), field->mName.c_str()), targetSrc);
  3862. }
  3863. auto resolvePassData = mModule->mCompiler->mResolvePassData;
  3864. if ((resolvePassData != NULL) && (resolvePassData->mGetSymbolReferenceKind == BfGetSymbolReferenceKind_Field))
  3865. {
  3866. resolvePassData->HandleFieldReference(targetSrc, curCheckType->mTypeDef, field);
  3867. }
  3868. if ((!curCheckType->mTypeFailed) && (!isResolvingFields) && (curCheckType->IsIncomplete()))
  3869. {
  3870. if ((fieldInstance->mResolvedType == NULL) ||
  3871. (!field->mIsStatic))
  3872. mModule->PopulateType(curCheckType, BfPopulateType_Data);
  3873. }
  3874. if (fieldInstance->mResolvedType == NULL)
  3875. {
  3876. BF_ASSERT((curCheckType->mTypeFailed) || (isResolvingFields));
  3877. return BfTypedValue();
  3878. }
  3879. if (fieldInstance->mFieldIdx == -1)
  3880. {
  3881. mModule->AssertErrorState();
  3882. return BfTypedValue();
  3883. }
  3884. mResultFieldInstance = fieldInstance;
  3885. // Are we accessing a 'var' field that has not yet been resolved?
  3886. if (fieldInstance->mResolvedType->IsVar())
  3887. {
  3888. // This can happen if we have one var field referencing another var field
  3889. fieldInstance->mResolvedType = mModule->ResolveVarFieldType(curCheckType, fieldInstance, field);
  3890. if (fieldInstance->mResolvedType == NULL)
  3891. return BfTypedValue();
  3892. }
  3893. auto resolvedFieldType = fieldInstance->mResolvedType;
  3894. if (fieldInstance->mIsEnumPayloadCase)
  3895. {
  3896. resolvedFieldType = curCheckType;
  3897. }
  3898. mModule->PopulateType(resolvedFieldType, BfPopulateType_Data);
  3899. mModule->AddDependency(curCheckType, mModule->mCurTypeInstance, field->mIsConst ? BfDependencyMap::DependencyFlag_ConstValue : BfDependencyMap::DependencyFlag_ReadFields);
  3900. if (fieldInstance->mHadConstEval)
  3901. {
  3902. mModule->AddDependency(curCheckType, mModule->mCurTypeInstance, BfDependencyMap::DependencyFlag_ConstEvalConstField);
  3903. if ((mModule->mContext->mCurTypeState != NULL) && (mModule->mContext->mCurTypeState->mCurFieldDef != NULL))
  3904. {
  3905. // If we're initializing another const field then also set it as having const eval
  3906. auto resolvingFieldInstance = &mModule->mContext->mCurTypeState->mType->ToTypeInstance()->mFieldInstances[mModule->mContext->mCurTypeState->mCurFieldDef->mIdx];
  3907. if (resolvingFieldInstance->GetFieldDef()->mIsConst)
  3908. resolvingFieldInstance->mHadConstEval = true;
  3909. }
  3910. }
  3911. auto autoComplete = GetAutoComplete();
  3912. if (autoComplete != NULL)
  3913. {
  3914. autoComplete->CheckFieldRef(BfNodeDynCast<BfIdentifierNode>(targetSrc), fieldInstance);
  3915. if ((autoComplete->mResolveType == BfResolveType_GetResultString) && (autoComplete->IsAutocompleteNode(targetSrc)))
  3916. {
  3917. autoComplete->mResultString = ":";
  3918. autoComplete->mResultString += mModule->TypeToString(fieldInstance->mResolvedType);
  3919. autoComplete->mResultString += " ";
  3920. autoComplete->mResultString += mModule->TypeToString(curCheckType);
  3921. autoComplete->mResultString += ".";
  3922. autoComplete->mResultString += field->mName;
  3923. if (fieldInstance->mConstIdx != -1)
  3924. {
  3925. String constStr = autoComplete->ConstantToString(curCheckType->mConstHolder, BfIRValue(BfIRValueFlags_Const, fieldInstance->mConstIdx));
  3926. if (!constStr.IsEmpty())
  3927. {
  3928. autoComplete->mResultString += " = ";
  3929. if (constStr.StartsWith(':'))
  3930. autoComplete->mResultString.Append(StringView(constStr, 1, constStr.mLength - 1));
  3931. else
  3932. autoComplete->mResultString += constStr;
  3933. }
  3934. }
  3935. auto fieldDecl = fieldInstance->GetFieldDef()->mFieldDeclaration;
  3936. if ((fieldDecl != NULL) && (fieldDecl->mDocumentation != NULL))
  3937. {
  3938. String docString;
  3939. fieldDecl->mDocumentation->GetDocString(docString);
  3940. autoComplete->mResultString += "\x03";
  3941. autoComplete->mResultString += docString;
  3942. }
  3943. }
  3944. }
  3945. if (field->mIsStatic)
  3946. {
  3947. if ((target) && ((flags & BfLookupFieldFlag_IsImplicitThis) == 0) && (!curCheckType->mTypeDef->IsGlobalsContainer()))
  3948. {
  3949. //CS0176: Member 'Program.sVal' cannot be accessed with an instance reference; qualify it with a type name instead
  3950. mModule->Fail(StrFormat("Member '%s.%s' cannot be accessed with an instance reference; qualify it with a type name instead",
  3951. mModule->TypeToString(curCheckType).c_str(), field->mName.c_str()), targetSrc);
  3952. }
  3953. // Target must be an implicit 'this', or an error (accessing a static with a non-static target).
  3954. // Not actually needed in either case since this is a static lookup.
  3955. mResultLocalVar = NULL;
  3956. }
  3957. bool isConst = false;
  3958. if (field->mIsConst)
  3959. {
  3960. isConst = true;
  3961. auto fieldDef = fieldInstance->GetFieldDef();
  3962. if ((resolvedFieldType->IsPointer()) && (fieldDef->mIsExtern))
  3963. isConst = false;
  3964. }
  3965. if (resolvedFieldType->IsValuelessType())
  3966. {
  3967. return BfTypedValue(BfIRValue::sValueless, resolvedFieldType, true);
  3968. }
  3969. if (isConst)
  3970. {
  3971. if (fieldInstance->mIsEnumPayloadCase)
  3972. {
  3973. auto dscrType = curCheckType->GetDiscriminatorType();
  3974. mModule->mBfIRBuilder->PopulateType(curCheckType);
  3975. int tagIdx = -fieldInstance->mDataIdx - 1;
  3976. if ((mBfEvalExprFlags & BfEvalExprFlags_AllowEnumId) != 0)
  3977. {
  3978. return BfTypedValue(mModule->mBfIRBuilder->CreateConst(dscrType->mTypeDef->mTypeCode, tagIdx), fieldInstance->mOwner);
  3979. }
  3980. mModule->PopulateType(fieldInstance->mOwner, BfPopulateType_Data);
  3981. if (auto fieldTypeInstance = fieldInstance->mResolvedType->ToTypeInstance())
  3982. {
  3983. bool hasFields = false;
  3984. for (auto& fieldInstance : fieldTypeInstance->mFieldInstances)
  3985. {
  3986. if (!fieldInstance.mResolvedType->IsVoid())
  3987. hasFields = true;
  3988. }
  3989. if (hasFields)
  3990. mModule->FailAfter("Enum payload arguments expected", targetSrc);
  3991. }
  3992. SizedArray<BfIRValue, 3> values;
  3993. values.Add(mModule->mBfIRBuilder->CreateConstAggZero(mModule->mBfIRBuilder->MapType(curCheckType->mBaseType)));
  3994. values.Add(mModule->GetDefaultValue(curCheckType->GetUnionInnerType()));
  3995. values.Add(mModule->mBfIRBuilder->CreateConst(dscrType->mTypeDef->mTypeCode, tagIdx));
  3996. return BfTypedValue(mModule->mBfIRBuilder->CreateConstAgg(mModule->mBfIRBuilder->MapType(curCheckType), values), curCheckType);
  3997. }
  3998. if (fieldInstance->mConstIdx == -1)
  3999. {
  4000. if ((mBfEvalExprFlags & BfEvalExprFlags_DeclType) != 0)
  4001. {
  4002. // We don't need a real value
  4003. return BfTypedValue(mModule->GetDefaultValue(resolvedFieldType), resolvedFieldType);
  4004. }
  4005. curCheckType->mModule->ResolveConstField(curCheckType, fieldInstance, field);
  4006. if (fieldInstance->mConstIdx == -1)
  4007. return BfTypedValue(mModule->GetDefaultValue(resolvedFieldType), resolvedFieldType);
  4008. }
  4009. BF_ASSERT(fieldInstance->mConstIdx != -1);
  4010. auto foreignConst = curCheckType->mConstHolder->GetConstantById(fieldInstance->mConstIdx);
  4011. auto retVal = mModule->ConstantToCurrent(foreignConst, curCheckType->mConstHolder, resolvedFieldType);
  4012. return BfTypedValue(retVal, resolvedFieldType);
  4013. }
  4014. else if (field->mIsStatic)
  4015. {
  4016. mModule->CheckStaticAccess(curCheckType);
  4017. auto retVal = mModule->ReferenceStaticField(fieldInstance);
  4018. bool isStaticCtor = (mModule->mCurMethodInstance != NULL) &&
  4019. (mModule->mCurMethodInstance->mMethodDef->IsCtorOrInit()) &&
  4020. (mModule->mCurMethodInstance->mMethodDef->mIsStatic);
  4021. if ((field->mIsReadOnly) && (!isStaticCtor))
  4022. {
  4023. if (retVal.IsAddr())
  4024. retVal.mKind = BfTypedValueKind_ReadOnlyAddr;
  4025. }
  4026. else
  4027. mIsHeapReference = true;
  4028. return retVal;
  4029. }
  4030. else if (!target)
  4031. {
  4032. if (mModule->PreFail())
  4033. {
  4034. if ((flags & BfLookupFieldFlag_CheckingOuter) != 0)
  4035. 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()),
  4036. targetSrc);
  4037. else if ((mModule->mCurMethodInstance != NULL) && (mModule->mCurMethodInstance->mMethodDef->mMethodType == BfMethodType_CtorCalcAppend))
  4038. mModule->Fail(StrFormat("Cannot reference field '%s' before append allocations", field->mName.c_str()), targetSrc);
  4039. else
  4040. mModule->Fail(StrFormat("Cannot reference non-static field '%s' from a static method", field->mName.c_str()), targetSrc);
  4041. }
  4042. return mModule->GetDefaultTypedValue(resolvedFieldType, false, BfDefaultValueKind_Addr);
  4043. }
  4044. if ((mResultLocalVar != NULL) && (fieldInstance->mMergedDataIdx != -1))
  4045. {
  4046. if (mResultLocalVarFieldCount != 1)
  4047. {
  4048. fieldInstance->GetDataRange(mResultLocalVarField, mResultLocalVarFieldCount);
  4049. mResultLocalVarRefNode = targetSrc;
  4050. }
  4051. }
  4052. if ((curCheckType->IsIncomplete()) && (!curCheckType->mNeedsMethodProcessing))
  4053. {
  4054. BF_ASSERT(curCheckType->mTypeFailed || (mModule->mCurMethodState == NULL) || (mModule->mCurMethodState->mTempKind != BfMethodState::TempKind_None) || (mModule->mCompiler->IsAutocomplete()));
  4055. return mModule->GetDefaultTypedValue(resolvedFieldType);
  4056. }
  4057. bool isTemporary = target.IsTempAddr();
  4058. bool wantsLoadValue = false;
  4059. bool wantsReadOnly = false;
  4060. if ((field->mIsReadOnly) && (mModule->mCurMethodInstance != NULL) && ((!mModule->mCurMethodInstance->mMethodDef->IsCtorOrInit()) || (!target.IsThis())))
  4061. wantsReadOnly = true;
  4062. bool isComposite = target.mType->IsComposite();
  4063. if ((isComposite) && (!target.mType->IsTypedPrimitive()) && (!target.IsAddr()))
  4064. isTemporary = true;
  4065. if ((isComposite) && (!target.IsAddr()))
  4066. wantsLoadValue = true;
  4067. if ((target.mType->IsWrappableType()) && (!target.mType->IsPointer()))
  4068. {
  4069. BfTypeInstance* primStructType = mModule->GetWrappedStructType(target.mType);
  4070. BfIRValue allocaInst = mModule->CreateAlloca(primStructType, true, "tmpStruct");
  4071. BfIRValue elementAddr = mModule->mBfIRBuilder->CreateInBoundsGEP(allocaInst, 0, 1);
  4072. mModule->mBfIRBuilder->CreateStore(target.mValue, elementAddr);
  4073. target = BfTypedValue(allocaInst, primStructType, true);
  4074. }
  4075. if (target.IsCopyOnMutate())
  4076. target = mModule->CopyValue(target);
  4077. BfTypedValue targetValue;
  4078. if ((isBaseLookup) && (!target.IsSplat()))
  4079. {
  4080. if ((!isComposite) || (target.IsAddr()))
  4081. targetValue = BfTypedValue(mModule->mBfIRBuilder->CreateBitCast(target.mValue, mModule->mBfIRBuilder->MapTypeInstPtr(curCheckType)), curCheckType);
  4082. else
  4083. {
  4084. BfIRValue curVal = target.mValue;
  4085. auto baseCheckType = target.mType->ToTypeInstance();
  4086. while (baseCheckType != curCheckType)
  4087. {
  4088. curVal = mModule->mBfIRBuilder->CreateExtractValue(curVal, 0);
  4089. baseCheckType = baseCheckType->mBaseType;
  4090. }
  4091. targetValue = BfTypedValue(curVal, curCheckType);
  4092. }
  4093. }
  4094. else
  4095. targetValue = target;
  4096. bool doAccessCheck = true;
  4097. if ((flags & BfLookupFieldFlag_BindOnly) != 0)
  4098. doAccessCheck = false;
  4099. if ((mModule->mAttributeState != NULL) && (mModule->mAttributeState->mCustomAttributes != NULL) && (mModule->mAttributeState->mCustomAttributes->Contains(mModule->mCompiler->mDisableObjectAccessChecksAttributeTypeDef)))
  4100. doAccessCheck = false;
  4101. if (target.IsThis())
  4102. {
  4103. if (!mModule->mCurMethodState->mMayNeedThisAccessCheck)
  4104. doAccessCheck = false;
  4105. }
  4106. if (doAccessCheck)
  4107. mModule->EmitObjectAccessCheck(target);
  4108. if (fieldInstance->mDataIdx < 0)
  4109. {
  4110. BF_ASSERT(curCheckType->mTypeFailed);
  4111. return mModule->GetDefaultTypedValue(resolvedFieldType);
  4112. }
  4113. BfTypedValue retVal;
  4114. if (target.IsSplat())
  4115. {
  4116. retVal = mModule->ExtractValue(targetValue, fieldInstance, fieldInstance->mDataIdx);
  4117. }
  4118. else if ((target.mType->IsStruct()) && (!target.IsAddr()))
  4119. {
  4120. mModule->mBfIRBuilder->PopulateType(targetValue.mType);
  4121. retVal = BfTypedValue(mModule->mBfIRBuilder->CreateExtractValue(targetValue.mValue, fieldInstance->mDataIdx/*, field->mName*/),
  4122. resolvedFieldType);
  4123. }
  4124. else
  4125. {
  4126. mModule->mBfIRBuilder->PopulateType(curCheckType);
  4127. if ((targetValue.IsAddr()) && (!curCheckType->IsValueType()))
  4128. targetValue = mModule->LoadValue(targetValue);
  4129. retVal = BfTypedValue(mModule->mBfIRBuilder->CreateInBoundsGEP(targetValue.mValue, 0, fieldInstance->mDataIdx/*, field->mName*/),
  4130. resolvedFieldType, target.IsReadOnly() ? BfTypedValueKind_ReadOnlyAddr : BfTypedValueKind_Addr);
  4131. }
  4132. if (!retVal.IsSplat())
  4133. {
  4134. if (curCheckType->mIsUnion)
  4135. {
  4136. BfIRType llvmPtrType = mModule->mBfIRBuilder->GetPointerTo(mModule->mBfIRBuilder->MapType(resolvedFieldType));
  4137. retVal.mValue = mModule->mBfIRBuilder->CreateBitCast(retVal.mValue, llvmPtrType);
  4138. }
  4139. }
  4140. if (wantsLoadValue)
  4141. retVal = mModule->LoadValue(retVal, NULL, mIsVolatileReference);
  4142. else
  4143. {
  4144. if ((wantsReadOnly) && (retVal.IsAddr())&& (!retVal.IsReadOnly()))
  4145. retVal.mKind = BfTypedValueKind_ReadOnlyAddr;
  4146. mIsHeapReference = true;
  4147. }
  4148. if (isTemporary)
  4149. {
  4150. if (retVal.IsAddr())
  4151. retVal.mKind = BfTypedValueKind_TempAddr;
  4152. }
  4153. return retVal;
  4154. }
  4155. BfPropertyDef* nextProp = NULL;
  4156. if (curCheckType->mTypeDef->mPropertySet.TryGetWith(fieldName, &entry))
  4157. nextProp = (BfPropertyDef*)entry->mMemberDef;
  4158. if (nextProp != NULL)
  4159. {
  4160. BfCheckedKind checkedKind = BfCheckedKind_NotSet;
  4161. bool isInlined = false;
  4162. if ((mModule->mAttributeState != NULL) && (mModule->mAttributeState->mCustomAttributes != NULL))
  4163. {
  4164. if (mModule->mAttributeState->mCustomAttributes->Contains(mModule->mCompiler->mInlineAttributeTypeDef))
  4165. {
  4166. isInlined = true;
  4167. mModule->mAttributeState->mUsed = true;
  4168. }
  4169. if (mModule->mAttributeState->mCustomAttributes->Contains(mModule->mCompiler->mCheckedAttributeTypeDef))
  4170. {
  4171. checkedKind = BfCheckedKind_Checked;
  4172. mModule->mAttributeState->mUsed = true;
  4173. }
  4174. if (mModule->mAttributeState->mCustomAttributes->Contains(mModule->mCompiler->mUncheckedAttributeTypeDef))
  4175. {
  4176. checkedKind = BfCheckedKind_Unchecked;
  4177. mModule->mAttributeState->mUsed = true;
  4178. }
  4179. }
  4180. BfPropertyDef* matchedProp = NULL;
  4181. while (nextProp != NULL)
  4182. {
  4183. auto prop = nextProp;
  4184. nextProp = nextProp->mNextWithSameName;
  4185. if ((!isFailurePass) && (!mModule->CheckProtection(protectionCheckFlags, curCheckType, prop->mDeclaringType->mProject, prop->mProtection, startCheckType)))
  4186. {
  4187. continue;
  4188. }
  4189. if (!prop->mMethods.IsEmpty())
  4190. {
  4191. BfMethodDef* checkMethod = prop->mMethods[0];;
  4192. // Properties with explicit interfaces or marked as overrides can only be called indirectly
  4193. if ((checkMethod->mExplicitInterface != NULL) || (checkMethod->mIsOverride))
  4194. continue;
  4195. }
  4196. if ((!target.IsStatic()) || (prop->mIsStatic))
  4197. {
  4198. if (!mModule->IsInSpecializedSection())
  4199. {
  4200. if ((!curCheckType->IsTypeMemberIncluded(prop->mDeclaringType, activeTypeDef, mModule)) ||
  4201. (!curCheckType->IsTypeMemberAccessible(prop->mDeclaringType, mModule->GetVisibleProjectSet())))
  4202. continue;
  4203. }
  4204. if (matchedProp != NULL)
  4205. {
  4206. if (mModule->PreFail())
  4207. {
  4208. auto error = mModule->Fail(StrFormat("Ambiguous reference to property '%s.%s'", mModule->TypeToString(curCheckType).c_str(), fieldName.c_str()), targetSrc);
  4209. if (error != NULL)
  4210. {
  4211. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("See property declaration in project '%s'", matchedProp->mDeclaringType->mProject->mName.c_str()), matchedProp->mFieldDeclaration);
  4212. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("See property declaration in project '%s'", prop->mDeclaringType->mProject->mName.c_str()), prop->mFieldDeclaration);
  4213. break;
  4214. }
  4215. }
  4216. }
  4217. matchedProp = prop;
  4218. }
  4219. }
  4220. if (matchedProp != NULL)
  4221. {
  4222. auto prop = matchedProp;
  4223. gPropIdx++;
  4224. mModule->SetElementType(targetSrc, BfSourceElementType_Method);
  4225. mPropSrc = targetSrc;
  4226. mPropDef = prop;
  4227. mPropCheckedKind = checkedKind;
  4228. if (isInlined)
  4229. mPropGetMethodFlags = (BfGetMethodInstanceFlags)(mPropGetMethodFlags | BfGetMethodInstanceFlag_ForceInline);
  4230. if ((mModule->mAttributeState != NULL) && (mModule->mAttributeState->mCustomAttributes != NULL))
  4231. {
  4232. if (mModule->mAttributeState->mCustomAttributes->Contains(mModule->mCompiler->mFriendAttributeTypeDef))
  4233. {
  4234. mPropGetMethodFlags = (BfGetMethodInstanceFlags)(mPropGetMethodFlags | BfGetMethodInstanceFlag_Friend);
  4235. mModule->mAttributeState->mUsed = true;
  4236. }
  4237. if (mModule->mAttributeState->mCustomAttributes->Contains(mModule->mCompiler->mDisableObjectAccessChecksAttributeTypeDef))
  4238. {
  4239. mPropGetMethodFlags = (BfGetMethodInstanceFlags)(mPropGetMethodFlags | BfGetMethodInstanceFlag_DisableObjectAccessChecks);
  4240. mModule->mAttributeState->mUsed = true;
  4241. }
  4242. }
  4243. if (mPropDef->mIsStatic)
  4244. {
  4245. if ((target) && ((flags & BfLookupFieldFlag_IsImplicitThis) == 0) && (!curCheckType->mTypeDef->IsGlobalsContainer()))
  4246. {
  4247. //CS0176: Member 'Program.sVal' cannot be accessed with an instance reference; qualify it with a type name instead
  4248. mModule->Fail(StrFormat("Property '%s.%s' cannot be accessed with an instance reference; qualify it with a type name instead",
  4249. mModule->TypeToString(curCheckType).c_str(), mPropDef->mName.c_str()), targetSrc);
  4250. }
  4251. }
  4252. if (prop->mIsStatic)
  4253. mPropTarget = BfTypedValue(curCheckType);
  4254. else if (isBaseLookup)
  4255. {
  4256. if (target.mValue.IsFake())
  4257. {
  4258. mPropTarget = BfTypedValue(target.mValue, curCheckType, target.mKind);
  4259. }
  4260. else
  4261. {
  4262. mPropTarget = mModule->Cast(targetSrc, target, curCheckType);
  4263. BF_ASSERT(mPropTarget);
  4264. }
  4265. }
  4266. else
  4267. mPropTarget = target;
  4268. if (mPropTarget.mType->IsStructPtr())
  4269. {
  4270. mPropTarget = mModule->LoadValue(mPropTarget);
  4271. mPropTarget = BfTypedValue(mPropTarget.mValue, mPropTarget.mType->GetUnderlyingType(), mPropTarget.IsReadOnly() ? BfTypedValueKind_ReadOnlyAddr : BfTypedValueKind_Addr);
  4272. }
  4273. mOrigPropTarget = mPropTarget;
  4274. auto autoComplete = GetAutoComplete();
  4275. auto resolvePassData = mModule->mCompiler->mResolvePassData;
  4276. if (((autoComplete != NULL) && (autoComplete->mIsGetDefinition)) ||
  4277. ((resolvePassData != NULL) && (resolvePassData->mGetSymbolReferenceKind == BfGetSymbolReferenceKind_Property)))
  4278. {
  4279. BfPropertyDef* basePropDef = mPropDef;
  4280. BfTypeInstance* baseTypeInst = curCheckType;
  4281. mModule->GetBasePropertyDef(basePropDef, baseTypeInst);
  4282. resolvePassData->HandlePropertyReference(targetSrc, baseTypeInst->mTypeDef, basePropDef);
  4283. if ((autoComplete != NULL) && (autoComplete->IsAutocompleteNode(targetSrc)))
  4284. {
  4285. if (autoComplete->mIsGetDefinition)
  4286. {
  4287. //NOTE: passing 'force=true' in here causes https://github.com/beefytech/Beef/issues/1064
  4288. autoComplete->SetDefinitionLocation(basePropDef->GetRefNode());
  4289. }
  4290. autoComplete->mDefProp = basePropDef;
  4291. autoComplete->mDefType = baseTypeInst->mTypeDef;
  4292. }
  4293. }
  4294. if ((autoComplete != NULL) && (autoComplete->mResolveType == BfResolveType_GetResultString) && (autoComplete->IsAutocompleteNode(targetSrc)))
  4295. {
  4296. BfPropertyDef* basePropDef = mPropDef;
  4297. BfTypeInstance* baseTypeInst = curCheckType;
  4298. mModule->GetBasePropertyDef(basePropDef, baseTypeInst);
  4299. autoComplete->mResultString = ":";
  4300. autoComplete->mResultString += mModule->TypeToString(baseTypeInst);
  4301. autoComplete->mResultString += ".";
  4302. autoComplete->mResultString += basePropDef->mName;
  4303. }
  4304. // Check for direct auto-property access
  4305. if ((startCheckType == mModule->mCurTypeInstance) && ((flags & BfLookupFieldFlag_BindOnly) == 0))
  4306. {
  4307. if (auto propertyDeclaration = BfNodeDynCast<BfPropertyDeclaration>(mPropDef->mFieldDeclaration))
  4308. {
  4309. if ((curCheckType->mTypeDef->HasAutoProperty(propertyDeclaration)) && (propertyDeclaration->mVirtualSpecifier == NULL))
  4310. {
  4311. BfMethodDef* getter = GetPropertyMethodDef(mPropDef, BfMethodType_PropertyGetter, BfCheckedKind_NotSet, mPropTarget);
  4312. BfMethodDef* setter = GetPropertyMethodDef(mPropDef, BfMethodType_PropertySetter, BfCheckedKind_NotSet, mPropTarget);
  4313. bool optAllowed = true;
  4314. if ((getter != NULL) && (getter->mBody != NULL))
  4315. optAllowed = false;
  4316. if ((setter != NULL) && (setter->mBody != NULL))
  4317. optAllowed = false;
  4318. if (optAllowed)
  4319. {
  4320. auto autoFieldName = curCheckType->mTypeDef->GetAutoPropertyName(propertyDeclaration);
  4321. auto result = LookupField(targetSrc, target, autoFieldName, (BfLookupFieldFlags)(BfLookupFieldFlag_IgnoreProtection | BfLookupFieldFlag_IsImplicitThis));
  4322. if (result)
  4323. {
  4324. bool needsCopy = true;
  4325. if (setter == NULL)
  4326. {
  4327. if (((mModule->mCurMethodInstance->mMethodDef->mMethodType == BfMethodType_Ctor)) &&
  4328. (startCheckType == mModule->mCurTypeInstance))
  4329. {
  4330. // Allow writing inside ctor
  4331. }
  4332. else
  4333. {
  4334. result.MakeReadOnly();
  4335. needsCopy = false;
  4336. }
  4337. }
  4338. if (result.mKind == BfTypedValueKind_Addr)
  4339. result.mKind = BfTypedValueKind_CopyOnMutateAddr;
  4340. mPropDef = NULL;
  4341. mPropSrc = NULL;
  4342. mOrigPropTarget = NULL;
  4343. return result;
  4344. }
  4345. }
  4346. }
  4347. }
  4348. }
  4349. SetAndRestoreValue<BfTypedValue> prevResult(mResult, target);
  4350. CheckResultForReading(mResult);
  4351. return BfTypedValue();
  4352. }
  4353. }
  4354. isBaseLookup = true;
  4355. curCheckType = curCheckType->mBaseType;
  4356. }
  4357. }
  4358. auto outerTypeDef = mModule->GetOuterType(startCheckType);
  4359. if (outerTypeDef != NULL)
  4360. {
  4361. // Check statics in outer type
  4362. return LookupField(targetSrc, BfTypedValue(outerTypeDef), fieldName, BfLookupFieldFlag_CheckingOuter);
  4363. }
  4364. return BfTypedValue();
  4365. }
  4366. void BfExprEvaluator::ResolveArgValues(BfResolvedArgs& resolvedArgs, BfResolveArgsFlags flags)
  4367. {
  4368. static int idx = 0;
  4369. idx++;
  4370. int curIdx = idx;
  4371. if (resolvedArgs.mArguments == NULL)
  4372. return;
  4373. int argCount = (int)resolvedArgs.mArguments->size();
  4374. if ((resolvedArgs.mCommas != NULL) && (resolvedArgs.mCommas->size() != 0) && (resolvedArgs.mCommas->size() >= resolvedArgs.mArguments->size()))
  4375. {
  4376. //mModule->FailAfter("Expression expected", resolvedArgs.mCommas->back());
  4377. argCount++;
  4378. }
  4379. BfAutoComplete* autoComplete = GetAutoComplete();
  4380. bool hadIgnoredFixits = false;
  4381. if (autoComplete != NULL)
  4382. {
  4383. hadIgnoredFixits = autoComplete->mIgnoreFixits;
  4384. if (flags & BfResolveArgsFlag_DeferFixits)
  4385. autoComplete->mIgnoreFixits = true;
  4386. }
  4387. int deferredArgIdx = 0;
  4388. SizedArray<BfExpression*, 8> deferredArgs;
  4389. int argIdx = 0;
  4390. while (true)
  4391. {
  4392. //printf("Args: %p %p %d\n", resolvedArgs.mArguments, resolvedArgs.mArguments->mVals, resolvedArgs.mArguments->mSize);
  4393. BfExpression* argExpr = NULL;
  4394. bool isDeferredArg = false;
  4395. int curArgIdx = -1;
  4396. if (deferredArgIdx < deferredArgs.size())
  4397. {
  4398. argExpr = deferredArgs[deferredArgIdx++];
  4399. isDeferredArg = true;
  4400. }
  4401. else if (argIdx >= argCount)
  4402. {
  4403. break;
  4404. }
  4405. else
  4406. {
  4407. curArgIdx = argIdx++;
  4408. if (curArgIdx < resolvedArgs.mArguments->size())
  4409. argExpr = (*resolvedArgs.mArguments)[curArgIdx];
  4410. }
  4411. if (argExpr == NULL)
  4412. {
  4413. if (curArgIdx == 0)
  4414. {
  4415. if (resolvedArgs.mOpenToken != NULL)
  4416. mModule->FailAfter("Expression expected", resolvedArgs.mOpenToken);
  4417. }
  4418. else if (resolvedArgs.mCommas != NULL)
  4419. mModule->FailAfter("Expression expected", (*resolvedArgs.mCommas)[curArgIdx - 1]);
  4420. }
  4421. if (auto typedValueExpr = BfNodeDynCast<BfTypedValueExpression>(argExpr))
  4422. {
  4423. BfResolvedArg resolvedArg;
  4424. resolvedArg.mTypedValue = typedValueExpr->mTypedValue;
  4425. resolvedArg.mExpression = typedValueExpr->mRefNode;
  4426. resolvedArgs.mResolvedArgs.push_back(resolvedArg);
  4427. continue;
  4428. }
  4429. BfResolvedArg resolvedArg;
  4430. if (isDeferredArg)
  4431. resolvedArg.mArgFlags = (BfArgFlags)(resolvedArg.mArgFlags | BfArgFlag_StringInterpolateArg);
  4432. BfExprEvaluator exprEvaluator(mModule);
  4433. exprEvaluator.mResolveGenericParam = (flags & BfResolveArgsFlag_AllowUnresolvedTypes) == 0;
  4434. exprEvaluator.mBfEvalExprFlags = (BfEvalExprFlags)(exprEvaluator.mBfEvalExprFlags | BfEvalExprFlags_AllowRefExpr | BfEvalExprFlags_AllowOutExpr |
  4435. (mBfEvalExprFlags & (BfEvalExprFlags_Comptime)));
  4436. bool handled = false;
  4437. bool evaluated = false;
  4438. if (auto interpolateExpr = BfNodeDynCastExact<BfStringInterpolationExpression>(argExpr))
  4439. {
  4440. if ((interpolateExpr->mAllocNode == NULL) || ((flags & BfResolveArgsFlag_InsideStringInterpolationAlloc) != 0))
  4441. {
  4442. resolvedArg.mArgFlags = (BfArgFlags)(resolvedArg.mArgFlags | BfArgFlag_StringInterpolateFormat);
  4443. for (auto innerExpr : interpolateExpr->mExpressions)
  4444. deferredArgs.Add(innerExpr);
  4445. }
  4446. }
  4447. if (auto unaryOpExpr = BfNodeDynCastExact<BfUnaryOperatorExpression>(argExpr))
  4448. {
  4449. if ((unaryOpExpr->mOp == BfUnaryOp_Cascade) && ((flags & BfResolveArgsFlag_FromIndexer) == 0))
  4450. {
  4451. if ((mBfEvalExprFlags & BfEvalExprFlags_InCascade) != 0)
  4452. mModule->Fail("Cascade already specified on call target", unaryOpExpr->mOpToken);
  4453. resolvedArg.mArgFlags = (BfArgFlags)(resolvedArg.mArgFlags | BfArgFlag_Cascade);
  4454. argExpr = unaryOpExpr->mExpression;
  4455. }
  4456. }
  4457. bool deferParamEval = false;
  4458. if ((flags & BfResolveArgsFlag_DeferParamEval) != 0)
  4459. {
  4460. if (argExpr != NULL)
  4461. {
  4462. BfDeferEvalChecker deferEvalChecker;
  4463. deferEvalChecker.mDeferDelegateBind = false;
  4464. argExpr->Accept(&deferEvalChecker);
  4465. deferParamEval = deferEvalChecker.mNeedsDeferEval;
  4466. }
  4467. }
  4468. if (deferParamEval)
  4469. {
  4470. resolvedArg.mArgFlags = (BfArgFlags)(resolvedArg.mArgFlags | BfArgFlag_DeferredEval);
  4471. handled = true;
  4472. }
  4473. else if (auto delegateBindExpression = BfNodeDynCast<BfDelegateBindExpression>(argExpr))
  4474. {
  4475. resolvedArg.mArgFlags = (BfArgFlags)(resolvedArg.mArgFlags | BfArgFlag_DelegateBindAttempt);
  4476. handled = true;
  4477. }
  4478. else if (auto lambdaBindExpression = BfNodeDynCast<BfLambdaBindExpression>(argExpr))
  4479. {
  4480. resolvedArg.mArgFlags = (BfArgFlags)(resolvedArg.mArgFlags | BfArgFlag_LambdaBindAttempt);
  4481. handled = true;
  4482. }
  4483. else if (auto memberRef = BfNodeDynCast<BfMemberReferenceExpression>(argExpr))
  4484. {
  4485. if (memberRef->mTarget == NULL)
  4486. {
  4487. resolvedArg.mArgFlags = (BfArgFlags)(resolvedArg.mArgFlags | BfArgFlag_UnqualifiedDotAttempt);
  4488. handled = true;
  4489. }
  4490. }
  4491. else if (auto invokeExpr = BfNodeDynCast<BfInvocationExpression>(argExpr))
  4492. {
  4493. if (auto memberRef = BfNodeDynCast<BfMemberReferenceExpression>(invokeExpr->mTarget))
  4494. {
  4495. if (memberRef->mTarget == NULL)
  4496. {
  4497. resolvedArg.mArgFlags = (BfArgFlags)(resolvedArg.mArgFlags | BfArgFlag_UnqualifiedDotAttempt);
  4498. handled = true;
  4499. }
  4500. }
  4501. }
  4502. else if (auto defaultExpr = BfNodeDynCast<BfDefaultExpression>(argExpr))
  4503. {
  4504. if (defaultExpr->mTypeRef == NULL)
  4505. {
  4506. resolvedArg.mArgFlags = (BfArgFlags)(resolvedArg.mArgFlags | BfArgFlag_UntypedDefault);
  4507. handled = true;
  4508. }
  4509. }
  4510. else if (auto varDeclExpr = BfNodeDynCast<BfVariableDeclaration>(argExpr))
  4511. {
  4512. resolvedArg.mArgFlags = (BfArgFlags)(resolvedArg.mArgFlags | BfArgFlag_VariableDeclaration);
  4513. handled = true;
  4514. }
  4515. else if (auto unaryExpr = BfNodeDynCast<BfUnaryOperatorExpression>(argExpr))
  4516. {
  4517. if (unaryExpr->mOp == BfUnaryOp_Params)
  4518. {
  4519. resolvedArg.mArgFlags = (BfArgFlags)(resolvedArg.mArgFlags | BfArgFlag_ParamsExpr);
  4520. }
  4521. }
  4522. else if (auto uninitExpr = BfNodeDynCast<BfUninitializedExpression>(argExpr))
  4523. {
  4524. resolvedArg.mArgFlags = (BfArgFlags)(resolvedArg.mArgFlags | BfArgFlag_UninitializedExpr);
  4525. handled = true;
  4526. }
  4527. /*else if (auto castExpr = BfNodeDynCast<BfCastExpression>(argExpr))
  4528. {
  4529. if (auto namedTypeRef = BfNodeDynCastExact<BfNamedTypeReference>(castExpr->mTypeRef))
  4530. {
  4531. if (namedTypeRef->ToString() == "ExpectedType")
  4532. {
  4533. resolvedArg.mArgFlags = (BfArgFlags)(resolvedArg.mArgFlags | BfArgFlag_ExpectedTypeCast);
  4534. handled = true;
  4535. }
  4536. }
  4537. }*/
  4538. if ((argExpr != NULL) && (!handled))
  4539. {
  4540. bool deferParamValues = (flags & BfResolveArgsFlag_DeferParamValues) != 0;
  4541. SetAndRestoreValue<bool> ignoreWrites(mModule->mBfIRBuilder->mIgnoreWrites, mModule->mBfIRBuilder->mIgnoreWrites || deferParamValues);
  4542. auto prevInsertBlock = mModule->mBfIRBuilder->GetInsertBlock();
  4543. if (deferParamValues)
  4544. resolvedArg.mArgFlags = (BfArgFlags)(resolvedArg.mArgFlags | BfArgFlag_DeferredValue);
  4545. if (!evaluated)
  4546. {
  4547. exprEvaluator.mBfEvalExprFlags = (BfEvalExprFlags)(exprEvaluator.mBfEvalExprFlags | BfEvalExprFlags_AllowParamsExpr);
  4548. if ((resolvedArg.mArgFlags & BfArgFlag_StringInterpolateFormat) != 0)
  4549. exprEvaluator.mBfEvalExprFlags = (BfEvalExprFlags)(exprEvaluator.mBfEvalExprFlags | BfEvalExprFlags_StringInterpolateFormat);
  4550. exprEvaluator.Evaluate(argExpr, false, false, true);
  4551. }
  4552. if ((mModule->mCurMethodState != NULL) && (exprEvaluator.mResultLocalVar != NULL) && (exprEvaluator.mResultLocalVarRefNode != NULL))
  4553. {
  4554. auto localVar = exprEvaluator.mResultLocalVar;
  4555. int fieldIdx = mResultLocalVarField - 1;
  4556. auto methodState = mModule->mCurMethodState->GetMethodStateForLocal(localVar);
  4557. if (localVar->mCompositeCount >= 0)
  4558. {
  4559. if ((resolvedArg.mArgFlags & BfArgFlag_ParamsExpr) == 0)
  4560. mModule->Warn(0, "'params' token expected", argExpr);
  4561. for (int compositeIdx = 0; compositeIdx < localVar->mCompositeCount; compositeIdx++)
  4562. {
  4563. BfResolvedArg compositeResolvedArg;
  4564. auto compositeLocalVar = methodState->mLocals[localVar->mLocalVarIdx + compositeIdx + 1];
  4565. auto argValue = exprEvaluator.LoadLocal(compositeLocalVar, true);
  4566. if (argValue)
  4567. {
  4568. if (!argValue.mType->IsStruct())
  4569. argValue = mModule->LoadValue(argValue, NULL, exprEvaluator.mIsVolatileReference);
  4570. }
  4571. resolvedArg.mTypedValue = argValue;
  4572. resolvedArg.mExpression = argExpr;
  4573. resolvedArg.mArgFlags = (BfArgFlags)(resolvedArg.mArgFlags | BfArgFlag_FromParamComposite);
  4574. resolvedArgs.mResolvedArgs.push_back(resolvedArg);
  4575. }
  4576. continue;
  4577. }
  4578. }
  4579. exprEvaluator.CheckResultForReading(exprEvaluator.mResult);
  4580. auto argValue = exprEvaluator.mResult;
  4581. if (argValue)
  4582. {
  4583. //resolvedArg.mResolvedType = mModule->ResolveGenericType(argValue.mType);
  4584. resolvedArg.mResolvedType = argValue.mType;
  4585. if (resolvedArg.mResolvedType->IsRef())
  4586. argValue.mKind = BfTypedValueKind_Value;
  4587. else if ((!resolvedArg.mResolvedType->IsStruct()) && (!resolvedArg.mResolvedType->IsSizedArray()) && (!resolvedArg.mResolvedType->IsValuelessType()))
  4588. argValue = mModule->LoadValue(argValue, NULL, exprEvaluator.mIsVolatileReference);
  4589. }
  4590. resolvedArg.mTypedValue = argValue;
  4591. if (deferParamValues)
  4592. mModule->mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  4593. }
  4594. resolvedArg.mExpression = argExpr;
  4595. resolvedArgs.mResolvedArgs.push_back(resolvedArg);
  4596. }
  4597. if (autoComplete != NULL)
  4598. autoComplete->mIgnoreFixits = hadIgnoredFixits;
  4599. }
  4600. void BfExprEvaluator::PerformCallChecks(BfMethodInstance* methodInstance, BfAstNode* targetSrc)
  4601. {
  4602. BfCustomAttributes* customAttributes = methodInstance->GetCustomAttributes();
  4603. if (customAttributes != NULL)
  4604. mModule->CheckErrorAttributes(methodInstance->GetOwner(), methodInstance, customAttributes, targetSrc);
  4605. }
  4606. BfTypedValue BfExprEvaluator::CreateCall(BfAstNode* targetSrc, BfMethodInstance* methodInstance, BfIRValue func, bool bypassVirtual, SizedArrayImpl<BfIRValue>& irArgs, BfTypedValue* sret, BfCreateCallFlags callFlags)
  4607. {
  4608. // static int sCallIdx = 0;
  4609. // if (!mModule->mCompiler->mIsResolveOnly)
  4610. // sCallIdx++;
  4611. // int callIdx = sCallIdx;
  4612. // if (callIdx == 0x000000E8)
  4613. // {
  4614. // NOP;
  4615. // }
  4616. auto methodDef = methodInstance->mMethodDef;
  4617. BfIRValue funcCallInst = func;
  4618. auto importCallKind = methodInstance->GetImportCallKind();
  4619. if ((funcCallInst) && (importCallKind != BfImportCallKind_None))
  4620. {
  4621. if ((funcCallInst.IsFake()) && (!mModule->mBfIRBuilder->mIgnoreWrites))
  4622. {
  4623. mModule->mFuncReferences.TryGetValue(methodInstance, &funcCallInst);
  4624. }
  4625. if ((importCallKind == BfImportCallKind_GlobalVar) &&
  4626. (methodInstance->mHotMethod == NULL) &&
  4627. (mModule->mCompiler->IsHotCompile()))
  4628. {
  4629. // This may actually be a BfImportCallKind_GlobalVar_Hot, so check it...
  4630. mModule->CheckHotMethod(methodInstance, "");
  4631. importCallKind = methodInstance->GetImportCallKind();
  4632. }
  4633. if (importCallKind == BfImportCallKind_GlobalVar_Hot)
  4634. {
  4635. //TODO: Check against NULL for calling BfLoadSharedLibraries
  4636. auto checkVal = mModule->mBfIRBuilder->CreateLoad(funcCallInst);
  4637. BfIRBlock nullBlock = mModule->mBfIRBuilder->CreateBlock("importNull");
  4638. BfIRBlock doneBlock = mModule->mBfIRBuilder->CreateBlock("importLoad");
  4639. auto condVal = mModule->mBfIRBuilder->CreateIsNull(checkVal);
  4640. mModule->mBfIRBuilder->CreateCondBr(condVal, nullBlock, doneBlock);
  4641. mModule->mBfIRBuilder->AddBlock(nullBlock);
  4642. mModule->mBfIRBuilder->SetInsertPoint(nullBlock);
  4643. auto loadSharedLibsFunc = mModule->GetBuiltInFunc(BfBuiltInFuncType_LoadSharedLibraries);
  4644. mModule->mBfIRBuilder->CreateCall(loadSharedLibsFunc, SizedArray<BfIRValue, 0>());
  4645. mModule->mBfIRBuilder->CreateBr(doneBlock);
  4646. mModule->mBfIRBuilder->AddBlock(doneBlock);
  4647. mModule->mBfIRBuilder->SetInsertPoint(doneBlock);
  4648. funcCallInst = mModule->mBfIRBuilder->CreateLoad(funcCallInst);
  4649. }
  4650. else
  4651. {
  4652. funcCallInst = mModule->mBfIRBuilder->CreateLoad(funcCallInst);
  4653. }
  4654. }
  4655. if ((methodInstance->GetOwner()->IsInstanceOf(mModule->mCompiler->mDeferredCallTypeDef)) &&
  4656. (methodInstance->mMethodDef->mName == "Cancel"))
  4657. {
  4658. if (mModule->mCurMethodState != NULL)
  4659. mModule->mCurMethodState->mCancelledDeferredCall = true;
  4660. }
  4661. if (methodDef->mIsNoReturn)
  4662. {
  4663. mModule->mCurMethodState->SetHadReturn(true);
  4664. mModule->mCurMethodState->mLeftBlockUncond = true;
  4665. }
  4666. if (mModule->mCurTypeInstance != NULL)
  4667. {
  4668. bool isVirtual = (methodInstance->mVirtualTableIdx != -1) && (!bypassVirtual);
  4669. mModule->AddDependency(methodInstance->mMethodInstanceGroup->mOwner, mModule->mCurTypeInstance, isVirtual ? BfDependencyMap::DependencyFlag_VirtualCall : BfDependencyMap::DependencyFlag_Calls);
  4670. mModule->AddCallDependency(methodInstance, bypassVirtual);
  4671. }
  4672. if (methodInstance->GetOwner()->IsUnspecializedType())
  4673. {
  4674. BF_ASSERT((!methodInstance->mIRFunction) || (methodInstance == mModule->mCurMethodInstance));
  4675. }
  4676. if (mFunctionBindResult != NULL)
  4677. {
  4678. BF_ASSERT(mFunctionBindResult->mMethodInstance == NULL);
  4679. mFunctionBindResult->mMethodInstance = methodInstance;
  4680. for (auto arg : irArgs)
  4681. mFunctionBindResult->mIRArgs.push_back(arg);
  4682. }
  4683. BfType* origReturnType = methodInstance->mReturnType;
  4684. /*if (origReturnType->IsSelf())
  4685. {
  4686. origReturnType = methodInstance->GetOwner();
  4687. BF_ASSERT(origReturnType->IsInterface());
  4688. }*/
  4689. BfType* returnType = origReturnType;
  4690. BfTypedValue sretVal;
  4691. auto _GetDefaultReturnValue = [&]()
  4692. {
  4693. if (methodInstance->mVirtualTableIdx == -1)
  4694. {
  4695. if (methodInstance->GetOwner()->IsInterface())
  4696. {
  4697. // We're attempting to directly invoke a non-virtual interface method, if we're return an interface then
  4698. // it is a concrete interface
  4699. if (returnType->IsInterface())
  4700. returnType = mModule->CreateConcreteInterfaceType(returnType->ToTypeInstance());
  4701. }
  4702. }
  4703. if ((returnType->IsVar()) && (mExpectingType != NULL))
  4704. returnType = mExpectingType;
  4705. if (returnType->IsRef())
  4706. {
  4707. auto result = mModule->GetDefaultTypedValue(returnType->GetUnderlyingType(), true, BfDefaultValueKind_Addr);
  4708. if (methodDef->mIsReadOnly)
  4709. result.mKind = BfTypedValueKind_ReadOnlyAddr;
  4710. return result;
  4711. }
  4712. else
  4713. {
  4714. auto val = mModule->GetDefaultTypedValue(returnType, true, (GetStructRetIdx(methodInstance) != -1) ? BfDefaultValueKind_Addr : BfDefaultValueKind_Value);
  4715. if (val.mKind == BfTypedValueKind_Addr)
  4716. val.mKind = BfTypedValueKind_RestrictedTempAddr;
  4717. return val;
  4718. }
  4719. };
  4720. mModule->PopulateType(origReturnType, BfPopulateType_Data);
  4721. if (GetStructRetIdx(methodInstance) != -1)
  4722. {
  4723. // We need to ensure that mReceivingValue has the correct type, otherwise it's possible that a conversion operator needs to be applied
  4724. // This happens for returning Result<T>'s with a 'T' value
  4725. if ((sret == NULL) && (mReceivingValue != NULL) && (mReceivingValue->mType == returnType))
  4726. {
  4727. sretVal = *mReceivingValue;
  4728. sret = &sretVal;
  4729. auto ptrType = mModule->CreatePointerType(returnType);
  4730. if (returnType != sret->mType)
  4731. {
  4732. sret->mValue = mModule->mBfIRBuilder->CreateBitCast(sret->mValue, mModule->mBfIRBuilder->MapType(ptrType));
  4733. sret->mType = returnType;
  4734. }
  4735. mReceivingValue = NULL;
  4736. }
  4737. if (sret == NULL)
  4738. {
  4739. sretVal = BfTypedValue(mModule->CreateAlloca(returnType), returnType, BfTypedValueKind_RestrictedTempAddr);
  4740. sret = &sretVal;
  4741. }
  4742. }
  4743. else
  4744. {
  4745. BF_ASSERT(sret == NULL);
  4746. }
  4747. if ((mModule->mCurMethodState != NULL) && (mModule->mCurMethodState->mClosureState != NULL) && (mModule->mCurMethodState->mClosureState->mCapturing))
  4748. {
  4749. return _GetDefaultReturnValue();
  4750. }
  4751. BF_ASSERT(!methodInstance->mDisallowCalling);
  4752. if ((mModule->mCompiler->mResolvePassData != NULL) && (mModule->mCompiler->mResolvePassData->mAutoComplete != NULL))
  4753. {
  4754. bool wantQuickEval = true;
  4755. if (IsComptime())
  4756. {
  4757. auto autoComplete = mModule->mCompiler->mResolvePassData->mAutoComplete;
  4758. wantQuickEval =
  4759. ((autoComplete->mResolveType != BfResolveType_Autocomplete) &&
  4760. (autoComplete->mResolveType != BfResolveType_Autocomplete_HighPri) &&
  4761. (autoComplete->mResolveType != BfResolveType_GetResultString));
  4762. }
  4763. if (wantQuickEval)
  4764. {
  4765. // In an autocomplete pass we may have stale method references that need to be resolved
  4766. // in the full classify pass, and in the full classify pass while just refreshing internals, we
  4767. // may have NULL funcs temporarily. We simply skip generating the method call here.
  4768. if ((mBfEvalExprFlags & BfEvalExprFlags_Comptime) != 0)
  4769. {
  4770. if (methodInstance->mReturnType->IsInstanceOf(mModule->mCompiler->mSpanTypeDef))
  4771. {
  4772. if ((mExpectingType != NULL) && (mExpectingType->IsSizedArray()))
  4773. {
  4774. return BfTypedValue(mModule->mBfIRBuilder->GetUndefConstValue(mModule->mBfIRBuilder->MapType(mExpectingType)), mExpectingType);
  4775. }
  4776. }
  4777. auto returnType = methodInstance->mReturnType;
  4778. if ((returnType->IsVar()) && (mExpectingType != NULL))
  4779. returnType = mExpectingType;
  4780. if (methodInstance->mReturnType->IsValuelessType())
  4781. return BfTypedValue(mModule->mBfIRBuilder->GetFakeVal(), returnType);
  4782. return BfTypedValue(mModule->mBfIRBuilder->GetUndefConstValue(mModule->mBfIRBuilder->MapType(returnType)), returnType);
  4783. }
  4784. BfTypedValue result;
  4785. if (sret != NULL)
  4786. result = *sret;
  4787. else
  4788. result = _GetDefaultReturnValue();
  4789. return result;
  4790. }
  4791. }
  4792. bool forceBind = false;
  4793. if (mModule->mCompiler->mCEMachine != NULL)
  4794. {
  4795. bool doConstReturn = false;
  4796. if ((mBfEvalExprFlags & BfEvalExprFlags_Comptime) != 0)
  4797. {
  4798. if (mFunctionBindResult != NULL)
  4799. {
  4800. forceBind = true;
  4801. }
  4802. else if ((mBfEvalExprFlags & BfEvalExprFlags_InCascade) != 0)
  4803. {
  4804. mModule->Fail("Const evaluation not allowed with cascade operator", targetSrc);
  4805. }
  4806. else if (methodInstance->mIsUnspecialized)
  4807. {
  4808. doConstReturn = true;
  4809. }
  4810. else if (((methodInstance->mComptimeFlags & BfComptimeFlag_OnlyFromComptime) != 0) && (!mModule->mIsComptimeModule))
  4811. {
  4812. // This either generated an error already or this is just the non-const type check pass for a comptime-only method
  4813. doConstReturn = true;
  4814. }
  4815. else if ((mBfEvalExprFlags & BfEvalExprFlags_DisallowComptime) != 0)
  4816. {
  4817. doConstReturn = true;
  4818. }
  4819. else if (((callFlags & BfCreateCallFlags_GenericParamThis) != 0) && (methodInstance->GetOwner()->IsInterface()))
  4820. {
  4821. mModule->Warn(0, "Concrete method may fail to comptime during specialization", targetSrc);
  4822. doConstReturn = true;
  4823. }
  4824. else if (methodDef->mIsVirtual)
  4825. {
  4826. // This could only really be the case for a Type, since no other 'this' could qualify as const
  4827. }
  4828. else
  4829. {
  4830. bool hasUndef = false;
  4831. for (auto arg : irArgs)
  4832. {
  4833. auto constant = mModule->mBfIRBuilder->GetConstant(arg);
  4834. if (constant == NULL)
  4835. continue;
  4836. if (constant->mConstType == BfConstType_Undef)
  4837. {
  4838. hasUndef = true;
  4839. break;
  4840. }
  4841. }
  4842. if (!hasUndef)
  4843. {
  4844. CeEvalFlags evalFlags = CeEvalFlags_None;
  4845. if ((mBfEvalExprFlags & BfEvalExprFlags_NoCeRebuildFlags) != 0)
  4846. evalFlags = (CeEvalFlags)(evalFlags | CeEvalFlags_NoRebuild);
  4847. auto constRet = mModule->mCompiler->mCEMachine->Call(targetSrc, mModule, methodInstance, irArgs, evalFlags, mExpectingType);
  4848. if (constRet)
  4849. {
  4850. auto constant = mModule->mBfIRBuilder->GetConstant(constRet.mValue);
  4851. BF_ASSERT(!constRet.mType->IsVar());
  4852. return constRet;
  4853. }
  4854. if (mModule->mCompiler->mFastFinish)
  4855. {
  4856. if ((mModule->mCurMethodInstance == NULL) || (!mModule->mCurMethodInstance->mIsAutocompleteMethod))
  4857. {
  4858. // We didn't properly resolve this so queue for a rebuild later
  4859. mModule->DeferRebuildType(mModule->mCurTypeInstance);
  4860. }
  4861. }
  4862. }
  4863. doConstReturn = true;
  4864. }
  4865. }
  4866. else if (mModule->mIsComptimeModule)
  4867. {
  4868. if (methodInstance->mIsUnspecialized)
  4869. {
  4870. doConstReturn = true;
  4871. }
  4872. else
  4873. {
  4874. mModule->mCompiler->mCEMachine->QueueMethod(methodInstance, func);
  4875. }
  4876. }
  4877. if (doConstReturn)
  4878. {
  4879. if ((returnType->IsVar()) && (mExpectingType != NULL))
  4880. returnType = mExpectingType;
  4881. if (returnType->IsRef())
  4882. {
  4883. return _GetDefaultReturnValue();
  4884. }
  4885. else
  4886. {
  4887. if (returnType->IsInstanceOf(mModule->mCompiler->mSpanTypeDef))
  4888. {
  4889. if ((mExpectingType != NULL) && (mExpectingType->IsUndefSizedArray()))
  4890. {
  4891. if (returnType->GetUnderlyingType() == mExpectingType->GetUnderlyingType())
  4892. return mModule->GetDefaultTypedValue(mExpectingType, true, BfDefaultValueKind_Undef);
  4893. }
  4894. }
  4895. return mModule->GetDefaultTypedValue(returnType, true, BfDefaultValueKind_Undef);
  4896. }
  4897. return _GetDefaultReturnValue();
  4898. }
  4899. }
  4900. if (!forceBind)
  4901. {
  4902. if (((!func) && (methodInstance->mIsUnspecialized)) || (mModule->mBfIRBuilder->mIgnoreWrites))
  4903. {
  4904. // We don't actually submit method calls for unspecialized methods
  4905. // - this includes all methods in unspecialized types
  4906. return _GetDefaultReturnValue();
  4907. }
  4908. }
  4909. if (methodInstance->mVirtualTableIdx != -1)
  4910. {
  4911. if ((!bypassVirtual) && (mDeferCallRef == NULL))
  4912. {
  4913. if ((methodDef->mIsOverride) && (mModule->mCurMethodInstance->mIsReified))
  4914. {
  4915. // Ensure that declaring method gets referenced
  4916. auto typeInstance = methodInstance->GetOwner();
  4917. auto& vEntry = typeInstance->mVirtualMethodTable[methodInstance->mVirtualTableIdx];
  4918. BfMethodInstance* declaringMethodInstance = vEntry.mDeclaringMethod;
  4919. if ((declaringMethodInstance->mMethodInstanceGroup->mOnDemandKind < BfMethodOnDemandKind_InWorkList) || (!declaringMethodInstance->mIsReified))
  4920. mModule->GetMethodInstance(declaringMethodInstance);
  4921. }
  4922. auto funcType = mModule->mBfIRBuilder->MapMethod(methodInstance);
  4923. auto funcPtrType1 = mModule->mBfIRBuilder->GetPointerTo(funcType);
  4924. auto funcPtrType2 = mModule->mBfIRBuilder->GetPointerTo(funcPtrType1);
  4925. auto funcPtrType3 = mModule->mBfIRBuilder->GetPointerTo(funcPtrType2);
  4926. auto funcPtrType4 = mModule->mBfIRBuilder->GetPointerTo(funcPtrType3);
  4927. if (methodInstance->mMethodInstanceGroup->mOwner->IsInterface())
  4928. {
  4929. if (mModule->mIsComptimeModule)
  4930. {
  4931. funcCallInst = mModule->mBfIRBuilder->Comptime_GetInterfaceFunc(irArgs[0], methodInstance->mMethodInstanceGroup->mOwner->mTypeId, methodInstance->mMethodDef->mIdx, funcPtrType1);
  4932. }
  4933. else
  4934. {
  4935. // IFace dispatch
  4936. auto ifaceTypeInst = methodInstance->mMethodInstanceGroup->mOwner;
  4937. BfIRValue slotOfs = mModule->GetInterfaceSlotNum(methodInstance->mMethodInstanceGroup->mOwner);
  4938. auto vDataPtrPtr = mModule->mBfIRBuilder->CreateBitCast(irArgs[0], funcPtrType4);
  4939. auto vDataPtr = mModule->FixClassVData(mModule->mBfIRBuilder->CreateLoad(vDataPtrPtr/*, "vtable"*/));
  4940. auto ifacePtrPtr = mModule->mBfIRBuilder->CreateInBoundsGEP(vDataPtr, slotOfs/*, "iface"*/);
  4941. auto ifacePtr = mModule->mBfIRBuilder->CreateLoad(ifacePtrPtr);
  4942. auto funcPtr = mModule->mBfIRBuilder->CreateInBoundsGEP(ifacePtr, methodInstance->mVirtualTableIdx/*, "vfn"*/);
  4943. funcCallInst = mModule->mBfIRBuilder->CreateLoad(funcPtr);
  4944. }
  4945. }
  4946. else if (mModule->mIsComptimeModule)
  4947. {
  4948. funcCallInst = mModule->mBfIRBuilder->Comptime_GetVirtualFunc(irArgs[0], methodInstance->mVirtualTableIdx, funcPtrType1);
  4949. }
  4950. else
  4951. {
  4952. mModule->HadSlotCountDependency();
  4953. // Virtual dispatch
  4954. // int vDataIdx = 0;
  4955. // vDataIdx += 1 + methodInstance->GetOwner()->GetDynCastVDataCount() + mModule->mCompiler->mMaxInterfaceSlots;
  4956. BfIRValue vDataPtr;
  4957. BfIRValue vDataIdx;
  4958. if ((mModule->mCompiler->mOptions.mHasVDataExtender) && (mModule->mCompiler->IsHotCompile()))
  4959. {
  4960. auto typeInst = methodInstance->mMethodInstanceGroup->mOwner;
  4961. int extMethodIdx = (methodInstance->mVirtualTableIdx - typeInst->GetImplBaseVTableSize()) - typeInst->GetOrigSelfVTableSize();
  4962. if (extMethodIdx >= 0)
  4963. {
  4964. BF_ASSERT(mModule->mCompiler->IsHotCompile());
  4965. // We have grown outside our original virtual table, Load the new vdataPtr from the mHasVDataExtender
  4966. // vDataPtr = obj.vtable.extension.entry[curVersion]
  4967. BfIRValue vDataPtrPtr = mModule->mBfIRBuilder->CreateBitCast(irArgs[0], funcPtrType4);
  4968. vDataPtr = mModule->FixClassVData(mModule->mBfIRBuilder->CreateLoad(vDataPtrPtr));
  4969. // The offset of the vExt is one past the base vtable. When a base class extends its virtual table, an entry
  4970. // for that new method is inserted in mVirtualMethodTable (thus increasing the index relative to GetBaseVTableSize()),
  4971. // but the actual written vtable position doesn't change, hence offsetting from GetOrigBaseVTableSize()
  4972. #ifdef _DEBUG
  4973. int vExtIdx = typeInst->GetImplBaseVTableSize();
  4974. BF_ASSERT(typeInst->mVirtualMethodTable[vExtIdx].mDeclaringMethod.mMethodNum == -1); // A type entry with a -1 mMethodNum means it's a vtable ext slot
  4975. #endif
  4976. int vExtOfs = typeInst->GetOrigImplBaseVTableSize();
  4977. vDataIdx = mModule->mBfIRBuilder->CreateConst(BfTypeCode_Int32, 1 + mModule->mCompiler->GetDynCastVDataCount() + mModule->mCompiler->mMaxInterfaceSlots);
  4978. vDataIdx = mModule->mBfIRBuilder->CreateAdd(vDataIdx, mModule->mBfIRBuilder->CreateConst(BfTypeCode_Int32, vExtOfs));
  4979. BfIRValue extendPtr = mModule->mBfIRBuilder->CreateInBoundsGEP(vDataPtr, vDataIdx);
  4980. vDataPtr = mModule->mBfIRBuilder->CreateLoad(extendPtr);
  4981. vDataIdx = mModule->mBfIRBuilder->CreateConst(BfTypeCode_Int32, extMethodIdx);
  4982. }
  4983. else
  4984. {
  4985. // Map this new virtual index back to the original index
  4986. //vDataIdx += (methodInstance->mVirtualTableIdx - typeInst->GetBaseVTableSize()) + typeInst->GetOrigBaseVTableSize();
  4987. //vDataIdx = mModule->mBfIRBuilder->CreateConst(BfTypeCode_Int32, 1 + methodInstance->GetOwner()->GetDynCastVDataCount() + mModule->mCompiler->mMaxInterfaceSlots);
  4988. vDataIdx = mModule->mBfIRBuilder->GetConfigConst(BfIRConfigConst_VirtualMethodOfs, BfTypeCode_Int32);
  4989. vDataIdx = mModule->mBfIRBuilder->CreateAdd(vDataIdx, mModule->mBfIRBuilder->CreateConst(BfTypeCode_Int32,
  4990. (methodInstance->mVirtualTableIdx - typeInst->GetImplBaseVTableSize()) + typeInst->GetOrigImplBaseVTableSize()));
  4991. }
  4992. }
  4993. else
  4994. {
  4995. //vDataIdx += methodInstance->mVirtualTableIdx;
  4996. //vDataIdx = mModule->mBfIRBuilder->CreateConst(BfTypeCode_Int32, 1 + methodInstance->GetOwner()->GetDynCastVDataCount() + mModule->mCompiler->mMaxInterfaceSlots);
  4997. vDataIdx = mModule->mBfIRBuilder->GetConfigConst(BfIRConfigConst_VirtualMethodOfs, BfTypeCode_Int32);
  4998. vDataIdx = mModule->mBfIRBuilder->CreateAdd(vDataIdx, mModule->mBfIRBuilder->CreateConst(BfTypeCode_Int32, methodInstance->mVirtualTableIdx));
  4999. }
  5000. if (!vDataPtr)
  5001. {
  5002. BfIRValue vDataPtrPtr = mModule->mBfIRBuilder->CreateBitCast(irArgs[0], funcPtrType3);
  5003. vDataPtr = mModule->FixClassVData(mModule->mBfIRBuilder->CreateLoad(vDataPtrPtr/*, "vtable"*/));
  5004. }
  5005. auto funcPtr = mModule->mBfIRBuilder->CreateInBoundsGEP(vDataPtr, vDataIdx/*, "vfn"*/);
  5006. funcCallInst = mModule->mBfIRBuilder->CreateLoad(funcPtr);
  5007. }
  5008. }
  5009. }
  5010. else // non-virtual
  5011. {
  5012. if (methodInstance->GetOwner()->IsInterface())
  5013. {
  5014. // We're attempting to directly invoke a non-virtual interface method, this will happen during the unspecialized pass
  5015. // OR if we had an error and didn't find an implementing member in the actual target
  5016. if (!mModule->mCurMethodInstance->mIsUnspecialized)
  5017. mModule->AssertErrorState();
  5018. if (returnType->IsInterface())
  5019. returnType = mModule->CreateConcreteInterfaceType(returnType->ToTypeInstance());
  5020. return _GetDefaultReturnValue();
  5021. }
  5022. }
  5023. if (mFunctionBindResult != NULL)
  5024. {
  5025. mFunctionBindResult->mFunc = funcCallInst;
  5026. if (irArgs.size() != 0)
  5027. {
  5028. auto targetType = methodInstance->mMethodInstanceGroup->mOwner;
  5029. if ((targetType->IsValueType()) && (targetType->IsSplattable()) && (!methodDef->HasNoThisSplat()) && (!IsComptime()))
  5030. mFunctionBindResult->mTarget = BfTypedValue(irArgs[0], targetType, BfTypedValueKind_SplatHead);
  5031. else
  5032. mFunctionBindResult->mTarget = BfTypedValue(irArgs[0], targetType, targetType->IsComposite() ? BfTypedValueKind_Addr : BfTypedValueKind_Value);
  5033. }
  5034. else
  5035. {
  5036. mFunctionBindResult->mTarget = BfTypedValue();
  5037. }
  5038. return BfTypedValue();
  5039. }
  5040. if (methodInstance->mReturnType == NULL)
  5041. {
  5042. mModule->AssertErrorState();
  5043. return BfTypedValue();
  5044. }
  5045. if ((mModule->mCurMethodInstance != NULL) && (mModule->mCurMethodInstance->mIsUnspecialized))
  5046. {
  5047. // Don't actually do the call - our target may be a generic param
  5048. return _GetDefaultReturnValue();
  5049. }
  5050. if (mDeferCallRef != NULL)
  5051. {
  5052. mModule->AddDeferredCall(BfModuleMethodInstance(methodInstance, func), irArgs, mDeferScopeAlloc, mDeferCallRef);
  5053. //return _GetDefaultReturnValue();
  5054. return mModule->GetFakeTypedValue(returnType);
  5055. }
  5056. if (!funcCallInst)
  5057. {
  5058. if ((mModule->HasCompiledOutput()) || (mModule->mCompiler->mOptions.mExtraResolveChecks))
  5059. {
  5060. // This can happen either from an error, or from the resolver while doing Internals_Changed processing
  5061. mModule->AssertErrorState();
  5062. }
  5063. //return mModule->GetDefaultTypedValue(returnType,/*, true*/false, returnType->IsComposite());
  5064. return _GetDefaultReturnValue();
  5065. }
  5066. bool hasResult = !methodInstance->mReturnType->IsValuelessType();
  5067. BfIRValue firstArg;
  5068. if (irArgs.size() != 0)
  5069. firstArg = irArgs[0];
  5070. auto methodInstOwner = methodInstance->GetOwner();
  5071. auto expectCallingConvention = mModule->GetIRCallingConvention(methodInstance);
  5072. if ((methodInstOwner->IsFunction()) && (methodInstance->GetParamCount() > 0) && (methodInstance->GetParamName(0) == "this"))
  5073. {
  5074. auto paramType = methodInstance->GetParamType(0);
  5075. if (!paramType->IsValueType())
  5076. expectCallingConvention = BfIRCallingConv_ThisCall;
  5077. }
  5078. if ((methodInstance->mAlwaysInline) && (mModule->mCompiler->mOptions.mEmitLineInfo))
  5079. {
  5080. // Emit a NOP so we always have a "step over" point
  5081. mModule->EmitEnsureInstructionAt();
  5082. }
  5083. if (returnType->IsComposite())
  5084. mModule->mBfIRBuilder->PopulateType(returnType);
  5085. methodInstance->mMethodInstanceGroup->mHasEmittedReference = true;
  5086. BfIRValue callInst;
  5087. int callIRArgCount = (int)irArgs.size();
  5088. if (sret != NULL)
  5089. {
  5090. SizedArray<BfIRValue, 8> sretIRArgs;
  5091. int sretIdx = GetStructRetIdx(methodInstance);
  5092. int inIdx = 0;
  5093. for (int outIdx = 0; outIdx < irArgs.size() + 1; outIdx++)
  5094. {
  5095. if (outIdx == sretIdx)
  5096. {
  5097. sretIRArgs.Add(sret->mValue);
  5098. continue;
  5099. }
  5100. sretIRArgs.Add(irArgs[inIdx++]);
  5101. }
  5102. callInst = mModule->mBfIRBuilder->CreateCall(funcCallInst, sretIRArgs);
  5103. callIRArgCount++;
  5104. }
  5105. else
  5106. {
  5107. callInst = mModule->mBfIRBuilder->CreateCall(funcCallInst, irArgs);
  5108. if ((hasResult) && (!methodDef->mName.IsEmpty()) && (!methodInstance->mIsIntrinsic))
  5109. mModule->mBfIRBuilder->SetName(callInst, methodDef->mName);
  5110. }
  5111. if ((expectCallingConvention != BfIRCallingConv_CDecl) && (!methodInstance->mIsIntrinsic))
  5112. mModule->mBfIRBuilder->SetCallCallingConv(callInst, expectCallingConvention);
  5113. if ((methodDef->mIsNoReturn) && (!methodInstance->mIsIntrinsic))
  5114. mModule->mBfIRBuilder->Call_AddAttribute(callInst, -1, BfIRAttribute_NoReturn);
  5115. bool hadAttrs = false;
  5116. int paramIdx = 0;
  5117. bool doingThis = methodInstance->HasThis();
  5118. int argIdx = 0;
  5119. if (methodDef->mHasExplicitThis)
  5120. paramIdx++;
  5121. int paramCount = methodInstance->GetParamCount();
  5122. for ( ; argIdx < callIRArgCount ; )
  5123. {
  5124. if (methodInstance->mIsIntrinsic)
  5125. break;
  5126. if (argIdx == GetStructRetIdx(methodInstance))
  5127. {
  5128. mModule->mBfIRBuilder->Call_AddAttribute(callInst, argIdx + 1, BfIRAttribute_StructRet);
  5129. argIdx++;
  5130. continue;
  5131. }
  5132. auto _HandleParamType = [&] (BfType* paramType)
  5133. {
  5134. if (paramType->IsStruct())
  5135. {
  5136. if ((!doingThis) || (!methodDef->mIsMutating && methodInstance->AllowsSplatting(paramIdx)))
  5137. {
  5138. BfTypeCode loweredTypeCode = BfTypeCode_None;
  5139. BfTypeCode loweredTypeCode2 = BfTypeCode_None;
  5140. if (paramType->GetLoweredType(BfTypeUsage_Parameter, &loweredTypeCode, &loweredTypeCode2))
  5141. {
  5142. argIdx++;
  5143. if (loweredTypeCode2 != BfTypeCode_None)
  5144. argIdx++;
  5145. return; // Lowering never requires attributes
  5146. }
  5147. }
  5148. }
  5149. int addDeref = -1;
  5150. if (paramType->IsRef())
  5151. {
  5152. auto refType = (BfRefType*)paramType;
  5153. auto elementType = refType->mElementType;
  5154. mModule->PopulateType(elementType, BfPopulateType_Data);
  5155. addDeref = elementType->mSize;
  5156. if ((addDeref <= 0) && (!elementType->IsValuelessType()))
  5157. mModule->AssertErrorState();
  5158. }
  5159. if ((paramType->IsComposite()) && (!paramType->IsTypedPrimitive()))
  5160. {
  5161. if (mModule->mCompiler->mOptions.mAllowStructByVal)
  5162. {
  5163. //byval
  5164. }
  5165. else
  5166. {
  5167. mModule->PopulateType(paramType, BfPopulateType_Data);
  5168. auto typeInst = paramType->ToTypeInstance();
  5169. if ((typeInst != NULL) && (typeInst->mIsCRepr) && (typeInst->IsSplattable()) && (!IsComptime()))
  5170. {
  5171. // We're splatting
  5172. }
  5173. else
  5174. {
  5175. if (doingThis)
  5176. {
  5177. mModule->mBfIRBuilder->Call_AddAttribute(callInst, argIdx + 1, BfIRAttribute_NoCapture);
  5178. addDeref = paramType->mSize;
  5179. }
  5180. else if (methodInstance->WantsStructsAttribByVal(paramType))
  5181. {
  5182. mModule->mBfIRBuilder->Call_AddAttribute(callInst, argIdx + 1, BfIRAttribute_ByVal, mModule->mSystem->mPtrSize);
  5183. }
  5184. }
  5185. }
  5186. }
  5187. else if (paramType->IsPrimitiveType())
  5188. {
  5189. auto primType = (BfPrimitiveType*)paramType;
  5190. if ((primType->mTypeDef->mTypeCode == BfTypeCode_Boolean) && (!methodInstance->mIsIntrinsic))
  5191. mModule->mBfIRBuilder->Call_AddAttribute(callInst, argIdx + 1, BfIRAttribute_ZExt);
  5192. }
  5193. if (addDeref >= 0)
  5194. {
  5195. mModule->mBfIRBuilder->Call_AddAttribute(callInst, argIdx + 1, BfIRAttribute_Dereferencable, addDeref);
  5196. }
  5197. argIdx++;
  5198. };
  5199. BfType* paramType = NULL;
  5200. if (doingThis)
  5201. {
  5202. int thisIdx = methodInstance->GetThisIdx();
  5203. paramType = methodInstance->GetThisType();
  5204. if (paramType->IsValuelessType())
  5205. {
  5206. doingThis = false;
  5207. continue;
  5208. }
  5209. bool isSplatted = methodInstance->GetParamIsSplat(thisIdx) && (!IsComptime()); // (resolvedTypeRef->IsSplattable()) && (!methodDef->mIsMutating);
  5210. if (isSplatted)
  5211. {
  5212. BfTypeUtils::SplatIterate(_HandleParamType, paramType);
  5213. doingThis = false;
  5214. continue;
  5215. }
  5216. else
  5217. _HandleParamType(paramType);
  5218. }
  5219. else
  5220. {
  5221. if (paramIdx >= methodInstance->GetParamCount())
  5222. break;
  5223. paramType = methodInstance->GetParamType(paramIdx);
  5224. BfTypeCode loweredTypeCode = BfTypeCode_None;
  5225. BfTypeCode loweredTypeCode2 = BfTypeCode_None;
  5226. if (paramType->GetLoweredType(BfTypeUsage_Parameter, &loweredTypeCode, &loweredTypeCode2))
  5227. {
  5228. argIdx++;
  5229. paramIdx++;
  5230. if (loweredTypeCode2 != BfTypeCode_None)
  5231. argIdx++;
  5232. continue;
  5233. }
  5234. if ((paramType->IsValuelessType()) && (!paramType->IsMethodRef()))
  5235. {
  5236. paramIdx++;
  5237. continue;
  5238. }
  5239. if ((methodInstance->GetParamIsSplat(paramIdx)) && (!IsComptime()))
  5240. {
  5241. BfTypeUtils::SplatIterate(_HandleParamType, paramType);
  5242. paramIdx++;
  5243. continue;
  5244. }
  5245. else
  5246. _HandleParamType(methodInstance->GetParamType(paramIdx));
  5247. }
  5248. if (doingThis)
  5249. doingThis = false;
  5250. else
  5251. paramIdx++;
  5252. //argIdx++;
  5253. }
  5254. if ((callFlags & BfCreateCallFlags_TailCall) != 0)
  5255. mModule->mBfIRBuilder->SetTailCall(callInst);
  5256. if (methodDef->mIsNoReturn)
  5257. {
  5258. mModule->mBfIRBuilder->CreateUnreachable();
  5259. // For debuggability when looking back at stack trace
  5260. //mModule->ExtendLocalLifetimes(0);
  5261. if (mModule->IsTargetingBeefBackend())
  5262. {
  5263. auto checkScope = mModule->mCurMethodState->mCurScope;
  5264. while (checkScope != NULL)
  5265. {
  5266. mModule->EmitLifetimeEnds(checkScope);
  5267. checkScope = checkScope->mPrevScope;
  5268. }
  5269. // This 'fake' branch extends lifetimes of outer variable scopes
  5270. if (mModule->mCurMethodState->mIRExitBlock)
  5271. mModule->mBfIRBuilder->CreateBr_Fake(mModule->mCurMethodState->mIRExitBlock);
  5272. }
  5273. }
  5274. else
  5275. {
  5276. if (mModule->mCurMethodState != NULL)
  5277. mModule->mCurMethodState->mMayNeedThisAccessCheck = true;
  5278. }
  5279. BfTypedValue result;
  5280. if (sret != NULL)
  5281. result = *sret;
  5282. else if (hasResult)
  5283. {
  5284. BfTypeCode loweredRetType = BfTypeCode_None;
  5285. BfTypeCode loweredRetType2 = BfTypeCode_None;
  5286. if ((!IsComptime()) && (methodInstance->GetLoweredReturnType(&loweredRetType, &loweredRetType2)))
  5287. {
  5288. auto retVal = mModule->CreateAlloca(methodInstance->mReturnType);
  5289. BfIRType loweredIRType = mModule->GetIRLoweredType(loweredRetType, loweredRetType2);
  5290. loweredIRType = mModule->mBfIRBuilder->GetPointerTo(loweredIRType);
  5291. auto castedRetVal = mModule->mBfIRBuilder->CreateBitCast(retVal, loweredIRType);
  5292. mModule->mBfIRBuilder->CreateStore(callInst, castedRetVal);
  5293. result = BfTypedValue(retVal, methodInstance->mReturnType, BfTypedValueKind_RestrictedTempAddr);
  5294. }
  5295. else
  5296. result = BfTypedValue(callInst, methodInstance->mReturnType);
  5297. }
  5298. else
  5299. result = mModule->GetFakeTypedValue(methodInstance->mReturnType);
  5300. if (result.mType->IsRef())
  5301. {
  5302. result = mModule->RemoveRef(result);
  5303. if (methodDef->mIsReadOnly)
  5304. {
  5305. if (result.mKind == BfTypedValueKind_Addr)
  5306. result.mKind = BfTypedValueKind_ReadOnlyAddr;
  5307. }
  5308. }
  5309. return result;
  5310. }
  5311. BfTypedValue BfExprEvaluator::CreateCall(BfMethodMatcher* methodMatcher, BfTypedValue target)
  5312. {
  5313. auto& moduleMethodInstance = methodMatcher->mBestMethodInstance;
  5314. if (!moduleMethodInstance)
  5315. moduleMethodInstance = GetSelectedMethod(methodMatcher->mTargetSrc, methodMatcher->mBestMethodTypeInstance, methodMatcher->mBestMethodDef, *methodMatcher);
  5316. if (moduleMethodInstance.mMethodInstance == NULL)
  5317. return BfTypedValue();
  5318. if ((target) && (target.mType != moduleMethodInstance.mMethodInstance->GetOwner()))
  5319. {
  5320. auto castedTarget = mModule->Cast(methodMatcher->mTargetSrc, target, moduleMethodInstance.mMethodInstance->GetOwner());
  5321. BF_ASSERT(castedTarget);
  5322. target = castedTarget;
  5323. }
  5324. PerformCallChecks(moduleMethodInstance.mMethodInstance, methodMatcher->mTargetSrc);
  5325. BfCreateCallFlags callFlags = BfCreateCallFlags_None;
  5326. if (methodMatcher->mAllowImplicitRef)
  5327. callFlags = (BfCreateCallFlags)(callFlags | BfCreateCallFlags_AllowImplicitRef);
  5328. return CreateCall(methodMatcher->mTargetSrc, target, BfTypedValue(), methodMatcher->mBestMethodDef, moduleMethodInstance, callFlags, methodMatcher->mArguments);
  5329. }
  5330. void BfExprEvaluator::MakeBaseConcrete(BfTypedValue& typedValue)
  5331. {
  5332. if (typedValue.IsBase())
  5333. {
  5334. auto baseType = mModule->mCurTypeInstance->mBaseType;
  5335. if (baseType == NULL)
  5336. baseType = mModule->mContext->mBfObjectType;
  5337. mModule->PopulateType(baseType, BfPopulateType_Data);
  5338. typedValue = mModule->Cast(NULL, typedValue, baseType, BfCastFlags_Explicit);
  5339. }
  5340. }
  5341. void BfExprEvaluator::SplatArgs(BfTypedValue value, SizedArrayImpl<BfIRValue>& irArgs)
  5342. {
  5343. if (value.IsSplat())
  5344. {
  5345. int componentIdx = 0;
  5346. BfTypeUtils::SplatIterate([&](BfType* checkType) { irArgs.push_back(mModule->ExtractSplatValue(value, componentIdx++, checkType)); }, value.mType);
  5347. return;
  5348. }
  5349. mModule->mBfIRBuilder->PopulateType(value.mType);
  5350. std::function<void(BfTypedValue)> checkTypeLambda = [&](BfTypedValue curValue)
  5351. {
  5352. BfType* checkType = curValue.mType;
  5353. if (checkType->IsStruct())
  5354. {
  5355. auto checkTypeInstance = checkType->ToTypeInstance();
  5356. if ((checkTypeInstance->mBaseType != NULL) && (!checkTypeInstance->mBaseType->IsValuelessType()))
  5357. {
  5358. BfTypedValue baseValue;
  5359. if (curValue.IsAddr())
  5360. baseValue = BfTypedValue((!curValue.mValue) ? BfIRValue() : mModule->mBfIRBuilder->CreateInBoundsGEP(curValue.mValue, 0, 0), checkTypeInstance->mBaseType, true);
  5361. else
  5362. baseValue = BfTypedValue((!curValue.mValue) ? BfIRValue() : mModule->mBfIRBuilder->CreateExtractValue(curValue.mValue, 0), checkTypeInstance->mBaseType);
  5363. checkTypeLambda(baseValue);
  5364. }
  5365. if (checkTypeInstance->mIsUnion)
  5366. {
  5367. auto unionInnerType = checkTypeInstance->GetUnionInnerType();
  5368. if (!unionInnerType->IsValuelessType())
  5369. {
  5370. BfTypedValue unionValue = mModule->ExtractValue(curValue, NULL, 1);
  5371. checkTypeLambda(unionValue);
  5372. }
  5373. if (checkTypeInstance->IsEnum())
  5374. {
  5375. BfTypedValue dscrValue = mModule->ExtractValue(curValue, NULL, 2);
  5376. checkTypeLambda(dscrValue);
  5377. }
  5378. }
  5379. else
  5380. {
  5381. for (int fieldIdx = 0; fieldIdx < (int)checkTypeInstance->mFieldInstances.size(); fieldIdx++)
  5382. {
  5383. auto fieldInstance = (BfFieldInstance*)&checkTypeInstance->mFieldInstances[fieldIdx];
  5384. if (fieldInstance->mDataIdx >= 0)
  5385. {
  5386. BfTypedValue fieldValue = mModule->ExtractValue(curValue, fieldInstance, fieldInstance->mDataIdx);
  5387. checkTypeLambda(fieldValue);
  5388. }
  5389. }
  5390. }
  5391. }
  5392. else if (checkType->IsMethodRef())
  5393. {
  5394. BF_ASSERT(curValue.IsAddr());
  5395. BfMethodRefType* methodRefType = (BfMethodRefType*)checkType;
  5396. for (int dataIdx = 0; dataIdx < methodRefType->GetCaptureDataCount(); dataIdx++)
  5397. {
  5398. auto checkType = methodRefType->GetCaptureType(dataIdx);
  5399. if (methodRefType->WantsDataPassedAsSplat(dataIdx))
  5400. {
  5401. BF_ASSERT(dataIdx == 0);
  5402. auto ptrType = mModule->CreatePointerType(checkType);
  5403. auto elemPtr = mModule->mBfIRBuilder->CreateBitCast(curValue.mValue, mModule->mBfIRBuilder->MapType(ptrType));
  5404. checkTypeLambda(BfTypedValue(elemPtr, checkType, BfTypedValueKind_Addr));
  5405. //BfTypedValue fieldValue = mModule->ExtractValue(curValue, fieldInstance, fieldInstance->mDataIdx);
  5406. //checkTypeLambda(fieldValue);
  5407. }
  5408. else
  5409. {
  5410. auto elemVal = mModule->mBfIRBuilder->CreateInBoundsGEP(curValue.mValue, 0, dataIdx);
  5411. if (!checkType->IsComposite())
  5412. elemVal = mModule->mBfIRBuilder->CreateLoad(elemVal);
  5413. irArgs.Add(elemVal);
  5414. //irArgs.Add(mModule->ExtractValue(curValue, dataIdx));
  5415. }
  5416. }
  5417. }
  5418. else if (!checkType->IsValuelessType())
  5419. {
  5420. auto loadedVal = mModule->LoadValue(curValue);
  5421. loadedVal = mModule->PrepareConst(loadedVal);
  5422. irArgs.push_back(loadedVal.mValue);
  5423. }
  5424. };
  5425. checkTypeLambda(value);
  5426. }
  5427. void BfExprEvaluator::PushArg(BfTypedValue argVal, SizedArrayImpl<BfIRValue>& irArgs, bool disableSplat, bool disableLowering, bool isIntrinsic)
  5428. {
  5429. MakeBaseConcrete(argVal);
  5430. if (argVal.mType->IsVar())
  5431. {
  5432. argVal = mModule->GetDefaultTypedValue(mModule->mContext->mBfObjectType);
  5433. }
  5434. if (argVal.mType->IsValuelessType())
  5435. return;
  5436. bool wantSplat = false;
  5437. if ((argVal.mType->IsSplattable()) && (!disableSplat) && (!IsComptime()))
  5438. {
  5439. disableLowering = true;
  5440. auto argTypeInstance = argVal.mType->ToTypeInstance();
  5441. if (!disableSplat)
  5442. {
  5443. if ((argTypeInstance != NULL) && (argTypeInstance->mIsCRepr))
  5444. wantSplat = true;
  5445. else if ((int)irArgs.size() + argVal.mType->GetSplatCount() <= mModule->mCompiler->mOptions.mMaxSplatRegs)
  5446. wantSplat = true;
  5447. }
  5448. }
  5449. if (wantSplat)
  5450. {
  5451. SplatArgs(argVal, irArgs);
  5452. }
  5453. else
  5454. {
  5455. if (argVal.mType->IsComposite())
  5456. {
  5457. if ((mBfEvalExprFlags & BfEvalExprFlags_Comptime) != 0)
  5458. {
  5459. // Const eval entry - we want any incoming consts as they are
  5460. }
  5461. else if (isIntrinsic)
  5462. {
  5463. // We can handle composites either by value or not
  5464. }
  5465. else
  5466. argVal = mModule->MakeAddressable(argVal);
  5467. if ((!IsComptime()) && (!disableLowering) && (!isIntrinsic))
  5468. {
  5469. BfTypeCode loweredTypeCode = BfTypeCode_None;
  5470. BfTypeCode loweredTypeCode2 = BfTypeCode_None;
  5471. if (argVal.mType->GetLoweredType(BfTypeUsage_Parameter, &loweredTypeCode, &loweredTypeCode2))
  5472. {
  5473. auto primType = mModule->mBfIRBuilder->GetPrimitiveType(loweredTypeCode);
  5474. auto ptrType = mModule->mBfIRBuilder->GetPointerTo(primType);
  5475. BfIRValue primPtrVal = mModule->mBfIRBuilder->CreateBitCast(argVal.mValue, ptrType);
  5476. auto primVal = mModule->mBfIRBuilder->CreateLoad(primPtrVal);
  5477. irArgs.push_back(primVal);
  5478. if (loweredTypeCode2 != BfTypeCode_None)
  5479. {
  5480. auto primType2 = mModule->mBfIRBuilder->GetPrimitiveType(loweredTypeCode2);
  5481. auto ptrType2 = mModule->mBfIRBuilder->GetPointerTo(primType2);
  5482. BfIRValue primPtrVal2;
  5483. if (mModule->mBfIRBuilder->GetSize(loweredTypeCode) < mModule->mBfIRBuilder->GetSize(loweredTypeCode2))
  5484. primPtrVal2 = mModule->mBfIRBuilder->CreateInBoundsGEP(mModule->mBfIRBuilder->CreateBitCast(primPtrVal, ptrType2), 1);
  5485. else
  5486. primPtrVal2 = mModule->mBfIRBuilder->CreateBitCast(mModule->mBfIRBuilder->CreateInBoundsGEP(primPtrVal, 1), ptrType2);
  5487. auto primVal2 = mModule->mBfIRBuilder->CreateLoad(primPtrVal2);
  5488. irArgs.push_back(primVal2);
  5489. }
  5490. return;
  5491. }
  5492. }
  5493. }
  5494. else
  5495. argVal = mModule->LoadValue(argVal);
  5496. irArgs.push_back(argVal.mValue);
  5497. }
  5498. }
  5499. void BfExprEvaluator::PushThis(BfAstNode* targetSrc, BfTypedValue argVal, BfMethodInstance* methodInstance, SizedArrayImpl<BfIRValue>& irArgs, bool skipMutCheck)
  5500. {
  5501. MakeBaseConcrete(argVal);
  5502. auto methodDef = methodInstance->mMethodDef;
  5503. if (methodInstance->IsSkipCall())
  5504. return;
  5505. if (!argVal)
  5506. {
  5507. //BF_ASSERT(mFunctionBindResult != NULL);
  5508. return;
  5509. }
  5510. if (methodDef->mIsMutating)
  5511. {
  5512. bool checkMut = false;
  5513. if (argVal.mType->IsGenericParam())
  5514. {
  5515. // For capturing mutability
  5516. if (mResultLocalVar != NULL)
  5517. mResultLocalVar->mWrittenToId = mModule->mCurMethodState->GetRootMethodState()->mCurAccessId++;
  5518. }
  5519. if (((argVal.mType->IsComposite()) || (argVal.mType->IsTypedPrimitive())))
  5520. {
  5521. if ((argVal.IsReadOnly()) || (!argVal.IsAddr()))
  5522. {
  5523. if (!skipMutCheck)
  5524. {
  5525. String err = StrFormat("call mutating method '%s' on", mModule->MethodToString(methodInstance).c_str());
  5526. CheckModifyResult(argVal, targetSrc, err.c_str());
  5527. }
  5528. if (argVal.IsSplat())
  5529. {
  5530. argVal = mModule->AggregateSplat(argVal);
  5531. argVal = mModule->MakeAddressable(argVal);
  5532. }
  5533. }
  5534. else
  5535. {
  5536. if (mResultLocalVar != NULL)
  5537. {
  5538. // When we are capturing, we need to note that we require capturing by reference here
  5539. mResultLocalVar->mWrittenToId = mModule->mCurMethodState->GetRootMethodState()->mCurAccessId++;
  5540. }
  5541. }
  5542. }
  5543. }
  5544. if (argVal.mType->IsValuelessType())
  5545. return;
  5546. auto owner = methodInstance->GetOwner();
  5547. bool allowThisSplatting;
  5548. if (mModule->mIsComptimeModule)
  5549. allowThisSplatting = owner->IsTypedPrimitive() || owner->IsValuelessType();
  5550. else
  5551. allowThisSplatting = methodInstance->AllowsSplatting(-1);
  5552. if ((!allowThisSplatting) || (methodDef->mIsMutating))
  5553. {
  5554. argVal = mModule->MakeAddressable(argVal);
  5555. irArgs.push_back(argVal.mValue);
  5556. return;
  5557. }
  5558. auto thisType = methodInstance->GetThisType();
  5559. PushArg(argVal, irArgs, !methodInstance->AllowsSplatting(-1), thisType->IsPointer());
  5560. }
  5561. void BfExprEvaluator::FinishDeferredEvals(SizedArrayImpl<BfResolvedArg>& argValues)
  5562. {
  5563. for (int argIdx = 0; argIdx < argValues.size(); argIdx++)
  5564. {
  5565. auto& argValue = argValues[argIdx].mTypedValue;
  5566. if ((argValues[argIdx].mArgFlags & (BfArgFlag_DelegateBindAttempt | BfArgFlag_LambdaBindAttempt | BfArgFlag_UnqualifiedDotAttempt | BfArgFlag_DeferredEval)) != 0)
  5567. {
  5568. if (!argValue)
  5569. {
  5570. auto expr = BfNodeDynCast<BfExpression>(argValues[argIdx].mExpression);
  5571. if (expr != NULL)
  5572. argValue = mModule->CreateValueFromExpression(expr);
  5573. }
  5574. }
  5575. }
  5576. }
  5577. void BfExprEvaluator::FinishDeferredEvals(BfResolvedArgs& argValues)
  5578. {
  5579. for (int argIdx = 0; argIdx < (int)argValues.mResolvedArgs.size(); argIdx++)
  5580. {
  5581. auto& argValue = argValues.mResolvedArgs[argIdx].mTypedValue;
  5582. if ((argValues.mResolvedArgs[argIdx].mArgFlags & (BfArgFlag_VariableDeclaration)) != 0)
  5583. {
  5584. auto variableDeclaration = BfNodeDynCast<BfVariableDeclaration>((*argValues.mArguments)[argIdx]);
  5585. if ((variableDeclaration != NULL) && (variableDeclaration->mNameNode != NULL))
  5586. {
  5587. if (mModule->mCurMethodState == NULL)
  5588. {
  5589. mModule->Fail("Illegal local variable", variableDeclaration);
  5590. }
  5591. else
  5592. {
  5593. BfLocalVariable* localVar = new BfLocalVariable();
  5594. localVar->mName = variableDeclaration->mNameNode->ToString();
  5595. localVar->mResolvedType = mModule->GetPrimitiveType(BfTypeCode_Var);
  5596. localVar->mAddr = mModule->mBfIRBuilder->GetFakeVal();
  5597. localVar->mReadFromId = 0;
  5598. localVar->mWrittenToId = 0;
  5599. localVar->mAssignedKind = BfLocalVarAssignKind_Unconditional;
  5600. mModule->CheckVariableDef(localVar);
  5601. localVar->Init();
  5602. mModule->AddLocalVariableDef(localVar, true);
  5603. }
  5604. }
  5605. }
  5606. }
  5607. FinishDeferredEvals(argValues.mResolvedArgs);
  5608. }
  5609. void BfExprEvaluator::AddCallDependencies(BfMethodInstance* methodInstance)
  5610. {
  5611. if (methodInstance->mReturnType != NULL)
  5612. mModule->AddDependency(methodInstance->mReturnType, mModule->mCurTypeInstance, BfDependencyMap::DependencyFlag_LocalUsage);
  5613. for (int paramIdx = 0; paramIdx < methodInstance->GetParamCount(); paramIdx++)
  5614. {
  5615. auto paramType = methodInstance->GetParamType(paramIdx);
  5616. mModule->AddDependency(paramType, mModule->mCurTypeInstance, BfDependencyMap::DependencyFlag_LocalUsage);
  5617. }
  5618. if (methodInstance->mMethodInfoEx != NULL)
  5619. {
  5620. for (auto genericArg : methodInstance->mMethodInfoEx->mMethodGenericArguments)
  5621. {
  5622. if (genericArg->IsWrappableType())
  5623. genericArg = mModule->GetWrappedStructType(genericArg);
  5624. if (genericArg != NULL)
  5625. mModule->AddDependency(genericArg, mModule->mCurTypeInstance, BfDependencyMap::DependencyFlag_LocalUsage);
  5626. }
  5627. }
  5628. }
  5629. //TODO: delete argumentsZ
  5630. BfTypedValue BfExprEvaluator::CreateCall(BfAstNode* targetSrc, const BfTypedValue& inTarget, const BfTypedValue& origTarget, BfMethodDef* methodDef, BfModuleMethodInstance moduleMethodInstance, BfCreateCallFlags callFlags, SizedArrayImpl<BfResolvedArg>& argValues, BfTypedValue* argCascade)
  5631. {
  5632. bool bypassVirtual = (callFlags & BfCreateCallFlags_BypassVirtual) != 0;
  5633. bool skipThis = (callFlags & BfCreateCallFlags_SkipThis) != 0;;
  5634. static int sCallIdx = 0;
  5635. if (!mModule->mCompiler->mIsResolveOnly)
  5636. sCallIdx++;
  5637. int callIdx = sCallIdx;
  5638. if (callIdx == 0x000020F9)
  5639. {
  5640. NOP;
  5641. }
  5642. // Temporarily disable so we don't capture calls in params
  5643. SetAndRestoreValue<BfFunctionBindResult*> prevBindResult(mFunctionBindResult, NULL);
  5644. SetAndRestoreValue<bool> prevAllowVariableDeclarations;
  5645. if (mModule->mCurMethodState != NULL)
  5646. prevAllowVariableDeclarations.Init(mModule->mCurMethodState->mCurScope->mAllowVariableDeclarations, false);
  5647. BfMethodInstance* methodInstance = moduleMethodInstance.mMethodInstance;
  5648. SizedArray<BfIRValue, 4> irArgs;
  5649. if ((methodDef->mIsAbstract) && (bypassVirtual))
  5650. {
  5651. mModule->Fail(StrFormat("Abstract base method '%s' cannot be invoked", mModule->MethodToString(methodInstance).c_str()), targetSrc);
  5652. }
  5653. bool isSkipCall = moduleMethodInstance.mMethodInstance->IsSkipCall(bypassVirtual);
  5654. BfType* returnType = methodInstance->mReturnType;
  5655. /*if (returnType->IsSelf())
  5656. {
  5657. returnType = methodInstance->GetOwner();
  5658. BF_ASSERT(returnType->IsInterface());
  5659. }*/
  5660. Array<BfTypedValue> argCascades;
  5661. BfTypedValue target = inTarget;
  5662. if (!skipThis)
  5663. {
  5664. if ((target) && (target.mType->IsFunction()) && (methodInstance->GetOwner() == target.mType))
  5665. {
  5666. CheckResultForReading(target);
  5667. target = mModule->LoadValue(target);
  5668. auto funcType = mModule->mBfIRBuilder->MapMethod(moduleMethodInstance.mMethodInstance);
  5669. auto funcPtrType = mModule->mBfIRBuilder->GetPointerTo(funcType);
  5670. moduleMethodInstance.mFunc = mModule->mBfIRBuilder->CreateIntToPtr(target.mValue, funcPtrType);
  5671. }
  5672. else if (!methodDef->mIsStatic)
  5673. {
  5674. if ((!target) && (prevBindResult.mPrevVal != NULL))
  5675. {
  5676. auto bindResult = prevBindResult.mPrevVal;
  5677. if (bindResult->mBindType != NULL)
  5678. {
  5679. // Allow binding a function to a 'this' type even if no target is specified
  5680. auto delegateInfo = bindResult->mBindType->GetDelegateInfo();
  5681. if (delegateInfo != NULL)
  5682. {
  5683. if (delegateInfo->mHasExplicitThis)
  5684. {
  5685. target = mModule->GetDefaultTypedValue(delegateInfo->mParams[0], false, BfDefaultValueKind_Addr);
  5686. bypassVirtual = true;
  5687. }
  5688. }
  5689. else if (bindResult->mBindType->IsFunction())
  5690. {
  5691. BfMethodInstance* invokeMethodInstance = mModule->GetRawMethodInstanceAtIdx(bindResult->mBindType->ToTypeInstance(), 0, "Invoke");
  5692. if (!invokeMethodInstance->mMethodDef->mIsStatic)
  5693. {
  5694. target = mModule->GetDefaultTypedValue(invokeMethodInstance->GetThisType(), false, BfDefaultValueKind_Addr);
  5695. }
  5696. }
  5697. }
  5698. }
  5699. if (!target)
  5700. {
  5701. FinishDeferredEvals(argValues);
  5702. auto error = mModule->Fail(StrFormat("An instance reference is required to %s the non-static method '%s'",
  5703. (prevBindResult.mPrevVal != NULL) ? "bind" : "invoke",
  5704. mModule->MethodToString(methodInstance).c_str()), targetSrc);
  5705. if ((error != NULL) && (methodInstance->mMethodDef->GetRefNode() != NULL))
  5706. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("See method declaration"), methodInstance->mMethodDef->GetRefNode());
  5707. return mModule->GetDefaultTypedValue(returnType);
  5708. }
  5709. auto prevResult = mResult;
  5710. mResult = target;
  5711. CheckResultForReading(mResult);
  5712. mResult = prevResult;
  5713. if (methodDef->mMethodType != BfMethodType_Ctor)
  5714. {
  5715. bool doAccessCheck = true;
  5716. if (target.IsThis())
  5717. {
  5718. if (!mModule->mCurMethodState->mMayNeedThisAccessCheck)
  5719. doAccessCheck = false;
  5720. }
  5721. if ((mModule->mAttributeState != NULL) && (mModule->mAttributeState->mCustomAttributes != NULL) && (mModule->mAttributeState->mCustomAttributes->Contains(mModule->mCompiler->mDisableObjectAccessChecksAttributeTypeDef)))
  5722. doAccessCheck = false;
  5723. if ((doAccessCheck) && (!isSkipCall) && (prevBindResult.mPrevVal == NULL))
  5724. mModule->EmitObjectAccessCheck(target);
  5725. }
  5726. if (((prevBindResult.mPrevVal == NULL) || (!prevBindResult.mPrevVal->mSkipThis)) &&
  5727. (!isSkipCall))
  5728. {
  5729. bool skipMutCheck = false;
  5730. if ((prevBindResult.mPrevVal != NULL) && (prevBindResult.mPrevVal->mSkipMutCheck))
  5731. {
  5732. // If we are binding a delegate, then we will end up making a copy of the target anyway
  5733. // so we don't need to do a mutability check
  5734. skipMutCheck = true;
  5735. }
  5736. if (methodDef->mMethodType == BfMethodType_Extension)
  5737. PushArg(target, irArgs);
  5738. else
  5739. PushThis(targetSrc, target, moduleMethodInstance.mMethodInstance, irArgs, skipMutCheck);
  5740. }
  5741. }
  5742. else if (methodDef->mMethodType == BfMethodType_Extension)
  5743. {
  5744. // Handled in args
  5745. }
  5746. else
  5747. {
  5748. mModule->CheckStaticAccess(methodInstance->mMethodInstanceGroup->mOwner);
  5749. if (target)
  5750. {
  5751. FinishDeferredEvals(argValues);
  5752. mModule->Fail(StrFormat("Method '%s' cannot be accessed with an instance reference; qualify it with a type name instead",
  5753. mModule->MethodToString(methodInstance).c_str()), targetSrc);
  5754. return mModule->GetDefaultTypedValue(returnType);
  5755. }
  5756. }
  5757. }
  5758. if (isSkipCall)
  5759. {
  5760. FinishDeferredEvals(argValues);
  5761. mModule->EmitEnsureInstructionAt();
  5762. return mModule->GetDefaultTypedValue(returnType);
  5763. }
  5764. int argIdx = 0;
  5765. int paramIdx = 0;
  5766. BfIRValue expandedParamAlloca;
  5767. BfTypedValue expandedParamsArray;
  5768. BfType* expandedParamsElementType = NULL;
  5769. int extendedParamIdx = 0;
  5770. AddCallDependencies(methodInstance);
  5771. bool wasCapturingMatchInfo = false;
  5772. auto autoComplete = GetAutoComplete();
  5773. if (autoComplete != NULL)
  5774. {
  5775. // Set to false to make sure we don't capture method match info from 'params' array creation
  5776. wasCapturingMatchInfo = autoComplete->mIsCapturingMethodMatchInfo;
  5777. autoComplete->mIsCapturingMethodMatchInfo = false;
  5778. }
  5779. defer(
  5780. {
  5781. if (autoComplete != NULL)
  5782. autoComplete->mIsCapturingMethodMatchInfo = wasCapturingMatchInfo;
  5783. });
  5784. BfScopeData* boxScopeData = mDeferScopeAlloc;
  5785. if ((boxScopeData == NULL) && (mModule->mCurMethodState != NULL))
  5786. boxScopeData = mModule->mCurMethodState->mCurScope;
  5787. bool failed = false;
  5788. while (true)
  5789. {
  5790. int argExprIdx = argIdx;
  5791. if (methodDef->mMethodType == BfMethodType_Extension)
  5792. argExprIdx--;
  5793. bool isThis = (paramIdx == -1) || ((methodDef->mHasExplicitThis) && (paramIdx == 0));
  5794. bool isDirectPass = false;
  5795. if (paramIdx >= (int)methodInstance->GetParamCount())
  5796. {
  5797. if (methodInstance->IsVarArgs())
  5798. {
  5799. if (argExprIdx >= (int)argValues.size())
  5800. break;
  5801. BfTypedValue argValue = ResolveArgValue(argValues[argExprIdx], NULL);
  5802. if (argValue)
  5803. {
  5804. auto typeInst = argValue.mType->ToTypeInstance();
  5805. if (argValue.mType == mModule->GetPrimitiveType(BfTypeCode_Float))
  5806. argValue = mModule->Cast(argValues[argExprIdx].mExpression, argValue, mModule->GetPrimitiveType(BfTypeCode_Double));
  5807. if ((typeInst != NULL) && (typeInst->IsInstanceOf(mModule->mCompiler->mStringTypeDef)))
  5808. {
  5809. BfType* charType = mModule->GetPrimitiveType(BfTypeCode_Char8);
  5810. BfType* charPtrType = mModule->CreatePointerType(charType);
  5811. argValue = mModule->Cast(argValues[argExprIdx].mExpression, argValue, charPtrType);
  5812. }
  5813. PushArg(argValue, irArgs, true, false);
  5814. }
  5815. argIdx++;
  5816. continue;
  5817. }
  5818. if (argExprIdx < (int)argValues.size())
  5819. {
  5820. if (mModule->PreFail())
  5821. {
  5822. BfAstNode* errorRef = argValues[argExprIdx].mExpression;
  5823. if (errorRef == NULL)
  5824. errorRef = targetSrc;
  5825. BfError* error;
  5826. if ((argValues[argExprIdx].mArgFlags & BfArgFlag_StringInterpolateArg) != 0)
  5827. {
  5828. int checkIdx = argExprIdx - 1;
  5829. while (checkIdx >= 0)
  5830. {
  5831. if ((argValues[checkIdx].mArgFlags & BfArgFlag_StringInterpolateFormat) != 0)
  5832. {
  5833. errorRef = argValues[checkIdx].mExpression;
  5834. break;
  5835. }
  5836. checkIdx--;
  5837. }
  5838. error = mModule->Fail("Expanded string interpolation generates too many arguments. If string allocation was intended then consider adding a specifier such as 'scope'.", errorRef);
  5839. }
  5840. else if ((prevBindResult.mPrevVal != NULL) && (prevBindResult.mPrevVal->mBindType != NULL))
  5841. 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);
  5842. else
  5843. error = mModule->Fail(StrFormat("Too many arguments, expected %d fewer.", (int)argValues.size() - argExprIdx), errorRef);
  5844. if ((error != NULL) && (methodInstance->mMethodDef->mMethodDeclaration != NULL))
  5845. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("See method declaration"), methodInstance->mMethodDef->GetRefNode());
  5846. }
  5847. failed = true;
  5848. break;
  5849. }
  5850. break;
  5851. }
  5852. // Only create actual params if we're not just trying to bind the function
  5853. if ((prevBindResult.mPrevVal != NULL) && (!prevBindResult.mPrevVal->mWantsArgs))
  5854. break;
  5855. BfType* wantType = NULL;
  5856. bool wantsSplat = false;
  5857. if (expandedParamsElementType != NULL)
  5858. {
  5859. wantType = expandedParamsElementType;
  5860. }
  5861. else
  5862. {
  5863. wantsSplat = methodInstance->GetParamIsSplat(paramIdx) && (!IsComptime());
  5864. if (methodInstance->IsImplicitCapture(paramIdx))
  5865. {
  5866. auto paramType = methodInstance->GetParamType(paramIdx);
  5867. if (mModule->mCurMethodInstance->IsMixin())
  5868. {
  5869. // Don't bother, also- can fail on captures
  5870. }
  5871. else
  5872. {
  5873. // static int captureIdx = 0;
  5874. // captureIdx++;
  5875. // int curCaptureIdx = captureIdx;
  5876. //
  5877. // if (curCaptureIdx == 0x91)
  5878. // {
  5879. // NOP;
  5880. // }
  5881. auto lookupVal = DoImplicitArgCapture(targetSrc, methodInstance, paramIdx, failed, BfImplicitParamKind_General, origTarget);
  5882. if (lookupVal)
  5883. {
  5884. if (wantsSplat)
  5885. {
  5886. SplatArgs(lookupVal, irArgs);
  5887. }
  5888. else if (paramType->IsRef())
  5889. {
  5890. irArgs.push_back(lookupVal.mValue);
  5891. }
  5892. else
  5893. PushArg(lookupVal, irArgs, true);
  5894. }
  5895. }
  5896. paramIdx++;
  5897. continue;
  5898. }
  5899. wantType = methodInstance->GetParamType(paramIdx);
  5900. if (wantType->IsSelf())
  5901. wantType = methodInstance->GetOwner();
  5902. if (wantType->IsVar())
  5903. {
  5904. // Case happens when we can't find the argument type
  5905. failed = true;
  5906. }
  5907. BfParamKind paramKind = methodInstance->GetParamKind(paramIdx);
  5908. if (paramKind == BfParamKind_Params)
  5909. {
  5910. //TODO: Check to see if it's a direct array pass
  5911. if (argIdx < (int)argValues.size())
  5912. {
  5913. auto argValue = argValues[argIdx].mTypedValue;
  5914. if ((argValue.IsParams()) /*&& (mModule->CanCast(argValue, wantType))*/)
  5915. isDirectPass = true;
  5916. }
  5917. if (!isDirectPass)
  5918. {
  5919. int numElements = BF_MAX((int)argValues.size() - argIdx, 0);
  5920. if (methodDef->mMethodType == BfMethodType_Extension)
  5921. numElements++;
  5922. if (IsComptimeEntry())
  5923. {
  5924. if ((wantType->IsArray()) || (wantType->IsInstanceOf(mModule->mCompiler->mSpanTypeDef)))
  5925. {
  5926. auto genericTypeInst = wantType->ToGenericTypeInstance();
  5927. expandedParamsElementType = genericTypeInst->mGenericTypeInfo->mTypeGenericArguments[0];
  5928. auto irSizedArrayType = mModule->mBfIRBuilder->GetSizedArrayType(mModule->mBfIRBuilder->MapType(expandedParamsElementType), numElements);
  5929. Array<BfIRValue> values;
  5930. for (int i = 0; i < numElements; i++)
  5931. values.Add(mModule->mBfIRBuilder->GetFakeVal());
  5932. expandedParamsArray = BfTypedValue(mModule->mBfIRBuilder->CreateConstAgg(irSizedArrayType, values), wantType);
  5933. PushArg(expandedParamsArray, irArgs);
  5934. }
  5935. }
  5936. else if (wantType->IsArray())
  5937. {
  5938. BfArrayType* arrayType = (BfArrayType*)wantType;
  5939. mModule->PopulateType(arrayType, BfPopulateType_DataAndMethods);
  5940. expandedParamsElementType = arrayType->mGenericTypeInfo->mTypeGenericArguments[0];
  5941. int arrayClassSize = arrayType->mInstSize - expandedParamsElementType->mSize;
  5942. expandedParamsArray = BfTypedValue(mModule->AllocFromType(arrayType->GetUnderlyingType(), boxScopeData, BfIRValue(), mModule->GetConstValue(numElements), 1, BfAllocFlags_None),
  5943. arrayType, false);
  5944. BfResolvedArgs resolvedArgs;
  5945. MatchConstructor(targetSrc, NULL, expandedParamsArray, arrayType, resolvedArgs, false, false);
  5946. //TODO: Assert 'length' var is at slot 1
  5947. auto arrayBits = mModule->mBfIRBuilder->CreateBitCast(expandedParamsArray.mValue, mModule->mBfIRBuilder->MapType(arrayType->mBaseType));
  5948. int arrayLengthBitCount = arrayType->GetLengthBitCount();
  5949. if (arrayLengthBitCount == 0)
  5950. {
  5951. mModule->Fail("INTERNAL ERROR: Unable to find array 'length' field", targetSrc);
  5952. return BfTypedValue();
  5953. }
  5954. auto& fieldInstance = arrayType->mBaseType->mFieldInstances[0];
  5955. auto addr = mModule->mBfIRBuilder->CreateInBoundsGEP(arrayBits, 0, fieldInstance.mDataIdx);
  5956. if (arrayLengthBitCount == 64)
  5957. mModule->mBfIRBuilder->CreateAlignedStore(mModule->GetConstValue64(numElements), addr, 8);
  5958. else
  5959. mModule->mBfIRBuilder->CreateAlignedStore(mModule->GetConstValue32(numElements), addr, 4);
  5960. PushArg(expandedParamsArray, irArgs);
  5961. }
  5962. else if (wantType->IsInstanceOf(mModule->mCompiler->mSpanTypeDef))
  5963. {
  5964. auto genericTypeInst = wantType->ToGenericTypeInstance();
  5965. expandedParamsElementType = genericTypeInst->mGenericTypeInfo->mTypeGenericArguments[0];
  5966. expandedParamsArray = BfTypedValue(mModule->CreateAlloca(wantType), wantType, true);
  5967. expandedParamAlloca = mModule->CreateAlloca(genericTypeInst->mGenericTypeInfo->mTypeGenericArguments[0], true, NULL, mModule->GetConstValue(numElements));
  5968. mModule->mBfIRBuilder->CreateStore(expandedParamAlloca, mModule->mBfIRBuilder->CreateInBoundsGEP(expandedParamsArray.mValue, 0, 1));
  5969. mModule->mBfIRBuilder->CreateStore(mModule->GetConstValue(numElements), mModule->mBfIRBuilder->CreateInBoundsGEP(expandedParamsArray.mValue, 0, 2));
  5970. PushArg(expandedParamsArray, irArgs);
  5971. }
  5972. continue;
  5973. }
  5974. }
  5975. }
  5976. BfAstNode* arg = NULL;
  5977. bool hadMissingArg = false;
  5978. if (argExprIdx == -1)
  5979. arg = targetSrc;
  5980. if (argExprIdx >= 0)
  5981. {
  5982. if (argExprIdx < (int)argValues.size())
  5983. {
  5984. arg = argValues[argExprIdx].mExpression;
  5985. if (((argValues[argExprIdx].mArgFlags & BfArgFlag_StringInterpolateArg) != 0) && (!expandedParamsArray))
  5986. {
  5987. BfAstNode* errorRef = arg;
  5988. int checkIdx = argExprIdx - 1;
  5989. while (checkIdx >= 0)
  5990. {
  5991. if ((argValues[checkIdx].mArgFlags & BfArgFlag_StringInterpolateFormat) != 0)
  5992. {
  5993. errorRef = argValues[checkIdx].mExpression;
  5994. break;
  5995. }
  5996. checkIdx--;
  5997. }
  5998. 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);
  5999. }
  6000. if ((arg == NULL) && (argValues[argExprIdx].mExpression != NULL))
  6001. hadMissingArg = true;
  6002. }
  6003. else
  6004. hadMissingArg = true;
  6005. }
  6006. BfTypedValue argValue;
  6007. if (hadMissingArg)
  6008. {
  6009. if (expandedParamsArray)
  6010. break;
  6011. if ((argIdx >= (int) methodInstance->mDefaultValues.size()) || (!methodInstance->mDefaultValues[argIdx]))
  6012. {
  6013. BfAstNode* refNode = targetSrc;
  6014. if (argValues.size() > 0)
  6015. {
  6016. auto checkExpr = argValues.back().mExpression;
  6017. if (checkExpr != NULL)
  6018. refNode = checkExpr;
  6019. }
  6020. BfAstNode* prevNode = NULL;
  6021. if (targetSrc == NULL)
  6022. {
  6023. // We must be in BfModule::EmitCtorBody
  6024. }
  6025. else if (auto tupleExpr = BfNodeDynCastExact<BfTupleExpression>(targetSrc))
  6026. {
  6027. if (tupleExpr->mCommas.size() > 0)
  6028. prevNode = tupleExpr->mCommas.back();
  6029. else
  6030. prevNode = tupleExpr->mOpenParen;
  6031. if (tupleExpr->mCloseParen != NULL)
  6032. refNode = tupleExpr->mCloseParen;
  6033. }
  6034. else if (mModule->mParentNodeEntry != NULL)
  6035. {
  6036. if (auto objectCreateExpr = BfNodeDynCast<BfObjectCreateExpression>(mModule->mParentNodeEntry->mNode))
  6037. {
  6038. if (objectCreateExpr->mCommas.size() > 0)
  6039. prevNode = objectCreateExpr->mCommas.back();
  6040. else
  6041. prevNode = objectCreateExpr->mOpenToken;
  6042. if (objectCreateExpr->mCloseToken != NULL)
  6043. refNode = objectCreateExpr->mCloseToken;
  6044. if (auto newNode = BfNodeDynCast<BfNewNode>(objectCreateExpr->mNewNode))
  6045. {
  6046. if (newNode->mAllocNode == targetSrc)
  6047. refNode = targetSrc;
  6048. }
  6049. }
  6050. else if (auto invokeExpr = BfNodeDynCast<BfInvocationExpression>(mModule->mParentNodeEntry->mNode))
  6051. {
  6052. if (invokeExpr->mCommas.size() > 0)
  6053. prevNode = invokeExpr->mCommas.back();
  6054. else
  6055. prevNode = invokeExpr->mOpenParen;
  6056. if (invokeExpr->mCloseParen != NULL)
  6057. refNode = invokeExpr->mCloseParen;
  6058. }
  6059. }
  6060. if ((autoComplete != NULL) && (prevNode != NULL))
  6061. autoComplete->CheckEmptyStart(prevNode, wantType);
  6062. BfError* error = NULL;
  6063. if (mModule->mParentNodeEntry != NULL)
  6064. {
  6065. bool showCtorError = false;
  6066. if (auto ctorDeclaration = BfNodeDynCast<BfConstructorDeclaration>(mModule->mParentNodeEntry->mNode))
  6067. {
  6068. if (ctorDeclaration->mInitializer == NULL)
  6069. showCtorError = true;
  6070. }
  6071. if (auto typerDecl = BfNodeDynCast<BfTypeDeclaration>(mModule->mParentNodeEntry->mNode))
  6072. showCtorError = true;
  6073. if (showCtorError)
  6074. {
  6075. if (mModule->PreFail())
  6076. {
  6077. error = mModule->Fail(StrFormat("No parameterless constructor is available for base class. Consider calling base constructor '%s'.",
  6078. mModule->MethodToString(methodInstance).c_str()), refNode);
  6079. }
  6080. auto srcNode = mModule->mCurMethodInstance->mMethodDef->GetRefNode();
  6081. if ((autoComplete != NULL) && (autoComplete->CheckFixit(srcNode)))
  6082. autoComplete->FixitAddConstructor(mModule->mCurTypeInstance);
  6083. }
  6084. }
  6085. if (mModule->PreFail())
  6086. {
  6087. if (error == NULL)
  6088. error = mModule->Fail(StrFormat("Not enough parameters specified, expected %d more.", methodInstance->GetParamCount() - paramIdx), refNode);
  6089. if ((error != NULL) && (methodInstance->mMethodDef->mMethodDeclaration != NULL))
  6090. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("See method declaration"), methodInstance->mMethodDef->GetRefNode());
  6091. }
  6092. failed = true;
  6093. break;
  6094. }
  6095. auto foreignDefaultVal = methodInstance->mDefaultValues[argIdx];
  6096. auto foreignConst = methodInstance->GetOwner()->mConstHolder->GetConstant(foreignDefaultVal.mValue);
  6097. if (foreignConst->mConstType == BfConstType_AggZero)
  6098. {
  6099. // Allow this
  6100. }
  6101. else if (foreignConst->mTypeCode == BfTypeCode_NullPtr)
  6102. {
  6103. if (wantType->IsNullable())
  6104. {
  6105. argValue = mModule->GetDefaultTypedValue(wantType, false, BfDefaultValueKind_Addr);
  6106. }
  6107. }
  6108. else if (foreignConst->mConstType == BfConstType_GlobalVar)
  6109. {
  6110. auto globalVar = (BfGlobalVar*)foreignConst;
  6111. if (globalVar->mName[0] == '#')
  6112. {
  6113. if (strcmp(globalVar->mName, "#CallerLineNum") == 0)
  6114. {
  6115. argValue = BfTypedValue(mModule->GetConstValue(mModule->mCurFilePosition.mCurLine + 1), mModule->GetPrimitiveType(BfTypeCode_Int32));
  6116. }
  6117. else if (strcmp(globalVar->mName, "#CallerFilePath") == 0)
  6118. {
  6119. String filePath = "";
  6120. if (mModule->mCurFilePosition.mFileInstance != NULL)
  6121. filePath = mModule->mCurFilePosition.mFileInstance->mParser->mFileName;
  6122. argValue = BfTypedValue(mModule->GetStringObjectValue(filePath),
  6123. mModule->ResolveTypeDef(mModule->mCompiler->mStringTypeDef));
  6124. }
  6125. else if (strcmp(globalVar->mName, "#CallerFileName") == 0)
  6126. {
  6127. String filePath = "";
  6128. if (mModule->mCurFilePosition.mFileInstance != NULL)
  6129. filePath = mModule->mCurFilePosition.mFileInstance->mParser->mFileName;
  6130. argValue = BfTypedValue(mModule->GetStringObjectValue(GetFileName(filePath)),
  6131. mModule->ResolveTypeDef(mModule->mCompiler->mStringTypeDef));
  6132. }
  6133. else if (strcmp(globalVar->mName, "#CallerFileDir") == 0)
  6134. {
  6135. String filePath = "";
  6136. if (mModule->mCurFilePosition.mFileInstance != NULL)
  6137. filePath = mModule->mCurFilePosition.mFileInstance->mParser->mFileName;
  6138. argValue = BfTypedValue(mModule->GetStringObjectValue(GetFileDir(filePath)),
  6139. mModule->ResolveTypeDef(mModule->mCompiler->mStringTypeDef));
  6140. }
  6141. else if (strcmp(globalVar->mName, "#CallerTypeName") == 0)
  6142. {
  6143. String typeName = "";
  6144. if (mModule->mCurTypeInstance != NULL)
  6145. typeName = mModule->TypeToString(mModule->mCurTypeInstance);
  6146. argValue = BfTypedValue(mModule->GetStringObjectValue(typeName),
  6147. mModule->ResolveTypeDef(mModule->mCompiler->mStringTypeDef));
  6148. }
  6149. else if (strcmp(globalVar->mName, "#CallerType") == 0)
  6150. {
  6151. auto typeType = mModule->ResolveTypeDef(mModule->mCompiler->mTypeTypeDef);
  6152. BfType* type = mModule->mCurTypeInstance;
  6153. if (type != NULL)
  6154. {
  6155. mModule->AddDependency(type, mModule->mCurTypeInstance, BfDependencyMap::DependencyFlag_ExprTypeReference);
  6156. argValue = BfTypedValue(mModule->CreateTypeDataRef(type), typeType);
  6157. }
  6158. }
  6159. else if (strcmp(globalVar->mName, "#CallerMemberName") == 0)
  6160. {
  6161. String memberName = "";
  6162. if (mModule->mCurMethodInstance != NULL)
  6163. memberName = mModule->MethodToString(mModule->mCurMethodInstance);
  6164. argValue = BfTypedValue(mModule->GetStringObjectValue(memberName),
  6165. mModule->ResolveTypeDef(mModule->mCompiler->mStringTypeDef));
  6166. }
  6167. else if (strcmp(globalVar->mName, "#CallerProject") == 0)
  6168. {
  6169. String projectName = "";
  6170. if (mModule->mCurMethodInstance != NULL)
  6171. projectName = mModule->mCurMethodInstance->mMethodDef->mDeclaringType->mProject->mName;
  6172. argValue = BfTypedValue(mModule->GetStringObjectValue(projectName),
  6173. mModule->ResolveTypeDef(mModule->mCompiler->mStringTypeDef));
  6174. }
  6175. else if (strcmp(globalVar->mName, "#ProjectName") == 0)
  6176. {
  6177. String projectName = methodInstance->mMethodDef->mDeclaringType->mProject->mName;
  6178. argValue = BfTypedValue(mModule->GetStringObjectValue(projectName),
  6179. mModule->ResolveTypeDef(mModule->mCompiler->mStringTypeDef));
  6180. }
  6181. else
  6182. {
  6183. argValue = mModule->GetCompilerFieldValue(globalVar->mName);
  6184. }
  6185. }
  6186. }
  6187. else if (foreignConst->mConstType == BfConstType_GEP32_2)
  6188. {
  6189. auto constGep32_2 = (BfConstantGEP32_2*)foreignConst;
  6190. auto gepTarget = methodInstance->GetOwner()->mConstHolder->GetConstantById(constGep32_2->mTarget);
  6191. if (gepTarget->mConstType == BfConstType_GlobalVar)
  6192. {
  6193. auto globalVar = (BfGlobalVar*)gepTarget;
  6194. if (globalVar->mName[0] == '#')
  6195. {
  6196. if (strcmp(globalVar->mName, "#CallerExpression") == 0)
  6197. {
  6198. int exprIdx = constGep32_2->mIdx1;
  6199. if ((exprIdx >= 0) && (exprIdx < (int)argValues.size()))
  6200. {
  6201. auto expr = argValues[exprIdx].mExpression;
  6202. if (expr != NULL)
  6203. {
  6204. argValue = BfTypedValue(mModule->GetStringObjectValue(expr->ToString()),
  6205. mModule->ResolveTypeDef(mModule->mCompiler->mStringTypeDef));
  6206. }
  6207. }
  6208. else
  6209. {
  6210. mModule->Fail("CallerExpression index out of bounds", targetSrc);
  6211. argValue = BfTypedValue(mModule->GetStringObjectValue(""),
  6212. mModule->ResolveTypeDef(mModule->mCompiler->mStringTypeDef));
  6213. }
  6214. }
  6215. }
  6216. }
  6217. }
  6218. if (!argValue)
  6219. {
  6220. argValue = mModule->GetTypedValueFromConstant(foreignConst, methodInstance->GetOwner()->mConstHolder, foreignDefaultVal.mType);
  6221. if (!argValue)
  6222. mModule->Fail("Default parameter value failed", targetSrc);
  6223. mModule->mBfIRBuilder->PopulateType(foreignDefaultVal.mType);
  6224. }
  6225. }
  6226. else
  6227. {
  6228. if (argExprIdx == -1)
  6229. argValue = target;
  6230. else
  6231. argValue = argValues[argExprIdx].mTypedValue;
  6232. if ((argValue.IsParams()) && (!isDirectPass))
  6233. {
  6234. BfAstNode* refNode = arg;
  6235. if (auto unaryOperatorExpr = BfNodeDynCast<BfUnaryOperatorExpression>(refNode))
  6236. refNode = unaryOperatorExpr->mOpToken;
  6237. mModule->Warn(0, "Unused 'params' expression", refNode);
  6238. }
  6239. if (wantType->IsMethodRef())
  6240. {
  6241. auto expr = argValues[argExprIdx].mExpression;
  6242. if (expr != NULL)
  6243. SetMethodElementType(expr);
  6244. if (!argValue)
  6245. argValue = mModule->CreateValueFromExpression(BfNodeDynCast<BfExpression>(arg), wantType, (BfEvalExprFlags)((mBfEvalExprFlags & BfEvalExprFlags_InheritFlags) | BfEvalExprFlags_NoCast));
  6246. // Add any implicit captures now
  6247. auto methodRefType = (BfMethodRefType*)wantType;
  6248. BfMethodInstance* useMethodInstance = methodRefType->mMethodRef;
  6249. for (int dataIdx = 0; dataIdx < methodRefType->GetCaptureDataCount(); dataIdx++)
  6250. {
  6251. int paramIdx = methodRefType->GetParamIdxFromDataIdx(dataIdx);
  6252. auto lookupVal = DoImplicitArgCapture(arg, useMethodInstance, paramIdx, failed, BfImplicitParamKind_General, argValue);
  6253. if (lookupVal)
  6254. {
  6255. if (methodRefType->WantsDataPassedAsSplat(dataIdx))
  6256. SplatArgs(lookupVal, irArgs);
  6257. else
  6258. {
  6259. if (lookupVal.mType->IsComposite())
  6260. lookupVal = mModule->MakeAddressable(lookupVal, false);
  6261. irArgs.push_back(lookupVal.mValue);
  6262. }
  6263. }
  6264. }
  6265. paramIdx++;
  6266. argIdx++;
  6267. continue;
  6268. }
  6269. else if (argExprIdx >= 0)
  6270. {
  6271. BfParamKind paramKind = BfParamKind_Normal;
  6272. BfIdentifierNode* paramNameNode = NULL;
  6273. if (paramIdx < methodInstance->GetParamCount())
  6274. {
  6275. paramKind = methodInstance->GetParamKind(paramIdx);
  6276. paramNameNode = methodInstance->GetParamNameNode(paramIdx);
  6277. }
  6278. argValues[argExprIdx].mExpectedType = wantType;
  6279. argValue = ResolveArgValue(argValues[argExprIdx], wantType, NULL, paramKind, paramNameNode);
  6280. }
  6281. }
  6282. if (!argValue)
  6283. {
  6284. failed = true;
  6285. }
  6286. if (argValue)
  6287. {
  6288. if ((isThis) && (argValue.mType->IsRef()))
  6289. {
  6290. // Convert a 'ref this' to a 'this*'
  6291. argValue.mType = mModule->CreatePointerType(argValue.mType->GetUnderlyingType());
  6292. }
  6293. BfAstNode* refNode = arg;
  6294. if (refNode == NULL)
  6295. refNode = targetSrc;
  6296. if ((wantType->IsRef()) && (!argValue.mType->IsRef()) &&
  6297. (((callFlags & BfCreateCallFlags_AllowImplicitRef) != 0) || (wantType->IsIn())))
  6298. argValue = mModule->ToRef(argValue, (BfRefType*)wantType);
  6299. if (mModule->mCurMethodState != NULL)
  6300. {
  6301. SetAndRestoreValue<BfScopeData*> prevScopeData(mModule->mCurMethodState->mOverrideScope, boxScopeData);
  6302. argValue = mModule->Cast(refNode, argValue, wantType);
  6303. }
  6304. else
  6305. argValue = mModule->Cast(refNode, argValue, wantType);
  6306. if (!argValue)
  6307. {
  6308. if ((argExprIdx < (int)argValues.size()) && ((argValues[argExprIdx].mArgFlags & BfArgFlag_StringInterpolateArg) != 0))
  6309. {
  6310. BfAstNode* errorRef = NULL;
  6311. int checkIdx = argExprIdx - 1;
  6312. while (checkIdx >= 0)
  6313. {
  6314. if ((argValues[checkIdx].mArgFlags & BfArgFlag_StringInterpolateFormat) != 0)
  6315. {
  6316. errorRef = argValues[checkIdx].mExpression;
  6317. break;
  6318. }
  6319. checkIdx--;
  6320. }
  6321. if (errorRef != NULL)
  6322. mModule->Warn(0, "If string allocation was intended then consider adding a specifier such as 'scope'.", errorRef);
  6323. }
  6324. failed = true;
  6325. }
  6326. else if ((wantType->IsComposite()) && (!expandedParamsArray))
  6327. {
  6328. if (methodInstance->mIsIntrinsic)
  6329. {
  6330. // Intrinsics can handle structs either by value or address
  6331. }
  6332. else
  6333. {
  6334. // We need to make a temp and get the addr of that
  6335. if ((!wantsSplat) && (!argValue.IsValuelessType()) && (!argValue.IsAddr()) && (!IsComptimeEntry()))
  6336. {
  6337. argValue = mModule->MakeAddressable(argValue);
  6338. }
  6339. }
  6340. }
  6341. else if (!wantType->IsRef())
  6342. argValue = mModule->LoadValue(argValue);
  6343. }
  6344. if ((argExprIdx != -1) && (argExprIdx < (int)argValues.size()) && ((argValues[argExprIdx].mArgFlags & BfArgFlag_Cascade) != 0))
  6345. {
  6346. mUsedAsStatement = true;
  6347. argCascades.Add(argValue);
  6348. }
  6349. if (expandedParamsArray)
  6350. {
  6351. if (argValue)
  6352. {
  6353. if (IsComptimeEntry())
  6354. {
  6355. auto constant = mModule->mBfIRBuilder->GetConstant(expandedParamsArray.mValue);
  6356. BF_ASSERT(constant->mConstType == BfConstType_Agg);
  6357. auto constAgg = (BfConstantAgg*)constant;
  6358. constAgg->mValues[extendedParamIdx] = argValue.mValue;
  6359. }
  6360. else if (expandedParamAlloca)
  6361. {
  6362. argValue = mModule->LoadValue(argValue);
  6363. auto addr = mModule->mBfIRBuilder->CreateInBoundsGEP(expandedParamAlloca, extendedParamIdx);
  6364. auto storeInst = mModule->mBfIRBuilder->CreateAlignedStore(argValue.mValue, addr, argValue.mType->mAlign);
  6365. }
  6366. else
  6367. {
  6368. auto firstElem = mModule->GetFieldByName(expandedParamsArray.mType->ToTypeInstance(), "mFirstElement");
  6369. if (firstElem != NULL)
  6370. {
  6371. argValue = mModule->LoadValue(argValue);
  6372. auto firstAddr = mModule->mBfIRBuilder->CreateInBoundsGEP(expandedParamsArray.mValue, 0, firstElem->mDataIdx);
  6373. auto indexedAddr = mModule->CreateIndexedValue(argValue.mType, firstAddr, extendedParamIdx);
  6374. if (argValue.IsSplat())
  6375. mModule->AggregateSplatIntoAddr(argValue, indexedAddr);
  6376. else
  6377. mModule->mBfIRBuilder->CreateAlignedStore(argValue.mValue, indexedAddr, argValue.mType->mAlign);
  6378. }
  6379. }
  6380. }
  6381. extendedParamIdx++;
  6382. }
  6383. else
  6384. {
  6385. if ((paramIdx == 0) && (methodInstance->GetParamName(paramIdx) == "this") && (wantType->IsPointer()))
  6386. {
  6387. auto underlyingType = wantType->GetUnderlyingType();
  6388. mModule->PopulateType(underlyingType, BfPopulateType_Data);
  6389. if ((underlyingType->IsValuelessType()) && (!underlyingType->IsVoid()))
  6390. {
  6391. // We don't actually pass a 'this' pointer for mut methods on valueless structs
  6392. argIdx++;
  6393. paramIdx++;
  6394. continue;
  6395. }
  6396. }
  6397. if (argValue)
  6398. {
  6399. if (isThis)
  6400. PushThis(targetSrc, argValue, methodInstance, irArgs);
  6401. else if (wantsSplat)
  6402. SplatArgs(argValue, irArgs);
  6403. else
  6404. PushArg(argValue, irArgs, true, false, methodInstance->mIsIntrinsic);
  6405. }
  6406. paramIdx++;
  6407. }
  6408. argIdx++;
  6409. }
  6410. if (failed)
  6411. {
  6412. // Process the other unused arguments
  6413. while (argIdx < argValues.size())
  6414. {
  6415. mModule->AssertErrorState();
  6416. auto argValue = argValues[argIdx].mTypedValue;
  6417. if ((argValues[argIdx].mArgFlags & (BfArgFlag_DelegateBindAttempt | BfArgFlag_LambdaBindAttempt | BfArgFlag_UnqualifiedDotAttempt | BfArgFlag_DeferredEval | BfArgFlag_VariableDeclaration | BfArgFlag_UninitializedExpr)) != 0)
  6418. {
  6419. if (!argValue)
  6420. {
  6421. auto expr = BfNodeDynCast<BfExpression>(argValues[argIdx].mExpression);
  6422. if (expr != NULL)
  6423. argValue = mModule->CreateValueFromExpression(expr);
  6424. }
  6425. }
  6426. argIdx++;
  6427. }
  6428. return mModule->GetDefaultTypedValue(returnType, false, BfDefaultValueKind_Addr);
  6429. }
  6430. prevBindResult.Restore();
  6431. if (!methodDef->mIsStatic)
  6432. {
  6433. bool ignoreVirtualError = (mModule->mBfIRBuilder->mIgnoreWrites) && (mModule->mCurMethodInstance != NULL) && (mModule->mCurMethodInstance->mIsForeignMethodDef);
  6434. if ((methodInstance->GetOwner()->IsInterface()) && (!target.mType->IsGenericParam()) && (!target.mType->IsConcreteInterfaceType()) &&
  6435. (!mModule->mCurTypeInstance->IsInterface()) && (!ignoreVirtualError))
  6436. {
  6437. if (methodInstance->mVirtualTableIdx == -1)
  6438. {
  6439. mModule->PopulateType(methodInstance->GetOwner(), BfPopulateType_DataAndMethods);
  6440. }
  6441. if (methodInstance->mVirtualTableIdx == -1)
  6442. {
  6443. if (methodInstance->mMethodDef->mIsConcrete)
  6444. {
  6445. 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);
  6446. }
  6447. else if (methodInstance->HasSelf())
  6448. {
  6449. 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);
  6450. }
  6451. else
  6452. {
  6453. if ((bypassVirtual) && (mModule->mCurTypeInstance->IsInterface()))
  6454. {
  6455. // Allow a base call to be defined
  6456. }
  6457. else if ((methodInstance->IsSpecializedGenericMethod()) && (origTarget) && (!origTarget.mType->IsInterface()))
  6458. {
  6459. if (!mModule->mBfIRBuilder->mIgnoreWrites)
  6460. mModule->AssertErrorState();
  6461. }
  6462. else if ((!mModule->mCurMethodInstance->mIsUnspecialized))
  6463. {
  6464. // Compiler error?
  6465. String errorString = "Unable to dynamically dispatch '%s'";
  6466. if (methodInstance->IsSpecializedGenericMethod())
  6467. errorString = "Unable to dynamically dispatch '%s' because generic methods can only be directly dispatched";
  6468. if (methodInstance->mReturnType->IsConcreteInterfaceType())
  6469. errorString = "Unable to dynamically dispatch '%s' because the concrete return type is unknown";
  6470. mModule->Fail(StrFormat(errorString.c_str(), mModule->MethodToString(methodInstance).c_str()), targetSrc);
  6471. }
  6472. //BF_ASSERT(mModule->mCurMethodInstance->mIsUnspecialized);
  6473. }
  6474. if (mFunctionBindResult != NULL)
  6475. {
  6476. mFunctionBindResult->mMethodInstance = methodInstance;
  6477. mFunctionBindResult->mTarget = target;
  6478. mFunctionBindResult->mFunc = moduleMethodInstance.mFunc;
  6479. for (auto arg : irArgs)
  6480. mFunctionBindResult->mIRArgs.push_back(arg);
  6481. }
  6482. return mModule->GetDefaultTypedValue(returnType);
  6483. }
  6484. }
  6485. }
  6486. else
  6487. {
  6488. //BF_ASSERT(!methodInstance->GetOwner()->IsInterface());
  6489. }
  6490. if (target.mType != NULL)
  6491. {
  6492. // When we call a method from a static ctor, that method could access static fields so we need to make sure
  6493. // the type has been initialized
  6494. auto targetTypeInst = target.mType->ToTypeInstance();
  6495. if (targetTypeInst != NULL)
  6496. mModule->CheckStaticAccess(targetTypeInst);
  6497. }
  6498. if (methodInstance->mReturnType == NULL)
  6499. {
  6500. mModule->AssertErrorState();
  6501. mModule->Fail("Circular reference in method instance", targetSrc);
  6502. return BfTypedValue();
  6503. }
  6504. BfCreateCallFlags physCallFlags = BfCreateCallFlags_None;
  6505. if ((origTarget.mType != NULL) && (origTarget.mType->IsGenericParam()))
  6506. physCallFlags = (BfCreateCallFlags)(physCallFlags | BfCreateCallFlags_GenericParamThis);
  6507. auto func = moduleMethodInstance.mFunc;
  6508. BfTypedValue callResult = CreateCall(targetSrc, methodInstance, func, bypassVirtual, irArgs, NULL, physCallFlags);
  6509. // This gets triggered for non-sret (ie: comptime) composite returns so they aren't considered readonly
  6510. if ((callResult.mKind == BfTypedValueKind_Value) && (!callResult.mValue.IsConst()) &&
  6511. (!callResult.mType->IsValuelessType()) && (callResult.mType->IsComposite()) && (!methodInstance->GetLoweredReturnType()))
  6512. {
  6513. bool makeAddressable = true;
  6514. auto typeInstance = callResult.mType->ToTypeInstance();
  6515. if ((typeInstance != NULL) && (typeInstance->mHasUnderlyingArray))
  6516. makeAddressable = false;
  6517. if (makeAddressable)
  6518. {
  6519. callResult = mModule->MakeAddressable(callResult, true);
  6520. }
  6521. }
  6522. if (argCascades.mSize == 1)
  6523. {
  6524. if (argCascade == NULL)
  6525. return argCascades[0];
  6526. *argCascade = argCascades[0];
  6527. }
  6528. if (argCascades.mSize > 1)
  6529. {
  6530. if (argCascade == NULL)
  6531. return mModule->CreateTuple(argCascades, {});
  6532. *argCascade = mModule->CreateTuple(argCascades, {});
  6533. }
  6534. return callResult;
  6535. }
  6536. BfTypedValue BfExprEvaluator::MatchConstructor(BfAstNode* targetSrc, BfMethodBoundExpression* methodBoundExpr, BfTypedValue target, BfTypeInstance* targetType, BfResolvedArgs& argValues, bool callCtorBodyOnly, bool allowAppendAlloc, BfTypedValue* appendIndexValue)
  6537. {
  6538. // Temporarily disable so we don't capture calls in params
  6539. SetAndRestoreValue<BfFunctionBindResult*> prevBindResult(mFunctionBindResult, NULL);
  6540. static int sCtorCount = 0;
  6541. sCtorCount++;
  6542. BfMethodMatcher methodMatcher(targetSrc, mModule, "", argValues.mResolvedArgs, NULL);
  6543. methodMatcher.mBfEvalExprFlags = mBfEvalExprFlags;
  6544. BfTypeVector typeGenericArguments;
  6545. auto curTypeInst = targetType;
  6546. auto curTypeDef = targetType->mTypeDef;
  6547. BfProtectionCheckFlags protectionCheckFlags = BfProtectionCheckFlag_None;
  6548. auto activeTypeDef = mModule->GetActiveTypeDef();
  6549. auto visibleProjectSet = mModule->GetVisibleProjectSet();
  6550. bool isFailurePass = false;
  6551. for (int pass = 0; pass < 2; pass++)
  6552. {
  6553. isFailurePass = pass == 1;
  6554. curTypeDef->PopulateMemberSets();
  6555. BfMethodDef* nextMethodDef = NULL;
  6556. BfMemberSetEntry* entry;
  6557. if (curTypeDef->mMethodSet.TryGetWith(String("__BfCtor"), &entry))
  6558. nextMethodDef = (BfMethodDef*)entry->mMemberDef;
  6559. while (nextMethodDef != NULL)
  6560. {
  6561. auto checkMethod = nextMethodDef;
  6562. nextMethodDef = nextMethodDef->mNextWithSameName;
  6563. if ((isFailurePass) && (checkMethod->mMethodDeclaration == NULL))
  6564. continue; // Don't match private default ctor if there's a user-defined one
  6565. if (checkMethod->mIsStatic)
  6566. continue;
  6567. if ((checkMethod->mDeclaringType->IsExtension()) && (mModule->mAttributeState != NULL) && (mModule->mAttributeState->mCustomAttributes != NULL) &&
  6568. (mModule->mAttributeState->mCustomAttributes->Contains(mModule->mCompiler->mNoExtensionAttributeTypeDef)))
  6569. {
  6570. mModule->mAttributeState->mUsed = true;
  6571. continue;
  6572. }
  6573. if (!mModule->IsInSpecializedSection())
  6574. {
  6575. if ((!curTypeInst->IsTypeMemberIncluded(checkMethod->mDeclaringType, activeTypeDef, mModule)) ||
  6576. (!curTypeInst->IsTypeMemberAccessible(checkMethod->mDeclaringType, visibleProjectSet)))
  6577. continue;
  6578. }
  6579. auto checkProt = checkMethod->mProtection;
  6580. if (!isFailurePass)
  6581. {
  6582. if (callCtorBodyOnly)
  6583. {
  6584. if (curTypeDef != mModule->mCurTypeInstance->mTypeDef)
  6585. {
  6586. // We're calling the base class's ctor from a derived class
  6587. if (checkProt <= BfProtection_Private)
  6588. continue;
  6589. }
  6590. }
  6591. else
  6592. {
  6593. if ((checkProt == BfProtection_Protected) || (checkProt == BfProtection_ProtectedInternal)) // Treat protected constructors as private
  6594. checkProt = BfProtection_Private;
  6595. if (!mModule->CheckProtection(protectionCheckFlags, curTypeInst, checkMethod->mDeclaringType->mProject, checkProt, curTypeInst))
  6596. continue;
  6597. }
  6598. }
  6599. methodMatcher.CheckMethod(NULL, curTypeInst, checkMethod, isFailurePass);
  6600. }
  6601. if ((methodMatcher.mBestMethodDef != NULL) || (methodMatcher.mBackupMethodDef != NULL))
  6602. break;
  6603. }
  6604. if (methodMatcher.mBestMethodDef == NULL)
  6605. methodMatcher.mBestMethodDef = methodMatcher.mBackupMethodDef;
  6606. if (methodMatcher.mBestMethodDef == NULL)
  6607. {
  6608. mModule->Fail("No constructor available", targetSrc);
  6609. return BfTypedValue();
  6610. }
  6611. auto methodDef = methodMatcher.mBestMethodDef;
  6612. if (mModule->mCompiler->mResolvePassData != NULL)
  6613. mModule->mCompiler->mResolvePassData->HandleMethodReference(targetSrc, curTypeInst->mTypeDef->GetDefinition(), methodDef);
  6614. // There should always be a constructor
  6615. BF_ASSERT(methodMatcher.mBestMethodDef != NULL);
  6616. auto moduleMethodInstance = mModule->GetMethodInstance(methodMatcher.mBestMethodTypeInstance, methodMatcher.mBestMethodDef, methodMatcher.mBestMethodGenericArguments);
  6617. if (!mModule->CheckUseMethodInstance(moduleMethodInstance.mMethodInstance, targetSrc))
  6618. {
  6619. return BfTypedValue();
  6620. }
  6621. BfAutoComplete* autoComplete = GetAutoComplete();
  6622. if (autoComplete != NULL)
  6623. {
  6624. BfTypeInstance* resolvedTypeInstance = target.mType->ToTypeInstance();
  6625. auto ctorDecl = BfNodeDynCast<BfConstructorDeclaration>(methodDef->mMethodDeclaration);
  6626. if ((autoComplete->mIsGetDefinition) && (autoComplete->IsAutocompleteNode(targetSrc)) && (!BfNodeIsA<BfDelegateBindExpression>(targetSrc)))
  6627. {
  6628. if ((autoComplete->mDefMethod == NULL) && (autoComplete->mDefField == NULL) &&
  6629. (autoComplete->mDefProp == NULL)
  6630. && ((autoComplete->mDefType == NULL) || (autoComplete->mDefType == resolvedTypeInstance->mTypeDef)))
  6631. {
  6632. // Do we need to do this mDefType setting? If we do, then make sure we only get the element type of generics and such
  6633. //autoComplete->mDefType = resolvedTypeInstance->mTypeDef;
  6634. if (ctorDecl != NULL)
  6635. autoComplete->SetDefinitionLocation(ctorDecl->mThisToken, true);
  6636. else if (resolvedTypeInstance->mTypeDef->mTypeDeclaration != NULL)
  6637. autoComplete->SetDefinitionLocation(resolvedTypeInstance->mTypeDef->mTypeDeclaration->mNameNode, true);
  6638. }
  6639. }
  6640. else if ((autoComplete->mResolveType == BfResolveType_GetResultString) && (autoComplete->IsAutocompleteNode(targetSrc)) &&
  6641. (moduleMethodInstance.mMethodInstance != NULL))
  6642. {
  6643. autoComplete->mResultString = ":";
  6644. autoComplete->mResultString += mModule->MethodToString(moduleMethodInstance.mMethodInstance);
  6645. }
  6646. }
  6647. BfConstructorDeclaration* ctorDecl = (BfConstructorDeclaration*)methodMatcher.mBestMethodDef->mMethodDeclaration;
  6648. if ((methodMatcher.mBestMethodDef->mHasAppend) && (targetType->IsObject()))
  6649. {
  6650. if (!allowAppendAlloc)
  6651. {
  6652. if (mModule->mCurMethodInstance->mMethodDef->mMethodDeclaration == NULL)
  6653. mModule->Fail("Constructors with append allocations cannot be called from a default constructor. Considering adding an explicit default constructor with the [AllowAppend] specifier.", targetSrc);
  6654. else
  6655. mModule->Fail("Constructors with append allocations cannot be called from a constructor without [AllowAppend] specified.", targetSrc);
  6656. }
  6657. else
  6658. {
  6659. BfResolvedArg resolvedArg;
  6660. if (appendIndexValue != NULL)
  6661. {
  6662. resolvedArg.mTypedValue = *appendIndexValue;
  6663. }
  6664. else
  6665. {
  6666. auto intPtrType = mModule->GetPrimitiveType(BfTypeCode_IntPtr);
  6667. auto intPtrRefType = mModule->CreateRefType(intPtrType);
  6668. if (target.mValue.IsFake())
  6669. {
  6670. resolvedArg.mTypedValue = BfTypedValue(mModule->mBfIRBuilder->GetFakeVal(), intPtrRefType);
  6671. }
  6672. else
  6673. {
  6674. BFMODULE_FATAL(mModule, "Bad");
  6675. }
  6676. }
  6677. methodMatcher.mArguments.Insert(0, resolvedArg);
  6678. }
  6679. }
  6680. if (isFailurePass)
  6681. mModule->Fail(StrFormat("'%s' is inaccessible due to its protection level", mModule->MethodToString(moduleMethodInstance.mMethodInstance).c_str()), targetSrc);
  6682. prevBindResult.Restore();
  6683. return CreateCall(methodMatcher.mTargetSrc, target, BfTypedValue(), methodMatcher.mBestMethodDef, moduleMethodInstance, BfCreateCallFlags_None, methodMatcher.mArguments);
  6684. }
  6685. static int sInvocationIdx = 0;
  6686. BfTypedValue BfExprEvaluator::ResolveArgValue(BfResolvedArg& resolvedArg, BfType* wantType, BfTypedValue* receivingValue, BfParamKind paramKind, BfIdentifierNode* paramNameNode)
  6687. {
  6688. BfTypedValue argValue = resolvedArg.mTypedValue;
  6689. if ((resolvedArg.mArgFlags & (BfArgFlag_DelegateBindAttempt | BfArgFlag_LambdaBindAttempt | BfArgFlag_UnqualifiedDotAttempt | BfArgFlag_DeferredEval)) != 0)
  6690. {
  6691. if ((!argValue) || (argValue.mValue.IsFake()) || (resolvedArg.mWantsRecalc))
  6692. {
  6693. resolvedArg.mWantsRecalc = false;
  6694. auto expr = BfNodeDynCast<BfExpression>(resolvedArg.mExpression);
  6695. if (expr != NULL)
  6696. {
  6697. BfExprEvaluator exprEvaluator(mModule);
  6698. exprEvaluator.mReceivingValue = receivingValue;
  6699. BfEvalExprFlags flags = (BfEvalExprFlags)((mBfEvalExprFlags & BfEvalExprFlags_InheritFlags) | BfEvalExprFlags_NoCast);
  6700. if ((paramKind == BfParamKind_Params) || (paramKind == BfParamKind_DelegateParam))
  6701. flags = (BfEvalExprFlags)(flags | BfEvalExprFlags_AllowParamsExpr);
  6702. argValue = mModule->CreateValueFromExpression(exprEvaluator, expr, wantType, flags);
  6703. if ((argValue) && (argValue.mType != wantType) && (wantType != NULL))
  6704. {
  6705. if ((mDeferScopeAlloc != NULL) && (wantType == mModule->mContext->mBfObjectType))
  6706. {
  6707. BfAllocTarget allocTarget(mDeferScopeAlloc);
  6708. argValue = mModule->BoxValue(expr, argValue, wantType, allocTarget);
  6709. }
  6710. else
  6711. argValue = mModule->Cast(expr, argValue, wantType);
  6712. }
  6713. }
  6714. }
  6715. }
  6716. else if ((resolvedArg.mArgFlags & (BfArgFlag_DeferredValue)) != 0)
  6717. {
  6718. // We should have already had an error on the first call
  6719. SetAndRestoreValue<bool> prevIgnoreErrors(mModule->mIgnoreErrors, mModule->mHadBuildError);
  6720. auto expr = BfNodeDynCast<BfExpression>(resolvedArg.mExpression);
  6721. BF_ASSERT(expr != NULL);
  6722. argValue = mModule->CreateValueFromExpression(expr, wantType, (BfEvalExprFlags)((mBfEvalExprFlags & BfEvalExprFlags_InheritFlags) | BfEvalExprFlags_NoCast | BfEvalExprFlags_AllowRefExpr | BfEvalExprFlags_AllowOutExpr));
  6723. if ((argValue) && (wantType != NULL))
  6724. argValue = mModule->Cast(expr, argValue, wantType);
  6725. }
  6726. else if ((resolvedArg.mArgFlags & (BfArgFlag_UntypedDefault)) != 0)
  6727. {
  6728. argValue = mModule->GetDefaultTypedValue(wantType);
  6729. }
  6730. else if ((resolvedArg.mArgFlags & (BfArgFlag_VariableDeclaration | BfArgFlag_UninitializedExpr)) != 0)
  6731. {
  6732. auto variableDeclaration = BfNodeDynCast<BfVariableDeclaration>(resolvedArg.mExpression);
  6733. auto variableType = wantType;
  6734. bool isLet = (variableDeclaration != NULL) && (variableDeclaration->mTypeRef->IsExact<BfLetTypeReference>());
  6735. bool isVar = (variableDeclaration == NULL) || (variableDeclaration->mTypeRef->IsExact<BfVarTypeReference>());
  6736. if (mModule->mCurMethodState->mPendingNullConditional != NULL)
  6737. {
  6738. mModule->Fail("Variables cannot be declared in method arguments inside null conditional expressions", variableDeclaration);
  6739. }
  6740. if ((!isLet) && (!isVar))
  6741. {
  6742. if (variableType->IsVar())
  6743. {
  6744. auto resolvedType = mModule->ResolveTypeRef(variableDeclaration->mTypeRef);
  6745. if (resolvedType != NULL)
  6746. variableType = resolvedType;
  6747. }
  6748. else
  6749. {
  6750. mModule->Fail("Only 'ref' or 'var' variables can be declared in method arguments", variableDeclaration);
  6751. auto autoComplete = GetAutoComplete();
  6752. if (autoComplete != NULL)
  6753. autoComplete->CheckTypeRef(variableDeclaration->mTypeRef, true, true);
  6754. }
  6755. }
  6756. else
  6757. {
  6758. if (variableType->IsVar())
  6759. {
  6760. mModule->Fail("Variable type required for 'var' parameter types", variableDeclaration);
  6761. }
  6762. }
  6763. if (wantType->IsRef())
  6764. {
  6765. auto refType = (BfRefType*)wantType;
  6766. variableType = refType->mElementType;
  6767. }
  6768. if ((variableDeclaration != NULL) && (variableDeclaration->mInitializer != NULL))
  6769. {
  6770. mModule->Fail("Initializers cannot be used when declaring variables for 'out' parameters", variableDeclaration->mEqualsNode);
  6771. mModule->CreateValueFromExpression(variableDeclaration->mInitializer, variableType, BfEvalExprFlags_NoCast);
  6772. }
  6773. BfLocalVariable* localVar = new BfLocalVariable();
  6774. if ((variableDeclaration != NULL) && (variableDeclaration->mNameNode != NULL))
  6775. {
  6776. localVar->mName = variableDeclaration->mNameNode->ToString();
  6777. localVar->mNameNode = BfNodeDynCast<BfIdentifierNode>(variableDeclaration->mNameNode);
  6778. }
  6779. else
  6780. {
  6781. if (paramNameNode != NULL)
  6782. {
  6783. localVar->mName = "__";
  6784. paramNameNode->ToString(localVar->mName);
  6785. localVar->mName += "_";
  6786. localVar->mName += StrFormat("%d", mModule->mCurMethodState->GetRootMethodState()->mCurLocalVarId);
  6787. }
  6788. else
  6789. localVar->mName = "__" + StrFormat("%d", mModule->mCurMethodState->GetRootMethodState()->mCurLocalVarId);
  6790. }
  6791. localVar->mResolvedType = variableType;
  6792. if (!variableType->IsValuelessType())
  6793. localVar->mAddr = mModule->CreateAlloca(variableType);
  6794. localVar->mIsReadOnly = isLet;
  6795. localVar->mReadFromId = 0;
  6796. localVar->mWrittenToId = 0;
  6797. localVar->mAssignedKind = BfLocalVarAssignKind_Unconditional;
  6798. mModule->CheckVariableDef(localVar);
  6799. localVar->Init();
  6800. mModule->AddLocalVariableDef(localVar, true);
  6801. CheckVariableDeclaration(resolvedArg.mExpression, false, false, false);
  6802. argValue = BfTypedValue(localVar->mAddr, mModule->CreateRefType(variableType, BfRefType::RefKind_Out));
  6803. auto curScope = mModule->mCurMethodState->mCurScope;
  6804. if (curScope->mScopeKind == BfScopeKind_StatementTarget)
  6805. {
  6806. // Move this variable into the parent scope
  6807. curScope->mLocalVarStart = (int)mModule->mCurMethodState->mLocals.size();
  6808. }
  6809. }
  6810. return argValue;
  6811. }
  6812. BfTypedValue BfExprEvaluator::CheckEnumCreation(BfAstNode* targetSrc, BfTypeInstance* enumType, const StringImpl& caseName, BfResolvedArgs& argValues)
  6813. {
  6814. auto activeTypeDef = mModule->GetActiveTypeDef();
  6815. mModule->mBfIRBuilder->PopulateType(enumType);
  6816. auto resolvePassData = mModule->mCompiler->mResolvePassData;
  6817. // if (resolvePassData != NULL)
  6818. // {
  6819. // if (mModule->mParentNodeEntry != NULL)
  6820. // {
  6821. // if (auto invocationExpr = BfNodeDynCast<BfInvocationExpression>(mModule->mParentNodeEntry->mNode))
  6822. // {
  6823. // if (auto memberRefExpr = BfNodeDynCast<BfMemberReferenceExpression>(invocationExpr->mTarget))
  6824. // {
  6825. // BfAstNode* dotNode = memberRefExpr->mDotToken;
  6826. // BfAstNode* nameNode = targetSrc;
  6827. // String filter;
  6828. // auto autoComplete = resolvePassData->mAutoComplete;
  6829. // if ((autoComplete != NULL) && (autoComplete->InitAutocomplete(dotNode, nameNode, filter)))
  6830. // autoComplete->AddEnumTypeMembers(enumType, caseName, false, enumType == mModule->mCurTypeInstance);
  6831. // }
  6832. // }
  6833. // }
  6834. // }
  6835. for (int fieldIdx = 0; fieldIdx < (int)enumType->mFieldInstances.size(); fieldIdx++)
  6836. {
  6837. auto fieldInstance = &enumType->mFieldInstances[fieldIdx];
  6838. auto fieldDef = fieldInstance->GetFieldDef();
  6839. if (fieldDef == NULL)
  6840. continue;
  6841. if ((fieldInstance->mIsEnumPayloadCase) && (fieldDef->mName == caseName))
  6842. {
  6843. if ((!enumType->IsTypeMemberIncluded(fieldDef->mDeclaringType, activeTypeDef, mModule)) ||
  6844. (!enumType->IsTypeMemberAccessible(fieldDef->mDeclaringType, activeTypeDef)))
  6845. continue;
  6846. auto autoComplete = GetAutoComplete();
  6847. if ((autoComplete != NULL) && (autoComplete->mIsCapturingMethodMatchInfo))
  6848. {
  6849. BfAutoComplete::MethodMatchEntry methodMatchEntry;
  6850. methodMatchEntry.mPayloadEnumField = fieldInstance;
  6851. methodMatchEntry.mTypeInstance = enumType;
  6852. methodMatchEntry.mCurMethodInstance = mModule->mCurMethodInstance;
  6853. autoComplete->mMethodMatchInfo->mInstanceList.push_back(methodMatchEntry);
  6854. }
  6855. if (resolvePassData != NULL)
  6856. {
  6857. BfAstNode* nameNode = targetSrc;
  6858. if (resolvePassData->mGetSymbolReferenceKind == BfGetSymbolReferenceKind_Field)
  6859. resolvePassData->HandleFieldReference(nameNode, enumType->mTypeDef, fieldDef);
  6860. }
  6861. BfIRValue enumValue;
  6862. BfTypedValue result;
  6863. bool wantConst = IsComptimeEntry();
  6864. if (wantConst)
  6865. {
  6866. NOP;
  6867. }
  6868. else if ((mReceivingValue != NULL) && (mReceivingValue->mType == enumType) && (mReceivingValue->IsAddr()))
  6869. {
  6870. result = *mReceivingValue;
  6871. mReceivingValue = NULL;
  6872. enumValue = result.mValue;
  6873. }
  6874. else
  6875. {
  6876. mResultIsTempComposite = true;
  6877. enumValue = mModule->CreateAlloca(enumType);
  6878. result = BfTypedValue(enumValue, fieldInstance->mOwner, BfTypedValueKind_TempAddr);
  6879. }
  6880. BF_ASSERT(fieldInstance->mResolvedType->IsTuple());
  6881. auto tupleType = (BfTypeInstance*)fieldInstance->mResolvedType;
  6882. mModule->mBfIRBuilder->PopulateType(tupleType);
  6883. bool constFailed = false;
  6884. SizedArray<BfIRValue, 8> constTupleMembers;
  6885. BfIRValue fieldPtr;
  6886. BfIRValue tuplePtr;
  6887. if (wantConst)
  6888. {
  6889. constTupleMembers.Add(mModule->mBfIRBuilder->CreateConstAggZero(mModule->mBfIRBuilder->MapType(tupleType->mBaseType)));
  6890. }
  6891. else if (!tupleType->IsValuelessType())
  6892. {
  6893. fieldPtr = mModule->mBfIRBuilder->CreateInBoundsGEP(enumValue, 0, 1);
  6894. auto tuplePtrType = mModule->CreatePointerType(tupleType);
  6895. auto mappedPtrType = mModule->mBfIRBuilder->MapType(tuplePtrType);
  6896. tuplePtr = mModule->mBfIRBuilder->CreateBitCast(fieldPtr, mappedPtrType);
  6897. }
  6898. for (int tupleFieldIdx = 0; tupleFieldIdx < (int)tupleType->mFieldInstances.size(); tupleFieldIdx++)
  6899. {
  6900. auto tupleFieldInstance = &tupleType->mFieldInstances[tupleFieldIdx];
  6901. auto resolvedFieldType = tupleFieldInstance->GetResolvedType();
  6902. if (tupleFieldIdx >= argValues.mResolvedArgs.size())
  6903. {
  6904. BfAstNode* refNode = targetSrc;
  6905. BfAstNode* prevNode = NULL;
  6906. if (mModule->mParentNodeEntry != NULL)
  6907. {
  6908. if (auto invokeExpr = BfNodeDynCast<BfInvocationExpression>(mModule->mParentNodeEntry->mNode))
  6909. {
  6910. if (invokeExpr->mCloseParen != NULL)
  6911. refNode = invokeExpr->mCloseParen;
  6912. }
  6913. }
  6914. BfError* error = mModule->Fail(StrFormat("Not enough parameters specified, expected %d more.", tupleType->mFieldInstances.size() - (int)argValues.mArguments->size()), refNode);
  6915. if (error != NULL)
  6916. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("See enum declaration"), fieldDef->mFieldDeclaration);
  6917. if (wantConst)
  6918. constFailed = true;
  6919. break;
  6920. }
  6921. BfTypedValue receivingValue;
  6922. BfIRValue tupleFieldPtr;
  6923. if (tuplePtr)
  6924. {
  6925. tupleFieldPtr = mModule->mBfIRBuilder->CreateInBoundsGEP(tuplePtr, 0, tupleFieldInstance->mDataIdx);
  6926. receivingValue = BfTypedValue(tupleFieldPtr, tupleFieldInstance->mResolvedType, true);
  6927. }
  6928. auto argValue = ResolveArgValue(argValues.mResolvedArgs[tupleFieldIdx], resolvedFieldType, &receivingValue);
  6929. if (!argValue)
  6930. {
  6931. if (wantConst)
  6932. constFailed = true;
  6933. continue;
  6934. }
  6935. if (argValue.IsValuelessType())
  6936. {
  6937. continue;
  6938. }
  6939. // Used receiving value?
  6940. if (argValue.mValue == receivingValue.mValue)
  6941. continue;
  6942. argValue = mModule->AggregateSplat(argValue);
  6943. argValues.mResolvedArgs[tupleFieldIdx].mExpectedType = resolvedFieldType;
  6944. if ((argValues.mResolvedArgs[tupleFieldIdx].mArgFlags & (BfArgFlag_DelegateBindAttempt | BfArgFlag_LambdaBindAttempt | BfArgFlag_UnqualifiedDotAttempt)) != 0)
  6945. {
  6946. auto expr = BfNodeDynCast<BfExpression>(argValues.mResolvedArgs[tupleFieldIdx].mExpression);
  6947. BF_ASSERT(expr != NULL);
  6948. argValue = mModule->CreateValueFromExpression(expr, resolvedFieldType, (BfEvalExprFlags)(mBfEvalExprFlags & BfEvalExprFlags_InheritFlags));
  6949. }
  6950. if (argValue)
  6951. {
  6952. // argValue can have a value even if tuplePtr does not have a value. This can happen if we are assigning to a (void) tuple,
  6953. // but we have a value that needs to be attempted to be casted to void
  6954. argValue = mModule->Cast(argValues.mResolvedArgs[tupleFieldIdx].mExpression, argValue, resolvedFieldType);
  6955. if (wantConst)
  6956. {
  6957. if (!argValue.mValue.IsConst())
  6958. {
  6959. mModule->Fail("Field not const", argValues.mResolvedArgs[tupleFieldIdx].mExpression);
  6960. constFailed = true;
  6961. }
  6962. constTupleMembers.Add(argValue.mValue);
  6963. }
  6964. else if (tupleFieldPtr)
  6965. {
  6966. argValue = mModule->LoadValue(argValue);
  6967. if (argValue)
  6968. mModule->mBfIRBuilder->CreateAlignedStore(argValue.mValue, tupleFieldPtr, resolvedFieldType->mAlign);
  6969. }
  6970. }
  6971. else if (wantConst)
  6972. constFailed = true;
  6973. }
  6974. if ((intptr)argValues.mResolvedArgs.size() > tupleType->mFieldInstances.size())
  6975. {
  6976. BfAstNode* errorRef = argValues.mResolvedArgs[tupleType->mFieldInstances.size()].mExpression;
  6977. if (errorRef == NULL)
  6978. errorRef = targetSrc;
  6979. BfError* error = mModule->Fail(StrFormat("Too many arguments, expected %d fewer.", argValues.mResolvedArgs.size() - tupleType->mFieldInstances.size()), errorRef);
  6980. if (error != NULL)
  6981. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("See enum declaration"), fieldDef->mFieldDeclaration);
  6982. if (wantConst)
  6983. constFailed = true;
  6984. }
  6985. auto dscrType = enumType->GetDiscriminatorType();
  6986. auto dscrField = &enumType->mFieldInstances.back();
  6987. int tagIdx = -fieldInstance->mDataIdx - 1;
  6988. if ((wantConst) && (!constFailed))
  6989. {
  6990. auto unionType = enumType->GetUnionInnerType();
  6991. auto constTuple = mModule->mBfIRBuilder->CreateConstAgg(mModule->mBfIRBuilder->MapType(tupleType, BfIRPopulateType_Full), constTupleMembers);
  6992. Array<uint8> memArr;
  6993. memArr.Resize(unionType->mSize);
  6994. if (!mModule->mBfIRBuilder->WriteConstant(constTuple, memArr.mVals, tupleType))
  6995. {
  6996. constFailed = true;
  6997. }
  6998. else
  6999. {
  7000. auto unionValue = mModule->mBfIRBuilder->ReadConstant(memArr.mVals, unionType);
  7001. if (!unionValue)
  7002. {
  7003. constFailed = true;
  7004. }
  7005. else
  7006. {
  7007. SizedArray<BfIRValue, 3> constEnumMembers;
  7008. constEnumMembers.Add(mModule->mBfIRBuilder->CreateConstAggZero(mModule->mBfIRBuilder->MapType(enumType->mBaseType, BfIRPopulateType_Full)));
  7009. constEnumMembers.Add(unionValue);
  7010. constEnumMembers.Add(mModule->mBfIRBuilder->CreateConst(dscrType->mTypeDef->mTypeCode, tagIdx));
  7011. return BfTypedValue(mModule->mBfIRBuilder->CreateConstAgg(mModule->mBfIRBuilder->MapType(enumType, BfIRPopulateType_Full), constEnumMembers), enumType);
  7012. }
  7013. }
  7014. }
  7015. if (constFailed)
  7016. {
  7017. return mModule->GetDefaultTypedValue(enumType, false, BfDefaultValueKind_Addr);
  7018. }
  7019. auto dscFieldPtr = mModule->mBfIRBuilder->CreateInBoundsGEP(enumValue, 0, dscrField->mDataIdx);
  7020. mModule->mBfIRBuilder->CreateAlignedStore(mModule->mBfIRBuilder->CreateConst(dscrType->mTypeDef->mTypeCode, tagIdx), dscFieldPtr, 4);
  7021. return result;
  7022. }
  7023. }
  7024. return BfTypedValue();
  7025. }
  7026. bool BfExprEvaluator::CheckGenericCtor(BfGenericParamType* genericParamType, BfResolvedArgs& argValues, BfAstNode* targetSrc)
  7027. {
  7028. BfGenericParamFlags genericParamFlags = BfGenericParamFlag_None;
  7029. BfType* typeConstraint = NULL;
  7030. auto genericParam = mModule->GetMergedGenericParamData((BfGenericParamType*)genericParamType, genericParamFlags, typeConstraint);
  7031. bool success = true;
  7032. if ((argValues.mArguments != NULL) && (argValues.mArguments->size() != 0))
  7033. {
  7034. mModule->Fail(StrFormat("Only default parameterless constructors can be called on generic argument '%s'", genericParam->GetGenericParamDef()->mName.c_str()), targetSrc);
  7035. success = false;
  7036. }
  7037. else if ((genericParamFlags & (BfGenericParamFlag_New | BfGenericParamFlag_Struct | BfGenericParamFlag_Var)) == 0)
  7038. {
  7039. mModule->Fail(StrFormat("Must add 'where %s : new, struct' constraint to generic parameter to instantiate type", genericParam->GetGenericParamDef()->mName.c_str()), targetSrc);
  7040. success = false;
  7041. }
  7042. else if ((genericParamFlags & (BfGenericParamFlag_New | BfGenericParamFlag_Var)) == 0)
  7043. {
  7044. mModule->Fail(StrFormat("Must add 'where %s : new' constraint to generic parameter to instantiate type", genericParam->GetGenericParamDef()->mName.c_str()), targetSrc);
  7045. success = false;
  7046. }
  7047. else if ((genericParamFlags & (BfGenericParamFlag_Struct | BfGenericParamFlag_Var)) == 0)
  7048. {
  7049. mModule->Fail(StrFormat("Must add 'where %s : struct' constraint to generic parameter to instantiate type without allocator", genericParam->GetGenericParamDef()->mName.c_str()), targetSrc);
  7050. success = false;
  7051. }
  7052. return success;
  7053. }
  7054. BfTypedValue BfExprEvaluator::MatchMethod(BfAstNode* targetSrc, BfMethodBoundExpression* methodBoundExpr, BfTypedValue target, bool allowImplicitThis, bool bypassVirtual, const StringImpl& methodName,
  7055. BfResolvedArgs& argValues, BfSizedArray<ASTREF(BfTypeReference*)>* methodGenericArguments, BfCheckedKind checkedKind)
  7056. {
  7057. BP_ZONE("MatchMethod");
  7058. if (bypassVirtual)
  7059. {
  7060. // "bypassVirtual" means that we know for sure that the target is EXACTLY the specified target type,
  7061. // not derived from (or implementing) the target type. This cannot apply to interfaces.
  7062. BF_ASSERT(!target.mType->IsInterface());
  7063. }
  7064. auto origTarget = target;
  7065. if (mFunctionBindResult != NULL)
  7066. {
  7067. BF_ASSERT(!mFunctionBindResult->mOrigTarget);
  7068. mFunctionBindResult->mOrigTarget = origTarget;
  7069. }
  7070. if (target)
  7071. {
  7072. if (target.mType->IsConcreteInterfaceType())
  7073. target.mType = target.mType->GetUnderlyingType();
  7074. // Turn T* into a T, if we can
  7075. if ((target.mType->IsPointer()) && (target.mType->GetUnderlyingType()->IsGenericParam()))
  7076. {
  7077. auto underlyingType = target.mType->GetUnderlyingType();
  7078. auto genericParam = mModule->GetGenericParamInstance((BfGenericParamType*)underlyingType);
  7079. if (((genericParam->mTypeConstraint != NULL) && (genericParam->mTypeConstraint->IsValueType())) ||
  7080. ((genericParam->mGenericParamFlags & (BfGenericParamFlag_Struct)) != 0))
  7081. {
  7082. target.mType = underlyingType;
  7083. }
  7084. }
  7085. if ((!target.mType->IsGenericParam()) && (!target.IsSplat()) && (!target.mType->IsVar()))
  7086. target = MakeCallableTarget(targetSrc, target);
  7087. }
  7088. // static int sCallIdx = 0;
  7089. // if (!mModule->mCompiler->mIsResolveOnly)
  7090. // sCallIdx++;
  7091. // int callIdx = sCallIdx;
  7092. // if (callIdx == 118)
  7093. // {
  7094. // NOP;
  7095. // }
  7096. bool prevAllowVariableDeclarations = true;
  7097. if (mModule->mCurMethodState != NULL)
  7098. {
  7099. // Don't allow variable declarations in arguments for this method call
  7100. prevAllowVariableDeclarations = mModule->mCurMethodState->mCurScope->mAllowVariableDeclarations;
  7101. mModule->mCurMethodState->mCurScope->mAllowVariableDeclarations = false;
  7102. }
  7103. defer
  7104. (
  7105. if (mModule->mCurMethodState != NULL)
  7106. mModule->mCurMethodState->mCurScope->mAllowVariableDeclarations = prevAllowVariableDeclarations;
  7107. );
  7108. // Temporarily disable so we don't capture calls in params
  7109. SetAndRestoreValue<BfFunctionBindResult*> prevBindResult(mFunctionBindResult, NULL);
  7110. sInvocationIdx++;
  7111. bool wantCtor = methodName.IsEmpty();
  7112. BfAutoComplete::MethodMatchInfo* restoreCapturingMethodMatchInfo = NULL;
  7113. auto autoComplete = GetAutoComplete();
  7114. if ((autoComplete != NULL) && (autoComplete->mIsCapturingMethodMatchInfo))
  7115. {
  7116. if ((!targetSrc->IsFromParser(mModule->mCompiler->mResolvePassData->mParser)) ||
  7117. ((autoComplete->mMethodMatchInfo->mInvocationSrcIdx != -1) && (autoComplete->mMethodMatchInfo->mInvocationSrcIdx != targetSrc->GetSrcStart())))
  7118. {
  7119. autoComplete->mIsCapturingMethodMatchInfo = false;
  7120. restoreCapturingMethodMatchInfo = autoComplete->mMethodMatchInfo;
  7121. }
  7122. }
  7123. defer(
  7124. {
  7125. if ((restoreCapturingMethodMatchInfo != NULL) && (autoComplete->mMethodMatchInfo == restoreCapturingMethodMatchInfo))
  7126. autoComplete->mIsCapturingMethodMatchInfo = true;
  7127. });
  7128. /*if ((autoComplete != NULL) && (autoComplete->mIsCapturingMethodMatchInfo) && (autoComplete->mMethodMatchInfo->mInstanceList.size() != 0))
  7129. autoComplete->mIsCapturingMethodMatchInfo = false;*/
  7130. bool isUnboundCall = false;
  7131. if (target.mType != NULL)
  7132. {
  7133. if (target.mType->IsGenericParam())
  7134. {
  7135. auto genericParamTarget = (BfGenericParamType*) target.mType;
  7136. auto genericParamInstance = mModule->GetGenericParamInstance(genericParamTarget);
  7137. isUnboundCall = (genericParamInstance->mGenericParamFlags & BfGenericParamFlag_Var) != 0;
  7138. if (isUnboundCall)
  7139. {
  7140. if (mModule->mCurMethodInstance->mIsUnspecialized)
  7141. {
  7142. auto varType = mModule->GetPrimitiveType(BfTypeCode_Var);
  7143. target.mType = varType;
  7144. }
  7145. }
  7146. }
  7147. else if (target.mType->IsVar())
  7148. isUnboundCall = true;
  7149. }
  7150. /*if (mPrefixedAttributeState != NULL)
  7151. {
  7152. auto customAttr = mPrefixedAttributeState->mCustomAttributes->Get(mModule->mCompiler->mUnboundAttributeTypeDef);
  7153. if (customAttr != NULL)
  7154. {
  7155. if (!mModule->IsInGeneric())
  7156. {
  7157. mModule->Fail("'Unbound' can only be used within generics");
  7158. }
  7159. mPrefixedAttributeState->mUsed = true;
  7160. isUnboundCall = true;
  7161. }
  7162. }*/
  7163. if ((mModule->mAttributeState != NULL) && (mModule->mAttributeState->mCustomAttributes != NULL))
  7164. {
  7165. auto customAttr = mModule->mAttributeState->mCustomAttributes->Get(mModule->mCompiler->mUnboundAttributeTypeDef);
  7166. if (customAttr != NULL)
  7167. {
  7168. if (!mModule->IsInGeneric())
  7169. {
  7170. mModule->Fail("'Unbound' can only be used within generics");
  7171. }
  7172. mModule->mAttributeState->mUsed = true;
  7173. isUnboundCall = true;
  7174. }
  7175. }
  7176. if (isUnboundCall)
  7177. {
  7178. if ((mModule->mCurMethodInstance != NULL) && (mModule->mCurMethodInstance->mIsUnspecialized))
  7179. {
  7180. auto varType = mModule->GetPrimitiveType(BfTypeCode_Var);
  7181. for (int argIdx = 0; argIdx < (int)argValues.mResolvedArgs.size(); argIdx++)
  7182. {
  7183. if ((argValues.mResolvedArgs[argIdx].mArgFlags & BfArgFlag_DeferredEval) != 0)
  7184. {
  7185. mModule->CreateValueFromExpression((*argValues.mArguments)[argIdx], varType);
  7186. }
  7187. }
  7188. return BfTypedValue(mModule->GetDefaultValue(varType), varType);
  7189. }
  7190. }
  7191. SetAndRestoreValue<bool> prevNoBind(mNoBind, mNoBind || isUnboundCall);
  7192. bool wantsExtensionCheck = target;
  7193. auto targetType = target.mType;
  7194. BfTypeDef* curTypeDef = NULL;
  7195. BfTypeInstance* targetTypeInst = NULL;
  7196. bool checkNonStatic = true;
  7197. if (target)
  7198. {
  7199. if (targetType->IsVar())
  7200. return mModule->GetDefaultTypedValue(targetType);
  7201. targetTypeInst = targetType->ToTypeInstance();
  7202. if (targetTypeInst != NULL)
  7203. curTypeDef = targetTypeInst->mTypeDef;
  7204. }
  7205. else if (targetType != NULL) // Static targeted
  7206. {
  7207. if (targetType->IsWrappableType())
  7208. {
  7209. if ((targetType->IsPrimitiveType()) && (methodName.IsEmpty()))
  7210. {
  7211. if (argValues.mArguments->IsEmpty())
  7212. {
  7213. return mModule->GetDefaultTypedValue(targetType);
  7214. }
  7215. else if (argValues.mArguments->mSize == 1)
  7216. {
  7217. FinishDeferredEvals(argValues);
  7218. // This is just a primitive cast
  7219. auto& resolvedArg = argValues.mResolvedArgs[0];
  7220. BfTypedValue castedValue;
  7221. BfTypedValue castTarget = resolvedArg.mTypedValue;
  7222. if (resolvedArg.mTypedValue)
  7223. {
  7224. castTarget = mModule->LoadValue(castTarget);
  7225. castedValue = mModule->Cast(targetSrc, castTarget, targetType, BfCastFlags_Explicit);
  7226. }
  7227. if (!castedValue)
  7228. castedValue = mModule->GetDefaultTypedValue(targetType);
  7229. return castedValue;
  7230. }
  7231. }
  7232. targetTypeInst = mModule->GetWrappedStructType(targetType);
  7233. }
  7234. else if (targetType->IsGenericParam())
  7235. {
  7236. auto genericParamInstance = mModule->GetGenericParamInstance((BfGenericParamType*)targetType);
  7237. if (genericParamInstance->mTypeConstraint != NULL)
  7238. targetTypeInst = genericParamInstance->mTypeConstraint->ToTypeInstance();
  7239. if (genericParamInstance->mGenericParamFlags & BfGenericParamFlag_Var)
  7240. {
  7241. auto varType = mModule->GetPrimitiveType(BfTypeCode_Var);
  7242. return BfTypedValue(mModule->GetDefaultValue(varType), varType);
  7243. }
  7244. }
  7245. else
  7246. targetTypeInst = targetType->ToTypeInstance();
  7247. if (targetTypeInst == NULL)
  7248. {
  7249. //mModule->Fail("No static methods available", targetSrc);
  7250. //return BfTypedValue();
  7251. }
  7252. else
  7253. {
  7254. curTypeDef = targetTypeInst->mTypeDef;
  7255. checkNonStatic = false;
  7256. }
  7257. }
  7258. else // Current scopeData
  7259. {
  7260. if ((mModule->mCurMethodInstance != NULL) && (mModule->mCurMethodInstance->mIsForeignMethodDef) && (mModule->mCurMethodInstance->mMethodInfoEx->mForeignType->IsInterface()))
  7261. {
  7262. targetTypeInst = mModule->mCurMethodInstance->mMethodInfoEx->mForeignType;
  7263. curTypeDef = targetTypeInst->mTypeDef;
  7264. checkNonStatic = true;
  7265. target = mModule->GetThis();
  7266. //target.mType = targetTypeInst;
  7267. }
  7268. else
  7269. {
  7270. curTypeDef = mModule->mCurTypeInstance->mTypeDef;
  7271. targetTypeInst = mModule->mCurTypeInstance;
  7272. if (mModule->mCurMethodState == NULL)
  7273. {
  7274. checkNonStatic = false;
  7275. }
  7276. else
  7277. {
  7278. if (mModule->mCurMethodState->mMixinState != NULL)
  7279. {
  7280. targetTypeInst = mModule->mCurMethodState->mMixinState->mMixinMethodInstance->GetOwner();
  7281. curTypeDef = targetTypeInst->mTypeDef;
  7282. }
  7283. if (mModule->mCurMethodState->mTempKind != BfMethodState::TempKind_None)
  7284. {
  7285. checkNonStatic = mModule->mCurMethodState->mTempKind == BfMethodState::TempKind_NonStatic;
  7286. }
  7287. else
  7288. checkNonStatic = !mModule->mCurMethodInstance->mMethodDef->mIsStatic;
  7289. }
  7290. }
  7291. }
  7292. bool isIndirectMethodCall = false;
  7293. BfType* lookupType = targetType;
  7294. BfTypeInstance* lookupTypeInst = targetTypeInst;
  7295. if (targetType != NULL)
  7296. {
  7297. lookupType = BindGenericType(targetSrc, targetType);
  7298. if (lookupType->IsGenericParam())
  7299. lookupTypeInst = NULL;
  7300. }
  7301. BfMethodDef* methodDef = NULL;
  7302. BfTypeVector checkMethodGenericArguments;
  7303. BfTypeInstance* curTypeInst = targetTypeInst;
  7304. BfMethodMatcher methodMatcher(targetSrc, mModule, methodName, argValues.mResolvedArgs, methodGenericArguments);
  7305. methodMatcher.mOrigTarget = origTarget;
  7306. methodMatcher.mTarget = target;
  7307. methodMatcher.mCheckedKind = checkedKind;
  7308. methodMatcher.mAllowImplicitThis = allowImplicitThis;
  7309. methodMatcher.mAllowStatic = !target.mValue;
  7310. methodMatcher.mAllowNonStatic = !methodMatcher.mAllowStatic;
  7311. methodMatcher.mAutoFlushAmbiguityErrors = !wantsExtensionCheck;
  7312. if (allowImplicitThis)
  7313. {
  7314. if (mModule->mCurMethodState == NULL)
  7315. {
  7316. methodMatcher.mAllowStatic = true;
  7317. methodMatcher.mAllowNonStatic = false;
  7318. }
  7319. else if (mModule->mCurMethodState->mTempKind != BfMethodState::TempKind_None)
  7320. {
  7321. methodMatcher.mAllowNonStatic = mModule->mCurMethodState->mTempKind == BfMethodState::TempKind_NonStatic;
  7322. methodMatcher.mAllowStatic = true;
  7323. }
  7324. else
  7325. {
  7326. if (!mModule->mCurMethodInstance->mMethodDef->mIsStatic)
  7327. methodMatcher.mAllowNonStatic = true;
  7328. methodMatcher.mAllowStatic = true;
  7329. if (mModule->mCurMethodInstance->mMethodDef->mIsLocalMethod)
  7330. {
  7331. auto rootMethodState = mModule->mCurMethodState->GetRootMethodState();
  7332. methodMatcher.mAllowNonStatic = !rootMethodState->mMethodInstance->mMethodDef->mIsStatic;
  7333. }
  7334. }
  7335. }
  7336. if (methodName == BF_METHODNAME_CALCAPPEND)
  7337. methodMatcher.mMethodType = BfMethodType_CtorCalcAppend;
  7338. BF_ASSERT(methodMatcher.mBestMethodDef == NULL);
  7339. BfLocalMethod* matchedLocalMethod = NULL;
  7340. if (target.mType == NULL)
  7341. {
  7342. CheckLocalMethods(targetSrc, curTypeInst, methodName, methodMatcher, BfMethodType_Normal);
  7343. if (methodMatcher.mBestMethodDef == NULL)
  7344. methodMatcher.mBestMethodDef = methodMatcher.mBackupMethodDef;
  7345. if (methodMatcher.mBestMethodDef != NULL)
  7346. {
  7347. auto rootMethodState = mModule->mCurMethodState->GetRootMethodState();
  7348. auto methodDef = methodMatcher.mBestMethodDef;
  7349. if (mModule->mCompiler->mResolvePassData != NULL)
  7350. {
  7351. auto identifierNode = BfNodeDynCast<BfIdentifierNode>(targetSrc);
  7352. mModule->mCompiler->mResolvePassData->HandleLocalReference(identifierNode, curTypeInst->mTypeDef, rootMethodState->mMethodInstance->mMethodDef, ~methodDef->mIdx);
  7353. auto autoComplete = GetAutoComplete();
  7354. if ((autoComplete != NULL) && (autoComplete->IsAutocompleteNode(identifierNode)))
  7355. {
  7356. autoComplete->SetDefinitionLocation(methodDef->GetRefNode(), true);
  7357. if (autoComplete->mDefType == NULL)
  7358. {
  7359. autoComplete->mDefMethod = mModule->mCurMethodState->GetRootMethodState()->mMethodInstance->mMethodDef;
  7360. autoComplete->mDefType = curTypeDef;
  7361. autoComplete->mReplaceLocalId = ~methodDef->mIdx;
  7362. }
  7363. }
  7364. if ((autoComplete != NULL) && (autoComplete->mIsCapturingMethodMatchInfo))
  7365. {
  7366. BfAutoComplete::MethodMatchEntry methodMatchEntry;
  7367. methodMatchEntry.mMethodDef = methodDef;
  7368. methodMatchEntry.mTypeInstance = mModule->mCurTypeInstance;
  7369. methodMatchEntry.mCurMethodInstance = mModule->mCurMethodInstance;
  7370. autoComplete->mMethodMatchInfo->mInstanceList.push_back(methodMatchEntry);
  7371. }
  7372. }
  7373. if ((mModule->mCurMethodState->mClosureState != NULL) && (mModule->mCurMethodState->mClosureState->mCapturing))
  7374. {
  7375. auto methodInstance = mModule->GetRawMethodInstance(methodMatcher.mBestMethodTypeInstance, methodMatcher.mBestMethodDef);
  7376. if (methodInstance->mReturnType == NULL)
  7377. {
  7378. FinishDeferredEvals(argValues);
  7379. // If we are recursive then we won't even have a completed methodInstance yet to look at
  7380. return mModule->GetDefaultTypedValue(mModule->mContext->mBfObjectType);
  7381. }
  7382. }
  7383. }
  7384. }
  7385. if (methodMatcher.mBestMethodDef == NULL)
  7386. {
  7387. if (lookupTypeInst == NULL)
  7388. {
  7389. if ((lookupType != NULL) && (lookupType->IsConcreteInterfaceType()))
  7390. {
  7391. auto concreteInterfaceType = (BfConcreteInterfaceType*)lookupType;
  7392. lookupTypeInst = concreteInterfaceType->mInterface;
  7393. }
  7394. else if (isUnboundCall)
  7395. {
  7396. //auto resolvedType = mModule->ResolveGenericType(lookupType);
  7397. }
  7398. else if (lookupType->IsGenericParam())
  7399. {
  7400. auto genericParamTarget = (BfGenericParamType*)lookupType;
  7401. auto _HandleGenericParamInstance = [&](BfGenericParamInstance* genericParamInstance)
  7402. {
  7403. if (genericParamInstance->mTypeConstraint != NULL)
  7404. lookupTypeInst = genericParamInstance->mTypeConstraint->ToTypeInstance();
  7405. else
  7406. lookupTypeInst = mModule->mContext->mBfObjectType;
  7407. for (BfType* ifaceInst : genericParamInstance->mInterfaceConstraints)
  7408. {
  7409. if (ifaceInst->IsUnspecializedType())
  7410. ifaceInst = mModule->ResolveType(ifaceInst);
  7411. BfTypeInstance* typeInst = ifaceInst->ToTypeInstance();
  7412. BF_ASSERT(typeInst != NULL);
  7413. if (methodMatcher.CheckType(typeInst, target, false))
  7414. methodMatcher.mSelfType = lookupType;
  7415. }
  7416. };
  7417. auto genericParamInstance = mModule->GetGenericParamInstance(genericParamTarget);
  7418. _HandleGenericParamInstance(genericParamInstance);
  7419. // Check method generic constraints
  7420. if ((mModule->mCurMethodInstance != NULL) && (mModule->mCurMethodInstance->mIsUnspecialized) && (mModule->mCurMethodInstance->mMethodInfoEx != NULL))
  7421. {
  7422. for (int genericParamIdx = (int)mModule->mCurMethodInstance->mMethodInfoEx->mMethodGenericArguments.size();
  7423. genericParamIdx < mModule->mCurMethodInstance->mMethodInfoEx->mGenericParams.size(); genericParamIdx++)
  7424. {
  7425. auto genericParam = mModule->mCurMethodInstance->mMethodInfoEx->mGenericParams[genericParamIdx];
  7426. if (genericParam->mExternType == lookupType)
  7427. _HandleGenericParamInstance(genericParam);
  7428. }
  7429. }
  7430. }
  7431. }
  7432. if ((lookupTypeInst != NULL) && (!wantCtor))
  7433. {
  7434. methodMatcher.mBypassVirtual = bypassVirtual;
  7435. methodMatcher.CheckType(lookupTypeInst, target, false);
  7436. }
  7437. if ((lookupType != NULL) && (lookupType->IsGenericParam()))
  7438. {
  7439. //lookupType = mModule->ResolveGenericType(lookupType);
  7440. if (!lookupType->IsGenericParam())
  7441. {
  7442. target = MakeCallableTarget(targetSrc, target);
  7443. if (target)
  7444. {
  7445. lookupTypeInst = lookupType->ToTypeInstance();
  7446. }
  7447. }
  7448. }
  7449. }
  7450. bool isFailurePass = false;
  7451. if (methodMatcher.mBestMethodDef == NULL)
  7452. {
  7453. isFailurePass = true;
  7454. if (lookupTypeInst != NULL)
  7455. methodMatcher.CheckType(lookupTypeInst, target, true);
  7456. }
  7457. BfTypedValue staticResult;
  7458. methodMatcher.TryDevirtualizeCall(target, &origTarget, &staticResult);
  7459. if (staticResult)
  7460. return staticResult;
  7461. bypassVirtual |= methodMatcher.mBypassVirtual;
  7462. if (methodMatcher.mBestMethodDef != NULL)
  7463. {
  7464. curTypeInst = methodMatcher.mBestMethodTypeInstance;
  7465. methodDef = methodMatcher.mBestMethodDef;
  7466. }
  7467. if ((methodDef) && (!methodDef->mIsStatic) && (!target) && (allowImplicitThis))
  7468. {
  7469. target = mModule->GetThis();
  7470. }
  7471. // If we call "GetType" on a value type, statically determine the type rather than boxing and then dispatching
  7472. if ((methodDef) && (target) && (curTypeInst == mModule->mContext->mBfObjectType) &&
  7473. (methodDef->mName == "GetType") && (target.mType->IsValueType()) && (argValues.mArguments->IsEmpty()))
  7474. {
  7475. BfType* targetType = target.mType;
  7476. if (origTarget)
  7477. targetType = origTarget.mType;
  7478. auto typeType = mModule->ResolveTypeDef(mModule->mCompiler->mTypeTypeDef);
  7479. mModule->AddDependency(targetType, mModule->mCurTypeInstance, BfDependencyMap::DependencyFlag_ExprTypeReference);
  7480. return BfTypedValue(mModule->CreateTypeDataRef(targetType), typeType);
  7481. }
  7482. bool skipThis = false;
  7483. BfTypedValue fieldVal;
  7484. bool hasFieldVal = false;
  7485. // Fail, check for delegate field invocation
  7486. if ((methodDef == NULL) && ((methodGenericArguments == NULL) || (methodGenericArguments->size() == 0)))
  7487. {
  7488. // Check for payload enum initialization first
  7489. BfTypedValue enumResult;
  7490. BfTypeInstance* enumType = NULL;
  7491. if ((!target) && (target.HasType()) && (targetType->IsPayloadEnum()))
  7492. {
  7493. enumType = targetType->ToTypeInstance();
  7494. }
  7495. else if ((!target) && (!target.HasType()) && (mModule->mCurTypeInstance->IsPayloadEnum()))
  7496. {
  7497. enumType = mModule->mCurTypeInstance;
  7498. }
  7499. if (enumType != NULL)
  7500. {
  7501. enumResult = CheckEnumCreation(targetSrc, enumType, methodName, argValues);
  7502. }
  7503. if (enumResult)
  7504. {
  7505. if (mModule->mCompiler->WantsClassifyNode(targetSrc))
  7506. {
  7507. mModule->mCompiler->mResolvePassData->mSourceClassifier->SetElementType(targetSrc, BfSourceElementType_Normal);
  7508. }
  7509. return enumResult;
  7510. }
  7511. if (allowImplicitThis)
  7512. {
  7513. auto identifierNode = BfNodeDynCast<BfIdentifierNode>(targetSrc);
  7514. if (identifierNode != NULL)
  7515. fieldVal = LookupIdentifier(identifierNode);
  7516. }
  7517. else
  7518. {
  7519. SetAndRestoreValue<BfEvalExprFlags> prevFlags(mBfEvalExprFlags, (BfEvalExprFlags)(mBfEvalExprFlags & ~BfEvalExprFlags_AllowEnumId));
  7520. fieldVal = LookupField(targetSrc, target, methodName);
  7521. }
  7522. if (fieldVal)
  7523. {
  7524. hasFieldVal = true;
  7525. wantsExtensionCheck = !fieldVal.mType->IsDelegate() && !fieldVal.mType->IsFunction();
  7526. }
  7527. else if (mPropDef != NULL)
  7528. {
  7529. hasFieldVal = true;
  7530. BfMethodDef* matchedMethod = GetPropertyMethodDef(mPropDef, BfMethodType_PropertyGetter, mPropCheckedKind, mPropTarget);
  7531. if (matchedMethod != NULL)
  7532. {
  7533. auto getMethodInstance = mModule->GetRawMethodInstance(mPropTarget.mType->ToTypeInstance(), matchedMethod);
  7534. if ((getMethodInstance != NULL) &&
  7535. ((getMethodInstance->mReturnType->IsDelegate()) || (getMethodInstance->mReturnType->IsFunction())))
  7536. wantsExtensionCheck = false;
  7537. }
  7538. }
  7539. }
  7540. if ((!methodDef) && (!target.mValue))
  7541. {
  7542. // Check to see if we're constructing a struct via a call like: "Struct structVal = Struct()"
  7543. int wantNumGenericArgs = 0;
  7544. if ((methodGenericArguments != NULL) && (methodGenericArguments->size() > 0))
  7545. wantNumGenericArgs = (int)methodGenericArguments->size();
  7546. BfTypeInstance* resolvedTypeInstance = NULL;
  7547. if (wantCtor)
  7548. {
  7549. resolvedTypeInstance = targetTypeInst;
  7550. }
  7551. else if (targetType != NULL)
  7552. {
  7553. if (auto invocationExpr = BfNodeDynCast<BfInvocationExpression>(methodBoundExpr))
  7554. {
  7555. auto resolvedType = mModule->ResolveTypeRef(invocationExpr->mTarget, methodGenericArguments);
  7556. if (resolvedType != NULL)
  7557. resolvedTypeInstance = resolvedType->ToTypeInstance();
  7558. }
  7559. }
  7560. else
  7561. {
  7562. BfIdentifierNode* identifierNode = BfNodeDynCast<BfIdentifierNode>(targetSrc);
  7563. if (identifierNode != NULL)
  7564. {
  7565. SetAndRestoreValue<bool> prevIgnoreErrors(mModule->mIgnoreErrors, true);
  7566. BfType* refType;
  7567. if (methodGenericArguments != NULL)
  7568. {
  7569. refType = mModule->ResolveTypeRef(identifierNode, methodGenericArguments);
  7570. }
  7571. else
  7572. refType = mModule->ResolveTypeRef(identifierNode, NULL);
  7573. prevIgnoreErrors.Restore();
  7574. if ((refType != NULL) && (refType->IsPrimitiveType()))
  7575. {
  7576. FinishDeferredEvals(argValues);
  7577. if (argValues.mResolvedArgs.IsEmpty())
  7578. return mModule->GetDefaultTypedValue(refType);
  7579. if (argValues.mResolvedArgs.size() != 1)
  7580. {
  7581. mModule->Fail("Cast requires one parameter", targetSrc);
  7582. return BfTypedValue();
  7583. }
  7584. // This is just a primitive cast
  7585. auto& resolvedArg = argValues.mResolvedArgs[0];
  7586. BfTypedValue castedValue;
  7587. BfTypedValue castTarget = resolvedArg.mTypedValue;
  7588. if (resolvedArg.mTypedValue)
  7589. {
  7590. castTarget = mModule->LoadValue(castTarget);
  7591. castedValue = mModule->Cast(targetSrc, castTarget, refType, BfCastFlags_Explicit);
  7592. }
  7593. if (!castedValue)
  7594. castedValue = mModule->GetDefaultTypedValue(refType);
  7595. return castedValue;
  7596. }
  7597. if (refType != NULL)
  7598. {
  7599. resolvedTypeInstance = refType->ToTypeInstance();
  7600. if (refType->IsGenericParam())
  7601. {
  7602. CheckGenericCtor((BfGenericParamType*)refType, argValues, targetSrc);
  7603. return mModule->GetDefaultTypedValue(refType);
  7604. }
  7605. }
  7606. }
  7607. }
  7608. if (resolvedTypeInstance != NULL)
  7609. {
  7610. if ((!resolvedTypeInstance->IsStruct()) && (!resolvedTypeInstance->IsTypedPrimitive()))
  7611. {
  7612. if (mModule->PreFail())
  7613. mModule->Fail("Objects must be allocated through 'new' or 'scope'", targetSrc);
  7614. return BfTypedValue();
  7615. }
  7616. if (auto identifier = BfNodeDynCastExact<BfIdentifierNode>(targetSrc))
  7617. mModule->SetElementType(identifier, resolvedTypeInstance->IsEnum() ? BfSourceElementType_Type : BfSourceElementType_Struct);
  7618. if (mModule->mCompiler->mResolvePassData != NULL)
  7619. {
  7620. if (!BfNodeIsA<BfMemberReferenceExpression>(targetSrc))
  7621. mModule->mCompiler->mResolvePassData->HandleTypeReference(targetSrc, resolvedTypeInstance->mTypeDef);
  7622. }
  7623. BfTypedValue structInst;
  7624. mModule->PopulateType(resolvedTypeInstance);
  7625. if (!resolvedTypeInstance->IsValuelessType())
  7626. {
  7627. if ((mReceivingValue != NULL) && (mReceivingValue->mType == resolvedTypeInstance) && (mReceivingValue->IsAddr()))
  7628. {
  7629. structInst = *mReceivingValue;
  7630. mReceivingValue = NULL;
  7631. }
  7632. else
  7633. {
  7634. auto allocaInst = mModule->CreateAlloca(resolvedTypeInstance);
  7635. structInst = BfTypedValue(allocaInst, resolvedTypeInstance, true);
  7636. }
  7637. mResultIsTempComposite = true;
  7638. }
  7639. else
  7640. {
  7641. structInst = BfTypedValue(mModule->mBfIRBuilder->GetFakeVal(), resolvedTypeInstance, true);
  7642. }
  7643. mResultLocalVar = NULL;
  7644. mResultFieldInstance = NULL;
  7645. mResultLocalVarRefNode = NULL;
  7646. auto result = MatchConstructor(targetSrc, methodBoundExpr, structInst, resolvedTypeInstance, argValues, false, false);
  7647. if ((result) && (!result.mType->IsVoid()))
  7648. return result;
  7649. mModule->ValidateAllocation(resolvedTypeInstance, targetSrc);
  7650. mModule->AddDependency(resolvedTypeInstance, mModule->mCurTypeInstance, BfDependencyMap::DependencyFlag_LocalUsage);
  7651. if (mUsedAsStatement)
  7652. {
  7653. mModule->Warn(0, "Struct constructor being used as a statement", targetSrc);
  7654. }
  7655. return structInst;
  7656. }
  7657. }
  7658. // For for extensions in current type
  7659. if (wantsExtensionCheck)
  7660. {
  7661. auto checkTypeInst = mModule->mCurTypeInstance;
  7662. methodMatcher.mMethodType = BfMethodType_Extension;
  7663. if (methodMatcher.CheckType(checkTypeInst, BfTypedValue(), false, true))
  7664. {
  7665. isFailurePass = false;
  7666. curTypeInst = methodMatcher.mBestMethodTypeInstance;
  7667. methodDef = methodMatcher.mBestMethodDef;
  7668. }
  7669. }
  7670. // Look in globals. Always check for extension methods.
  7671. if ((methodDef == NULL) || (wantsExtensionCheck))
  7672. {
  7673. if (mModule->mContext->mCurTypeState != NULL)
  7674. {
  7675. BfGlobalLookup globalLookup;
  7676. globalLookup.mKind = BfGlobalLookup::Kind_Method;
  7677. globalLookup.mName = methodName;
  7678. mModule->PopulateGlobalContainersList(globalLookup);
  7679. for (auto& globalContainer : mModule->mContext->mCurTypeState->mGlobalContainers)
  7680. {
  7681. if (globalContainer.mTypeInst == NULL)
  7682. continue;
  7683. methodMatcher.mMethodType = wantsExtensionCheck ? BfMethodType_Extension : BfMethodType_Normal;
  7684. if (methodMatcher.CheckType(globalContainer.mTypeInst, BfTypedValue(), false))
  7685. {
  7686. isFailurePass = false;
  7687. curTypeInst = methodMatcher.mBestMethodTypeInstance;
  7688. methodDef = methodMatcher.mBestMethodDef;
  7689. }
  7690. }
  7691. }
  7692. }
  7693. // Look in static search. Always check for extension methods.
  7694. if ((methodDef == NULL) || (wantsExtensionCheck))
  7695. {
  7696. BfStaticSearch* staticSearch = mModule->GetStaticSearch();
  7697. if (staticSearch != NULL)
  7698. {
  7699. for (auto typeInst : staticSearch->mStaticTypes)
  7700. {
  7701. methodMatcher.mMethodType = wantsExtensionCheck ? BfMethodType_Extension : BfMethodType_Normal;
  7702. if (methodMatcher.CheckType(typeInst, BfTypedValue(), false))
  7703. {
  7704. isFailurePass = false;
  7705. curTypeInst = methodMatcher.mBestMethodTypeInstance;
  7706. methodDef = methodMatcher.mBestMethodDef;
  7707. }
  7708. }
  7709. }
  7710. }
  7711. if ((methodDef == NULL) && (hasFieldVal))
  7712. {
  7713. if (mPropDef != NULL)
  7714. fieldVal = GetResult();
  7715. if (fieldVal)
  7716. {
  7717. if (fieldVal.mType->IsGenericParam())
  7718. {
  7719. bool delegateFailed = true;
  7720. auto genericParamInstance = mModule->GetGenericParamInstance((BfGenericParamType*)fieldVal.mType);
  7721. BfTypeInstance* typeInstConstraint = NULL;
  7722. if (genericParamInstance->mTypeConstraint != NULL)
  7723. typeInstConstraint = genericParamInstance->mTypeConstraint->ToTypeInstance();
  7724. if ((typeInstConstraint != NULL) &&
  7725. ((typeInstConstraint->IsInstanceOf(mModule->mCompiler->mDelegateTypeDef)) || (typeInstConstraint->IsInstanceOf(mModule->mCompiler->mFunctionTypeDef))))
  7726. {
  7727. MarkResultUsed();
  7728. if (argValues.mArguments->size() == 1)
  7729. {
  7730. BfExprEvaluator exprEvaluator(mModule);
  7731. exprEvaluator.mBfEvalExprFlags = BfEvalExprFlags_AllowParamsExpr;
  7732. exprEvaluator.Evaluate((*argValues.mArguments)[0]);
  7733. if ((mModule->mCurMethodState != NULL) && (exprEvaluator.mResultLocalVar != NULL) && (exprEvaluator.mResultLocalVarRefNode != NULL))
  7734. {
  7735. auto localVar = exprEvaluator.mResultLocalVar;
  7736. if ((localVar->mCompositeCount >= 0) && (localVar->mResolvedType == fieldVal.mType))
  7737. {
  7738. delegateFailed = false;
  7739. if (mModule->mCurMethodInstance->mIsUnspecialized)
  7740. {
  7741. auto retTypeType = mModule->CreateModifiedTypeType(fieldVal.mType, BfToken_RetType);
  7742. return mModule->GetFakeTypedValue(retTypeType);
  7743. }
  7744. }
  7745. }
  7746. }
  7747. if (delegateFailed)
  7748. {
  7749. mModule->Fail(StrFormat("Generic delegates can only be invoked with 'params %s' composite parameters", mModule->TypeToString(fieldVal.mType).c_str()), targetSrc);
  7750. return BfTypedValue();
  7751. }
  7752. }
  7753. }
  7754. if (fieldVal.mType->IsTypeInstance())
  7755. {
  7756. prevBindResult.Restore();
  7757. auto fieldTypeInst = fieldVal.mType->ToTypeInstance();
  7758. MarkResultUsed();
  7759. if (mFunctionBindResult != NULL)
  7760. {
  7761. mFunctionBindResult->mOrigTarget = BfTypedValue();
  7762. }
  7763. return MatchMethod(targetSrc, NULL, fieldVal, false, false, "Invoke", argValues, methodGenericArguments, checkedKind);
  7764. }
  7765. if (fieldVal.mType->IsVar())
  7766. {
  7767. FinishDeferredEvals(argValues);
  7768. return BfTypedValue(mModule->GetDefaultValue(fieldVal.mType), fieldVal.mType);
  7769. }
  7770. if (fieldVal.mType->IsGenericParam())
  7771. {
  7772. auto genericParam = mModule->GetGenericParamInstance((BfGenericParamType*)fieldVal.mType);
  7773. BfType* typeConstraint = genericParam->mTypeConstraint;
  7774. if ((mModule->mCurMethodInstance != NULL) && (mModule->mCurMethodInstance->mIsUnspecialized) && (mModule->mCurMethodInstance->mMethodInfoEx != NULL))
  7775. {
  7776. for (int genericParamIdx = (int)mModule->mCurMethodInstance->mMethodInfoEx->mMethodGenericArguments.size();
  7777. genericParamIdx < mModule->mCurMethodInstance->mMethodInfoEx->mGenericParams.size(); genericParamIdx++)
  7778. {
  7779. auto genericParam = mModule->mCurMethodInstance->mMethodInfoEx->mGenericParams[genericParamIdx];
  7780. if ((genericParam->mExternType == fieldVal.mType) && (genericParam->mTypeConstraint != NULL))
  7781. typeConstraint = genericParam->mTypeConstraint;
  7782. }
  7783. }
  7784. if ((typeConstraint != NULL) &&
  7785. ((typeConstraint->IsDelegate()) || (typeConstraint->IsFunction())))
  7786. {
  7787. BfMethodInstance* invokeMethodInstance = mModule->GetRawMethodInstanceAtIdx(typeConstraint->ToTypeInstance(), 0, "Invoke");
  7788. methodDef = invokeMethodInstance->mMethodDef;
  7789. methodMatcher.mBestMethodInstance = invokeMethodInstance;
  7790. methodMatcher.mBestMethodTypeInstance = invokeMethodInstance->GetOwner();
  7791. methodMatcher.mBestMethodDef = invokeMethodInstance->mMethodDef;
  7792. target = mModule->GetDefaultTypedValue(methodMatcher.mBestMethodTypeInstance);
  7793. isFailurePass = false;
  7794. isIndirectMethodCall = true;
  7795. }
  7796. }
  7797. else if (fieldVal.mType->IsMethodRef())
  7798. {
  7799. auto functionBindResults = prevBindResult.mPrevVal;
  7800. if (functionBindResults != NULL)
  7801. {
  7802. functionBindResults->mOrigTarget = fieldVal;
  7803. }
  7804. origTarget = fieldVal;
  7805. auto methodRefType = (BfMethodRefType*)fieldVal.mType;
  7806. BfMethodInstance* methodInstance = methodRefType->mMethodRef;
  7807. methodDef = methodInstance->mMethodDef;
  7808. if (methodDef->mIsLocalMethod)
  7809. {
  7810. methodMatcher.mBestMethodInstance = mModule->ReferenceExternalMethodInstance(methodInstance);
  7811. }
  7812. else
  7813. {
  7814. BfTypeVector methodGenericArguments;
  7815. if (methodInstance->mMethodInfoEx != NULL)
  7816. methodGenericArguments = methodInstance->mMethodInfoEx->mMethodGenericArguments;
  7817. methodMatcher.mBestMethodInstance = mModule->GetMethodInstance(methodInstance->GetOwner(), methodInstance->mMethodDef, methodGenericArguments);
  7818. }
  7819. methodMatcher.mBestMethodTypeInstance = methodInstance->GetOwner();
  7820. if (methodInstance->HasThis())
  7821. {
  7822. bool failed = false;
  7823. target = DoImplicitArgCapture(targetSrc, methodInstance, -1, failed, BfImplicitParamKind_General, origTarget);
  7824. }
  7825. else if (!methodDef->mIsStatic)
  7826. {
  7827. auto thisType = methodInstance->GetParamType(-1);
  7828. BF_ASSERT(thisType->IsValuelessType());
  7829. target = BfTypedValue(mModule->mBfIRBuilder->GetFakeVal(), methodMatcher.mBestMethodTypeInstance);
  7830. }
  7831. else
  7832. target = BfTypedValue(methodMatcher.mBestMethodTypeInstance);
  7833. methodMatcher.mBypassVirtual = true;
  7834. bypassVirtual = true;
  7835. isFailurePass = false;
  7836. isIndirectMethodCall = true;
  7837. }
  7838. if (methodDef == NULL)
  7839. {
  7840. mModule->Fail(StrFormat("Cannot perform invocation on type '%s'", mModule->TypeToString(fieldVal.mType).c_str()), targetSrc);
  7841. return BfTypedValue();
  7842. }
  7843. }
  7844. }
  7845. // This will flush out any new ambiguity errors from extension methods
  7846. methodMatcher.FlushAmbiguityError();
  7847. if (methodDef == NULL)
  7848. {
  7849. FinishDeferredEvals(argValues);
  7850. auto compiler = mModule->mCompiler;
  7851. if ((compiler->IsAutocomplete()) && (compiler->mResolvePassData->mAutoComplete->CheckFixit(targetSrc)))
  7852. {
  7853. mModule->CheckTypeRefFixit(targetSrc);
  7854. bool wantStatic = !target.mValue;
  7855. if ((targetType == NULL) && (allowImplicitThis))
  7856. {
  7857. targetType = mModule->mCurTypeInstance;
  7858. if (mModule->mCurMethodInstance != NULL)
  7859. wantStatic = mModule->mCurMethodInstance->mMethodDef->mIsStatic;
  7860. }
  7861. if (targetType != NULL)
  7862. {
  7863. auto typeInst = targetType->ToTypeInstance();
  7864. if ((targetType != NULL) && (!methodName.IsEmpty()))
  7865. {
  7866. BfTypeVector paramTypes;
  7867. for (int argIdx = 0; argIdx < (int)argValues.mResolvedArgs.size(); argIdx++)
  7868. {
  7869. auto& resolvedArg = argValues.mResolvedArgs[argIdx];
  7870. paramTypes.Add(resolvedArg.mTypedValue.mType);
  7871. }
  7872. autoComplete->FixitAddMethod(typeInst, methodName, mExpectingType, paramTypes, wantStatic);
  7873. }
  7874. }
  7875. }
  7876. if (methodName.IsEmpty())
  7877. {
  7878. // Would have caused a parsing error
  7879. }
  7880. else if (target.mType != NULL)
  7881. {
  7882. if (mModule->PreFail())
  7883. {
  7884. if ((origTarget.mType->IsPointer()) && (origTarget.mType->GetUnderlyingType()->IsObjectOrInterface()))
  7885. {
  7886. mModule->Fail(StrFormat("Methods cannot be called on type '%s' because the type is a pointer to a reference type (ie: a double-reference).",
  7887. mModule->TypeToString(origTarget.mType).c_str()), targetSrc);
  7888. }
  7889. else
  7890. mModule->Fail(StrFormat("Method '%s' does not exist in type '%s'", methodName.c_str(), mModule->TypeToString(target.mType).c_str()), targetSrc);
  7891. }
  7892. }
  7893. else
  7894. {
  7895. if (mModule->PreFail())
  7896. mModule->Fail(StrFormat("Method '%s' does not exist", methodName.c_str()), targetSrc);
  7897. }
  7898. return BfTypedValue();
  7899. }
  7900. if ((prevBindResult.mPrevVal != NULL) && (methodMatcher.mMethodCheckCount > 1))
  7901. prevBindResult.mPrevVal->mCheckedMultipleMethods = true;
  7902. BfType* overrideReturnType = NULL;
  7903. BfModuleMethodInstance moduleMethodInstance = GetSelectedMethod(targetSrc, curTypeInst, methodDef, methodMatcher, &overrideReturnType);
  7904. if ((mModule->mAttributeState != NULL) && ((mModule->mAttributeState->mFlags & (BfAttributeState::Flag_StopOnError | BfAttributeState::Flag_HadError)) ==
  7905. (BfAttributeState::Flag_StopOnError | BfAttributeState::Flag_HadError)))
  7906. {
  7907. FinishDeferredEvals(argValues);
  7908. return BfTypedValue();
  7909. }
  7910. if ((moduleMethodInstance.mMethodInstance != NULL) && (!mModule->CheckUseMethodInstance(moduleMethodInstance.mMethodInstance, targetSrc)))
  7911. {
  7912. FinishDeferredEvals(argValues);
  7913. return BfTypedValue();
  7914. }
  7915. if ((mModule->mCurMethodInstance != NULL) && (mModule->mCurMethodInstance->mIsUnspecialized))
  7916. {
  7917. if (methodMatcher.mHasVarArguments)
  7918. {
  7919. BfType* retType = mModule->GetPrimitiveType(BfTypeCode_Var);
  7920. if ((!methodMatcher.mHadVarConflictingReturnType) && (methodMatcher.mBestRawMethodInstance != NULL) && (!methodMatcher.mBestRawMethodInstance->mReturnType->IsUnspecializedTypeVariation()) &&
  7921. (prevBindResult.mPrevVal == NULL))
  7922. {
  7923. if ((!methodMatcher.mBestRawMethodInstance->mReturnType->IsGenericParam()) ||
  7924. (((BfGenericParamType*)methodMatcher.mBestRawMethodInstance->mReturnType)->mGenericParamKind != BfGenericParamKind_Method))
  7925. retType = methodMatcher.mBestRawMethodInstance->mReturnType;
  7926. }
  7927. return mModule->GetDefaultTypedValue(retType, true, BfDefaultValueKind_Addr);
  7928. }
  7929. }
  7930. if ((bypassVirtual) && (!target.mValue) && (target.mType->IsInterface()))
  7931. {
  7932. target = mModule->GetThis();
  7933. }
  7934. if (!moduleMethodInstance)
  7935. {
  7936. FinishDeferredEvals(argValues);
  7937. if (mModule->IsInUnspecializedGeneric())
  7938. return mModule->GetDefaultTypedValue(mModule->GetPrimitiveType(BfTypeCode_Var));
  7939. return BfTypedValue();
  7940. }
  7941. bool isSkipCall = moduleMethodInstance.mMethodInstance->IsSkipCall(bypassVirtual);
  7942. if ((moduleMethodInstance.mMethodInstance->IsOrInUnspecializedVariation()) && (!mModule->mBfIRBuilder->mIgnoreWrites))
  7943. {
  7944. // Invalid methods such as types with a HasVar tuple generic arg will be marked as mIsUnspecializedVariation and shouldn't actually be called
  7945. FinishDeferredEvals(argValues);
  7946. return mModule->GetDefaultTypedValue(moduleMethodInstance.mMethodInstance->mReturnType, true, BfDefaultValueKind_Addr);
  7947. }
  7948. if (methodDef->IsEmptyPartial())
  7949. {
  7950. // Ignore call
  7951. return mModule->GetDefaultTypedValue(moduleMethodInstance.mMethodInstance->mReturnType, true, BfDefaultValueKind_Addr);
  7952. }
  7953. if ((moduleMethodInstance.mMethodInstance->mMethodDef->mIsStatic) && (moduleMethodInstance.mMethodInstance->GetOwner()->IsInterface()))
  7954. {
  7955. bool isConstrained = false;
  7956. if (target.mType != NULL)
  7957. isConstrained = target.mType->IsGenericParam();
  7958. if ((target.mType == NULL) && ((mModule->mCurMethodInstance->mIsForeignMethodDef) || (mModule->mCurTypeInstance->IsInterface())))
  7959. isConstrained = true;
  7960. // If mIgnoreWrites is off then we skip devirtualization, so allow this
  7961. if ((target.mType != NULL) && (!target.mType->IsInterface()) && (mModule->mBfIRBuilder->mIgnoreWrites))
  7962. isConstrained = true;
  7963. if (!isConstrained)
  7964. {
  7965. if (mModule->mCurTypeInstance->IsInterface())
  7966. {
  7967. if (methodDef->mBody == NULL)
  7968. mModule->Fail(StrFormat("Interface method '%s' must provide a body to be explicitly invoked", mModule->MethodToString(moduleMethodInstance.mMethodInstance).c_str()), targetSrc);
  7969. }
  7970. else
  7971. 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);
  7972. FinishDeferredEvals(argValues);
  7973. return mModule->GetDefaultTypedValue(moduleMethodInstance.mMethodInstance->mReturnType, true, BfDefaultValueKind_Addr);
  7974. }
  7975. }
  7976. // 'base' could really mean 'this' if we're in an extension
  7977. if ((target.IsBase()) && (targetTypeInst == mModule->mCurTypeInstance))
  7978. target.ToThis();
  7979. else
  7980. MakeBaseConcrete(target);
  7981. BfType* callTargetType = curTypeInst;
  7982. if (methodDef->mMethodType == BfMethodType_Extension)
  7983. {
  7984. callTargetType = moduleMethodInstance.mMethodInstance->GetParamType(0);
  7985. if ((callTargetType->IsRef()) && (target.IsAddr()) && (!target.IsReadOnly()) && (target.mType->IsValueType()))
  7986. {
  7987. target = BfTypedValue(target.mValue, mModule->CreateRefType(target.mType));
  7988. }
  7989. }
  7990. BfTypedValue callTarget;
  7991. if (isSkipCall)
  7992. {
  7993. // Just a fake value so we can continue on without generating any code (boxing, conversion, etc)
  7994. if (target)
  7995. {
  7996. if (((target.mType->IsComposite()) || (target.mType->IsTypedPrimitive())))
  7997. {
  7998. if ((moduleMethodInstance.mMethodInstance->mMethodDef->mIsMutating) &&
  7999. ((target.IsReadOnly()) || (!target.IsAddr())))
  8000. {
  8001. String err = StrFormat("call mutating method '%s' on", mModule->MethodToString(moduleMethodInstance.mMethodInstance).c_str());
  8002. CheckModifyResult(target, targetSrc, err.c_str());
  8003. }
  8004. }
  8005. callTarget = BfTypedValue(mModule->mBfIRBuilder->GetFakeVal(), targetTypeInst);
  8006. }
  8007. }
  8008. else if (targetTypeInst == callTargetType)
  8009. {
  8010. if ((target) && (methodDef->HasNoThisSplat()))
  8011. {
  8012. callTarget = mModule->MakeAddressable(target);
  8013. }
  8014. else
  8015. callTarget = target;
  8016. if ((callTarget) && (moduleMethodInstance.mMethodInstance->GetOwner()->IsInterface()))
  8017. {
  8018. auto wantThis = moduleMethodInstance.mMethodInstance->GetParamType(-1);
  8019. if ((callTarget.mType != wantThis) && (wantThis->IsInterface()))
  8020. callTarget = mModule->Cast(targetSrc, callTarget, wantThis, BfCastFlags_Explicit);
  8021. }
  8022. }
  8023. else if (target)
  8024. {
  8025. if (methodMatcher.mFakeConcreteTarget)
  8026. {
  8027. BF_ASSERT(callTargetType->IsInterface());
  8028. callTarget = mModule->GetDefaultTypedValue(mModule->CreateConcreteInterfaceType(callTargetType->ToTypeInstance()));
  8029. }
  8030. else if (((target.mType->IsGenericParam()) || (target.mType->IsConcreteInterfaceType())) && (callTargetType->IsInterface()))
  8031. {
  8032. // Leave as generic
  8033. callTarget = target;
  8034. }
  8035. else
  8036. {
  8037. bool handled = false;
  8038. if ((target.mType->IsTypedPrimitive()) && (callTargetType->IsTypedPrimitive()))
  8039. {
  8040. handled = true;
  8041. callTarget = target;
  8042. }
  8043. else if ((target.mType->IsStructOrStructPtr()) || (target.mType->IsTypedPrimitive()))
  8044. {
  8045. //BF_ASSERT(target.IsAddr());
  8046. if (callTargetType->IsObjectOrInterface())
  8047. {
  8048. // Box it
  8049. callTarget = mModule->Cast(targetSrc, target, callTargetType, BfCastFlags_Explicit);
  8050. handled = true;
  8051. }
  8052. else
  8053. {
  8054. //BF_ASSERT(target.IsAddr() || target.IsSplat() || target.mType->IsPointer());
  8055. }
  8056. }
  8057. else
  8058. target = mModule->LoadValue(target);
  8059. if (!handled)
  8060. {
  8061. // Could we have just unconditionally done this?
  8062. callTarget = mModule->Cast(targetSrc, target, callTargetType, BfCastFlags_Explicit);
  8063. }
  8064. }
  8065. }
  8066. if (isFailurePass)
  8067. {
  8068. BfError* error;
  8069. if (methodMatcher.mMatchFailKind == BfMethodMatcher::MatchFailKind_CheckedMismatch)
  8070. 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);
  8071. else
  8072. error = mModule->Fail(StrFormat("'%s' is inaccessible due to its protection level", mModule->MethodToString(moduleMethodInstance.mMethodInstance).c_str()), targetSrc);
  8073. if (error != NULL)
  8074. {
  8075. if ((error != NULL) && (moduleMethodInstance.mMethodInstance->mMethodDef->mMethodDeclaration != NULL))
  8076. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("See method declaration"), moduleMethodInstance.mMethodInstance->mMethodDef->GetRefNode());
  8077. }
  8078. }
  8079. if ((mModule->mCompiler->mResolvePassData != NULL) && (methodDef != NULL))
  8080. {
  8081. auto identifierNode = BfNodeDynCast<BfIdentifierNode>(targetSrc);
  8082. while (auto qualifiedNameNode = BfNodeDynCast<BfQualifiedNameNode>(identifierNode))
  8083. identifierNode = qualifiedNameNode->mRight;
  8084. if ((identifierNode != NULL) && (methodDef->mIdx >= 0) && (!isIndirectMethodCall) &&
  8085. ((targetTypeInst == NULL) || (!targetTypeInst->IsDelegateOrFunction())))
  8086. {
  8087. mModule->mCompiler->mResolvePassData->HandleMethodReference(identifierNode, moduleMethodInstance.mMethodInstance->GetOwner()->mTypeDef, methodDef);
  8088. auto autoComplete = GetAutoComplete();
  8089. if ((autoComplete != NULL) && (autoComplete->IsAutocompleteNode(identifierNode)))
  8090. {
  8091. autoComplete->SetDefinitionLocation(methodDef->GetRefNode(), true);
  8092. int virtualIdx = moduleMethodInstance.mMethodInstance->mVirtualTableIdx;
  8093. if ((autoComplete->mResolveType == BfResolveType_GoToDefinition) &&
  8094. (virtualIdx != -1) && (targetTypeInst != NULL) && (!targetTypeInst->IsStruct()) && (!targetTypeInst->IsTypedPrimitive()) && (!targetTypeInst->IsInterface()) &&
  8095. // 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
  8096. (targetTypeInst->mVirtualMethodTable.size() != 0))
  8097. {
  8098. auto methodEntry = targetTypeInst->mVirtualMethodTable[virtualIdx];
  8099. if (methodEntry.mImplementingMethod.mMethodNum != -1)
  8100. {
  8101. BfMethodInstance* callingMethodInstance = methodEntry.mImplementingMethod;
  8102. if (callingMethodInstance != NULL)
  8103. {
  8104. auto callingMethodDef = callingMethodInstance->mMethodDef;
  8105. auto callingMethodDeclaration = callingMethodDef->GetMethodDeclaration();
  8106. if ((callingMethodDeclaration != NULL) && (callingMethodDeclaration->mNameNode != NULL))
  8107. autoComplete->SetDefinitionLocation(callingMethodDeclaration->mNameNode, true);
  8108. }
  8109. }
  8110. }
  8111. if (autoComplete->mDefType == NULL)
  8112. {
  8113. autoComplete->mDefMethod = methodDef;
  8114. autoComplete->mDefType = moduleMethodInstance.mMethodInstance->GetOwner()->mTypeDef;
  8115. }
  8116. if (autoComplete->mResolveType == BfResolveType_GetResultString)
  8117. {
  8118. autoComplete->mResultString = ":";
  8119. autoComplete->mResultString += mModule->MethodToString(moduleMethodInstance.mMethodInstance);
  8120. auto methodDecl = moduleMethodInstance.mMethodInstance->mMethodDef->GetMethodDeclaration();
  8121. if ((methodDecl != NULL) && (methodDecl->mDocumentation != NULL))
  8122. {
  8123. autoComplete->mResultString += "\x03";
  8124. methodDecl->mDocumentation->GetDocString(autoComplete->mResultString);
  8125. }
  8126. }
  8127. }
  8128. }
  8129. }
  8130. // This was causing forward-backward-forward steps when we just used 'targetSrc'. Using closeParen is undesirable because most of the time
  8131. // we DO just want it to just go to the targetSrc... do we even need this?
  8132. /*if (auto invokeExpr = BfNodeDynCast<BfInvocationExpression>(targetSrc->mParent))
  8133. {
  8134. // We set the srcPos to the close paren right before the call so we keep a forward progression of src positions in the case
  8135. // where some of the params are method calls and such
  8136. if (invokeExpr->mCloseParen != NULL)
  8137. mModule->UpdateExprSrcPos(invokeExpr->mCloseParen);
  8138. else
  8139. mModule->UpdateExprSrcPos(targetSrc);
  8140. }
  8141. else
  8142. mModule->UpdateExprSrcPos(targetSrc);*/
  8143. if (!mModule->mBfIRBuilder->mIgnoreWrites)
  8144. {
  8145. //BF_ASSERT(!callTarget.mValue.IsFake());
  8146. }
  8147. prevBindResult.Restore();
  8148. // Check mut
  8149. if ((callTarget.mType != NULL) &&
  8150. (callTarget.mType->IsGenericParam()) &&
  8151. ((!callTarget.IsAddr()) || (callTarget.IsReadOnly())) &&
  8152. (callTarget.mKind != BfTypedValueKind_MutableValue) &&
  8153. (moduleMethodInstance.mMethodInstance->mMethodDef->mIsMutating))
  8154. {
  8155. auto genericParamInstance = mModule->GetGenericParamInstance((BfGenericParamType*)callTarget.mType);
  8156. bool needsMut = true;
  8157. if ((genericParamInstance->mGenericParamFlags & (BfGenericParamFlag_StructPtr | BfGenericParamFlag_Class | BfGenericParamFlag_Var)) != 0)
  8158. needsMut = false;
  8159. if (genericParamInstance->mTypeConstraint != NULL)
  8160. {
  8161. auto typeConstaintTypeInstance = genericParamInstance->mTypeConstraint->ToTypeInstance();
  8162. if ((typeConstaintTypeInstance != NULL) && (!typeConstaintTypeInstance->IsComposite()))
  8163. needsMut = false;
  8164. }
  8165. if ((mFunctionBindResult != NULL) && (mFunctionBindResult->mSkipMutCheck))
  8166. needsMut = false;
  8167. if (needsMut)
  8168. {
  8169. String err = StrFormat("call mutating method '%s' on", mModule->MethodToString(moduleMethodInstance.mMethodInstance).c_str());
  8170. CheckModifyResult(callTarget, targetSrc, err.c_str(), true);
  8171. }
  8172. }
  8173. // Check mut on interface
  8174. if ((callTarget.mType != NULL) &&
  8175. (callTarget.mType->IsInterface()) &&
  8176. (target.IsThis()) &&
  8177. (mModule->mCurTypeInstance) &&
  8178. (!mModule->mCurMethodInstance->mMethodDef->mIsMutating) &&
  8179. (methodDef->mIsMutating))
  8180. {
  8181. mModule->Fail(StrFormat("Cannot call mutating method '%s' within default interface method '%s'. Consider adding 'mut' specifier to this method.",
  8182. mModule->MethodToString(moduleMethodInstance.mMethodInstance).c_str(), mModule->MethodToString(mModule->mCurMethodInstance).c_str()), targetSrc);
  8183. }
  8184. BfTypedValue result;
  8185. BfTypedValue argCascade;
  8186. //
  8187. {
  8188. SetAndRestoreValue<BfEvalExprFlags> prevEvalExprFlag(mBfEvalExprFlags);
  8189. if ((mModule->mAttributeState != NULL) && (mModule->mAttributeState->mCustomAttributes != NULL) && (mModule->mAttributeState->mCustomAttributes->Contains(mModule->mCompiler->mConstEvalAttributeTypeDef)))
  8190. {
  8191. mModule->mAttributeState->mUsed = true;
  8192. mBfEvalExprFlags = (BfEvalExprFlags)(mBfEvalExprFlags | BfEvalExprFlags_Comptime);
  8193. }
  8194. else if ((moduleMethodInstance.mMethodInstance->mComptimeFlags & BfComptimeFlag_ConstEval) != 0)
  8195. {
  8196. mBfEvalExprFlags = (BfEvalExprFlags)(mBfEvalExprFlags | BfEvalExprFlags_Comptime);
  8197. }
  8198. else if (((moduleMethodInstance.mMethodInstance->mComptimeFlags & BfComptimeFlag_Comptime) != 0) && (!mModule->mIsComptimeModule))
  8199. {
  8200. if ((mModule->mCurMethodInstance == NULL) || (mModule->mCurMethodInstance->mComptimeFlags == BfComptimeFlag_None))
  8201. mBfEvalExprFlags = (BfEvalExprFlags)(mBfEvalExprFlags | BfEvalExprFlags_Comptime);
  8202. }
  8203. if (((moduleMethodInstance.mMethodInstance->mComptimeFlags & BfComptimeFlag_OnlyFromComptime) != 0) &&
  8204. ((mBfEvalExprFlags & BfEvalExprFlags_Comptime) != 0) &&
  8205. ((mModule->mCurMethodInstance == NULL) || (mModule->mCurMethodInstance->mComptimeFlags == BfComptimeFlag_None)) &&
  8206. (!mModule->mIsComptimeModule))
  8207. {
  8208. 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);
  8209. }
  8210. BfCreateCallFlags subCallFlags = BfCreateCallFlags_None;
  8211. if (bypassVirtual)
  8212. subCallFlags = (BfCreateCallFlags)(subCallFlags | BfCreateCallFlags_BypassVirtual);
  8213. if (skipThis)
  8214. subCallFlags = (BfCreateCallFlags)(subCallFlags | BfCreateCallFlags_SkipThis);
  8215. result = CreateCall(targetSrc, callTarget, origTarget, methodDef, moduleMethodInstance, subCallFlags, argValues.mResolvedArgs, &argCascade);
  8216. }
  8217. if (overrideReturnType != NULL)
  8218. {
  8219. BF_ASSERT(moduleMethodInstance.mMethodInstance->mIsUnspecializedVariation);
  8220. result = mModule->GetDefaultTypedValue(overrideReturnType, false, BfDefaultValueKind_Addr);
  8221. }
  8222. if (result)
  8223. {
  8224. if (result.mType->IsRef())
  8225. result = mModule->RemoveRef(result);
  8226. }
  8227. PerformCallChecks(moduleMethodInstance.mMethodInstance, targetSrc);
  8228. if (result)
  8229. {
  8230. bool discardedReturnValue = mUsedAsStatement;
  8231. if (discardedReturnValue)
  8232. {
  8233. auto _ShowDiscardWaring = [&](const String& text, BfCustomAttributes* customAttributes, BfIRConstHolder* constHolder, BfAstNode* refNode)
  8234. {
  8235. if (customAttributes != NULL)
  8236. {
  8237. auto customAttribute = customAttributes->Get(mModule->mCompiler->mNoDiscardAttributeTypeDef);
  8238. if (!customAttribute->mCtorArgs.IsEmpty())
  8239. {
  8240. String* str = mModule->GetStringPoolString(customAttribute->mCtorArgs[0], constHolder);
  8241. if ((str != NULL) && (!str->IsEmpty()))
  8242. {
  8243. mModule->Warn(0, text + ": " + *str, targetSrc);
  8244. return;
  8245. }
  8246. }
  8247. }
  8248. mModule->Warn(0, text, targetSrc);
  8249. };
  8250. bool showedWarning = false;
  8251. if (moduleMethodInstance.mMethodInstance->mMethodDef->mIsNoDiscard)
  8252. {
  8253. _ShowDiscardWaring("Discarding return value of method with [NoDiscard] attribute", moduleMethodInstance.mMethodInstance->GetCustomAttributes(),
  8254. moduleMethodInstance.mMethodInstance->GetOwner()->mConstHolder, targetSrc);
  8255. showedWarning = true;
  8256. }
  8257. auto typeInst = result.mType->ToTypeInstance();
  8258. if (typeInst != NULL)
  8259. {
  8260. if ((typeInst->mTypeDef->mIsNoDiscard) && (!showedWarning))
  8261. {
  8262. _ShowDiscardWaring("Discarding return value whose type has [NoDiscard] attribute", typeInst->mCustomAttributes, typeInst->mConstHolder, targetSrc);
  8263. }
  8264. BfModuleMethodInstance moduleMethodInstance = mModule->GetMethodByName(typeInst, "ReturnValueDiscarded", 0, true);
  8265. if (moduleMethodInstance)
  8266. {
  8267. auto wasGetDefinition = (autoComplete != NULL) && (autoComplete->mIsGetDefinition);
  8268. if (wasGetDefinition)
  8269. autoComplete->mIsGetDefinition = false;
  8270. result = mModule->MakeAddressable(result);
  8271. BfResolvedArgs resolvedArgs;
  8272. MatchMethod(targetSrc, NULL, result, false, false, "ReturnValueDiscarded", resolvedArgs, NULL);
  8273. if (wasGetDefinition)
  8274. autoComplete->mIsGetDefinition = true;
  8275. }
  8276. }
  8277. }
  8278. }
  8279. if (argCascade)
  8280. {
  8281. if (argCascade.mType->IsRef())
  8282. argCascade = mModule->RemoveRef(argCascade);
  8283. result = argCascade;
  8284. }
  8285. if (result)
  8286. {
  8287. if (result.mType->IsSelf())
  8288. {
  8289. if (methodMatcher.mSelfType != NULL)
  8290. {
  8291. BF_ASSERT(mModule->IsInGeneric());
  8292. result = mModule->GetDefaultTypedValue(methodMatcher.mSelfType);
  8293. }
  8294. else
  8295. {
  8296. // Will be an error
  8297. result = mModule->GetDefaultTypedValue(methodMatcher.mBestMethodTypeInstance);
  8298. }
  8299. }
  8300. }
  8301. return result;
  8302. }
  8303. void BfExprEvaluator::LookupQualifiedName(BfQualifiedNameNode* nameNode, bool ignoreInitialError, bool* hadError)
  8304. {
  8305. BfIdentifierNode* nameLeft = nameNode->mLeft;
  8306. BfIdentifierNode* nameRight = nameNode->mRight;
  8307. StringT<64> fieldName;
  8308. if (nameNode->mRight != NULL)
  8309. nameNode->mRight->ToString(fieldName);
  8310. bool wasBaseLookup = false;
  8311. if (auto qualifiedLeftName = BfNodeDynCast<BfQualifiedNameNode>(nameNode->mLeft))
  8312. {
  8313. if (CheckIsBase(qualifiedLeftName->mRight))
  8314. {
  8315. wasBaseLookup = true;
  8316. auto type = mModule->ResolveTypeRef(qualifiedLeftName->mLeft, NULL);
  8317. if (type == NULL)
  8318. return;
  8319. auto fieldName = nameNode->mRight->ToString();
  8320. auto target = mModule->GetThis();
  8321. target.mType = type;
  8322. mResult = LookupField(nameNode->mRight, target, fieldName);
  8323. if ((mPropDef != NULL) && (mPropDef->IsVirtual()))
  8324. mPropDefBypassVirtual = true;
  8325. return;
  8326. }
  8327. }
  8328. if (!wasBaseLookup)
  8329. mResult = LookupIdentifier(nameNode->mLeft, ignoreInitialError, hadError);
  8330. GetResult();
  8331. if (!mResult)
  8332. {
  8333. if (!ignoreInitialError)
  8334. mModule->Fail("Identifier not found", nameNode->mLeft);
  8335. return;
  8336. }
  8337. if (mResult.mType->IsObject())
  8338. {
  8339. mResult = mModule->LoadValue(mResult, 0, mIsVolatileReference);
  8340. }
  8341. else if ((mResult.mType->IsPointer()) && mResult.mType->IsStructOrStructPtr())
  8342. {
  8343. BfPointerType* structPtrType = (BfPointerType*)mResult.mType;
  8344. mResult = mModule->LoadValue(mResult, 0, mIsVolatileReference);
  8345. mResult.mType = structPtrType->mElementType;
  8346. if (mResult.mKind == BfTypedValueKind_ThisValue)
  8347. mResult.mKind = BfTypedValueKind_ThisAddr;
  8348. else
  8349. mResult.mKind = BfTypedValueKind_Addr;
  8350. }
  8351. mIsVolatileReference = false;
  8352. mIsHeapReference = false;
  8353. if (!mResult)
  8354. return;
  8355. auto origResult = mResult;
  8356. auto lookupType = BindGenericType(nameNode, mResult.mType);
  8357. if (mResult.mType->IsVar())
  8358. {
  8359. mResult = BfTypedValue(mModule->GetDefaultValue(mResult.mType), mResult.mType, true);
  8360. return;
  8361. }
  8362. if ((!mResult.mType->IsTypeInstance()) && (!mResult.mType->IsGenericParam()))
  8363. {
  8364. if (hadError != NULL)
  8365. *hadError = true;
  8366. mModule->Fail(StrFormat("Type '%s' has no fields", mModule->TypeToString(mResult.mType).c_str()), nameNode->mLeft);
  8367. mResult = BfTypedValue();
  8368. return;
  8369. }
  8370. BfTypedValue lookupVal = mResult;
  8371. mResult = LookupField(nameNode->mRight, lookupVal, fieldName);
  8372. if ((!mResult) && (mPropDef == NULL) && (lookupType->IsGenericParam()))
  8373. {
  8374. auto genericParamInst = mModule->GetGenericParamInstance((BfGenericParamType*)lookupType);
  8375. SizedArray<BfTypeInstance*, 8> searchConstraints;
  8376. for (auto ifaceConstraint : genericParamInst->mInterfaceConstraints)
  8377. {
  8378. if (!searchConstraints.Contains(ifaceConstraint))
  8379. {
  8380. searchConstraints.push_back(ifaceConstraint);
  8381. for (auto& innerIFaceEntry : ifaceConstraint->mInterfaces)
  8382. {
  8383. auto innerIFace = innerIFaceEntry.mInterfaceType;
  8384. if (!searchConstraints.Contains(innerIFace))
  8385. {
  8386. searchConstraints.push_back(innerIFace);
  8387. }
  8388. }
  8389. }
  8390. }
  8391. BfTypedValue prevTarget;
  8392. BfPropertyDef* prevDef = NULL;
  8393. for (auto ifaceConstraint : searchConstraints)
  8394. {
  8395. BfTypedValue lookupVal = BfTypedValue(mModule->mBfIRBuilder->GetFakeVal(), ifaceConstraint);
  8396. mResult = LookupField(nameNode->mRight, lookupVal, fieldName);
  8397. if (mPropDef != NULL)
  8398. {
  8399. if (prevDef != NULL)
  8400. {
  8401. bool isBetter = mModule->TypeIsSubTypeOf(mPropTarget.mType->ToTypeInstance(), prevTarget.mType->ToTypeInstance());
  8402. bool isWorse = mModule->TypeIsSubTypeOf(prevTarget.mType->ToTypeInstance(), mPropTarget.mType->ToTypeInstance());
  8403. if ((isWorse) && (!isBetter))
  8404. continue;
  8405. if (isBetter == isWorse)
  8406. {
  8407. auto error = mModule->Fail("Ambiguous property reference", nameNode->mRight);
  8408. if (error != NULL)
  8409. {
  8410. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("'%s' has a candidate", mModule->TypeToString(prevTarget.mType).c_str()), prevDef->GetRefNode());
  8411. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("'%s' has a candidate", mModule->TypeToString(mPropTarget.mType).c_str()), mPropDef->GetRefNode());
  8412. }
  8413. }
  8414. }
  8415. prevDef = mPropDef;
  8416. prevTarget = mPropTarget;
  8417. }
  8418. }
  8419. /*if ((mResult) || (mPropDef != NULL))
  8420. break;*/
  8421. }
  8422. if (mPropDef != NULL)
  8423. {
  8424. mOrigPropTarget = origResult;
  8425. if (((CheckIsBase(nameNode->mLeft)) || (wasBaseLookup)) && (mPropDef->IsVirtual()))
  8426. mPropDefBypassVirtual = true;
  8427. }
  8428. if ((mResult) || (mPropDef != NULL))
  8429. return;
  8430. if (hadError != NULL)
  8431. *hadError = true;
  8432. BfTypeInstance* typeInst = lookupType->ToTypeInstance();
  8433. auto compiler = mModule->mCompiler;
  8434. if ((typeInst != NULL) && (compiler->IsAutocomplete()) && (compiler->mResolvePassData->mAutoComplete->CheckFixit(nameNode->mRight)))
  8435. {
  8436. FixitAddMember(typeInst, mExpectingType, nameNode->mRight->ToString(), false);
  8437. }
  8438. mModule->Fail(StrFormat("Unable to find member '%s' in '%s'", fieldName.c_str(), mModule->TypeToString(lookupType).c_str()), nameNode->mRight);
  8439. }
  8440. void BfExprEvaluator::LookupQualifiedName(BfAstNode* nameNode, BfIdentifierNode* nameLeft, BfIdentifierNode* nameRight, bool ignoreInitialError, bool* hadError)
  8441. {
  8442. String fieldName;
  8443. if (nameRight != NULL)
  8444. fieldName = nameRight->ToString();
  8445. bool wasBaseLookup = false;
  8446. if (auto qualifiedLeftName = BfNodeDynCast<BfQualifiedNameNode>(nameLeft))
  8447. {
  8448. if (CheckIsBase(qualifiedLeftName->mRight))
  8449. {
  8450. wasBaseLookup = true;
  8451. auto type = mModule->ResolveTypeRef(qualifiedLeftName->mLeft, NULL);
  8452. if (type == NULL)
  8453. return;
  8454. auto fieldName = nameRight->ToString();
  8455. auto target = mModule->GetThis();
  8456. target.mType = type;
  8457. mResult = LookupField(nameRight, target, fieldName);
  8458. if ((mPropDef != NULL) && (mPropDef->IsVirtual()))
  8459. mPropDefBypassVirtual = true;
  8460. return;
  8461. }
  8462. }
  8463. if (!wasBaseLookup)
  8464. {
  8465. mResult = LookupIdentifier(nameLeft, ignoreInitialError, hadError);
  8466. if ((mResult) && (!mResult.mType->IsComposite()))
  8467. CheckResultForReading(mResult);
  8468. }
  8469. GetResult();
  8470. if (!mResult)
  8471. {
  8472. if (!ignoreInitialError)
  8473. mModule->Fail("Identifier not found", nameLeft);
  8474. return;
  8475. }
  8476. if (mResult.mType->IsObject())
  8477. {
  8478. mResult = mModule->LoadValue(mResult, 0, mIsVolatileReference);
  8479. }
  8480. else if ((mResult.mType->IsPointer()) && mResult.mType->IsStructOrStructPtr())
  8481. {
  8482. BfPointerType* structPtrType = (BfPointerType*)mResult.mType;
  8483. mResult = mModule->LoadValue(mResult, 0, mIsVolatileReference);
  8484. mResult.mType = structPtrType->mElementType;
  8485. if (mResult.mKind == BfTypedValueKind_ThisValue)
  8486. mResult.mKind = BfTypedValueKind_ThisAddr;
  8487. else
  8488. mResult.mKind = BfTypedValueKind_Addr;
  8489. }
  8490. mIsVolatileReference = false;
  8491. mIsHeapReference = false;
  8492. if (!mResult)
  8493. return;
  8494. if (mResult.mType->IsAllocType())
  8495. mResult.mType = mResult.mType->GetUnderlyingType();
  8496. auto origResult = mResult;
  8497. if (mResult.mType->IsVar())
  8498. {
  8499. mResult = BfTypedValue(mModule->GetDefaultValue(mResult.mType), mResult.mType, true);
  8500. return;
  8501. }
  8502. if ((!mResult.mType->IsTypeInstance()) && (!mResult.mType->IsGenericParam()))
  8503. {
  8504. if (mResult.mType->IsSizedArray())
  8505. {
  8506. if (mResult.mType->IsValuelessType())
  8507. {
  8508. mResult.mType = mModule->GetWrappedStructType(mResult.mType);
  8509. mResult.mValue = mModule->mBfIRBuilder->GetFakeVal();
  8510. }
  8511. else
  8512. {
  8513. mResult = mModule->MakeAddressable(mResult);
  8514. mResult.mType = mModule->GetWrappedStructType(mResult.mType);
  8515. mResult.mValue = mModule->mBfIRBuilder->CreateBitCast(mResult.mValue, mModule->mBfIRBuilder->MapTypeInstPtr(mResult.mType->ToTypeInstance()));
  8516. }
  8517. }
  8518. else if (mResult.mType->IsWrappableType())
  8519. {
  8520. mResult.mType = mModule->GetWrappedStructType(mResult.mType);
  8521. }
  8522. else
  8523. {
  8524. if (hadError != NULL)
  8525. *hadError = true;
  8526. mModule->Fail(StrFormat("Type '%s' has no fields", mModule->TypeToString(mResult.mType).c_str()), nameLeft);
  8527. mResult = BfTypedValue();
  8528. return;
  8529. }
  8530. }
  8531. BfTypedValue lookupVal = mResult;
  8532. auto lookupType = BindGenericType(nameNode, mResult.mType);
  8533. if ((lookupType->IsGenericParam()) && (!mResult.mType->IsGenericParam()))
  8534. {
  8535. // Try to lookup from generic binding
  8536. mResult = LookupField(nameRight, BfTypedValue(mModule->mBfIRBuilder->GetFakeVal(), lookupType), fieldName, BfLookupFieldFlag_BindOnly);
  8537. if (mPropDef != NULL)
  8538. {
  8539. mOrigPropTarget = lookupVal;
  8540. return;
  8541. }
  8542. }
  8543. if (mPropDef == NULL)
  8544. mResult = LookupField(nameRight, lookupVal, fieldName, CheckIsBase(nameLeft) ? BfLookupFieldFlag_BaseLookup : BfLookupFieldFlag_None);
  8545. if ((!mResult) && (mPropDef == NULL) && (lookupType->IsGenericParam()))
  8546. {
  8547. auto genericParamInst = mModule->GetGenericParamInstance((BfGenericParamType*)lookupType);
  8548. SizedArray<BfTypeInstance*, 8> searchConstraints;
  8549. for (auto ifaceConstraint : genericParamInst->mInterfaceConstraints)
  8550. {
  8551. if (!searchConstraints.Contains(ifaceConstraint))
  8552. {
  8553. searchConstraints.push_back(ifaceConstraint);
  8554. for (auto& innerIFaceEntry : ifaceConstraint->mInterfaces)
  8555. {
  8556. auto innerIFace = innerIFaceEntry.mInterfaceType;
  8557. if (!searchConstraints.Contains(innerIFace))
  8558. {
  8559. searchConstraints.push_back(innerIFace);
  8560. }
  8561. }
  8562. }
  8563. }
  8564. BfTypedValue prevTarget;
  8565. BfPropertyDef* prevDef = NULL;
  8566. for (auto ifaceConstraint : searchConstraints)
  8567. {
  8568. BfTypedValue lookupVal = BfTypedValue(mModule->mBfIRBuilder->GetFakeVal(), ifaceConstraint);
  8569. mResult = LookupField(nameRight, lookupVal, fieldName);
  8570. if (mPropDef != NULL)
  8571. {
  8572. if (prevDef != NULL)
  8573. {
  8574. bool isBetter = mModule->TypeIsSubTypeOf(mPropTarget.mType->ToTypeInstance(), prevTarget.mType->ToTypeInstance());
  8575. bool isWorse = mModule->TypeIsSubTypeOf(prevTarget.mType->ToTypeInstance(), mPropTarget.mType->ToTypeInstance());
  8576. if ((isWorse) && (!isBetter))
  8577. continue;
  8578. if (isBetter == isWorse)
  8579. {
  8580. auto error = mModule->Fail("Ambiguous property reference", nameRight);
  8581. if (error != NULL)
  8582. {
  8583. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("'%s' has a candidate", mModule->TypeToString(prevTarget.mType).c_str()), prevDef->GetRefNode());
  8584. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("'%s' has a candidate", mModule->TypeToString(mPropTarget.mType).c_str()), mPropDef->GetRefNode());
  8585. }
  8586. }
  8587. }
  8588. prevDef = mPropDef;
  8589. prevTarget = mPropTarget;
  8590. }
  8591. }
  8592. if ((mPropDef == NULL) && (genericParamInst->IsEnum()))
  8593. {
  8594. if ((fieldName == "Underlying") || (fieldName == "UnderlyingRef"))
  8595. {
  8596. mResult = mModule->GetDefaultTypedValue(mModule->GetPrimitiveType(BfTypeCode_Var));
  8597. return;
  8598. }
  8599. }
  8600. }
  8601. if (mPropDef != NULL)
  8602. {
  8603. mOrigPropTarget = origResult;
  8604. if ((CheckIsBase(nameLeft)) || (wasBaseLookup))
  8605. {
  8606. if (mPropDef->IsVirtual())
  8607. mPropDefBypassVirtual = true;
  8608. }
  8609. }
  8610. if ((mResult) || (mPropDef != NULL))
  8611. return;
  8612. if (hadError != NULL)
  8613. *hadError = true;
  8614. BfTypeInstance* typeInst = lookupType->ToTypeInstance();
  8615. auto compiler = mModule->mCompiler;
  8616. if ((typeInst != NULL) && (compiler->IsAutocomplete()) && (compiler->mResolvePassData->mAutoComplete->CheckFixit(nameRight)))
  8617. {
  8618. FixitAddMember(typeInst, mExpectingType, nameRight->ToString(), false);
  8619. }
  8620. mModule->Fail(StrFormat("Unable to find member '%s' in '%s'", fieldName.c_str(), mModule->TypeToString(lookupType).c_str()), nameRight);
  8621. }
  8622. void BfExprEvaluator::LookupQualifiedStaticField(BfQualifiedNameNode* nameNode, bool ignoreIdentifierNotFoundError)
  8623. {
  8624. // Lookup left side as a type
  8625. {
  8626. BfType* type = NULL;
  8627. {
  8628. type = mModule->ResolveTypeRef(nameNode->mLeft, NULL, BfPopulateType_Data, BfResolveTypeRefFlag_AllowRef);
  8629. mModule->CheckTypeRefFixit(nameNode->mLeft);
  8630. }
  8631. if (type != NULL)
  8632. {
  8633. BfTypedValue lookupType;
  8634. if (type->IsWrappableType())
  8635. lookupType = BfTypedValue(mModule->GetWrappedStructType(type));
  8636. else
  8637. lookupType = BfTypedValue(type);
  8638. auto findName = nameNode->mRight->ToString();
  8639. /*if (findName == "base")
  8640. {
  8641. mResult = BfTypedValue(lookupType);
  8642. return;
  8643. }*/
  8644. mResult = LookupField(nameNode->mRight, lookupType, findName);
  8645. if ((mResult) || (mPropDef != NULL))
  8646. return;
  8647. if (lookupType.mType != NULL)
  8648. {
  8649. BfTypeInstance* typeInst = lookupType.mType->ToTypeInstance();
  8650. auto compiler = mModule->mCompiler;
  8651. if ((typeInst != NULL) && (compiler->IsAutocomplete()) && (compiler->mResolvePassData->mAutoComplete->CheckFixit(nameNode->mRight)))
  8652. {
  8653. FixitAddMember(typeInst, mExpectingType, nameNode->mRight->ToString(), true);
  8654. }
  8655. }
  8656. if ((mBfEvalExprFlags & BfEvalExprFlags_NoLookupError) == 0)
  8657. mModule->Fail("Field not found", nameNode->mRight);
  8658. return;
  8659. }
  8660. }
  8661. String fieldName = nameNode->mRight->ToString();
  8662. if (auto qualifiedLeftName = BfNodeDynCast<BfQualifiedNameNode>(nameNode->mLeft))
  8663. LookupQualifiedStaticField(qualifiedLeftName, true);
  8664. else if (auto leftName = BfNodeDynCast<BfIdentifierNode>(nameNode->mLeft))
  8665. {
  8666. mResult = LookupIdentifier(leftName);
  8667. }
  8668. GetResult();
  8669. if (!mResult)
  8670. {
  8671. if (!ignoreIdentifierNotFoundError)
  8672. mModule->Fail("Identifier not found", nameNode->mLeft);
  8673. return;
  8674. }
  8675. if (mResult.mType->IsObject())
  8676. {
  8677. mResult = mModule->LoadValue(mResult);
  8678. }
  8679. else if ((mResult.mType->IsPointer()) && mResult.mType->IsStructOrStructPtr())
  8680. {
  8681. BfPointerType* structPtrType = (BfPointerType*) mResult.mType;
  8682. mResult = mModule->LoadValue(mResult);
  8683. mResult.mType = structPtrType->mElementType;
  8684. }
  8685. if (!mResult)
  8686. return;
  8687. if (!mResult.mType->IsTypeInstance())
  8688. {
  8689. mModule->Fail(StrFormat("Type '%s' has no fields", mModule->TypeToString(mResult.mType).c_str()), nameNode->mLeft);
  8690. return;
  8691. }
  8692. auto leftResult = mResult;
  8693. mResult = LookupField(nameNode->mRight, leftResult, fieldName);
  8694. if ((mResult) || (mPropDef != NULL))
  8695. return;
  8696. mModule->Fail(StrFormat("Unable to find member '%s' in '%s'", fieldName.c_str(), mModule->TypeToString(leftResult.mType).c_str()), nameNode->mRight);
  8697. }
  8698. void BfExprEvaluator::LookupQualifiedStaticField(BfAstNode* nameNode, BfIdentifierNode* nameLeft, BfIdentifierNode* nameRight, bool ignoreIdentifierNotFoundError)
  8699. {
  8700. // Lookup left side as a type
  8701. {
  8702. BfType* type = mModule->ResolveTypeRef(nameLeft, NULL, BfPopulateType_Declaration, (BfResolveTypeRefFlags)(BfResolveTypeRefFlag_IgnoreLookupError | BfResolveTypeRefFlag_AllowGlobalContainer));
  8703. if (type != NULL)
  8704. {
  8705. BfTypedValue lookupType;
  8706. if (type->IsWrappableType())
  8707. lookupType = BfTypedValue(mModule->GetWrappedStructType(type));
  8708. else
  8709. lookupType = BfTypedValue(type);
  8710. auto findName = nameRight->ToString();
  8711. if ((lookupType.mType != NULL) && (lookupType.mType->IsGenericParam()))
  8712. {
  8713. auto genericParamInstance = mModule->GetGenericParamInstance((BfGenericParamType*)lookupType.mType);
  8714. if (genericParamInstance->mTypeConstraint != NULL)
  8715. {
  8716. mResult = LookupField(nameRight, BfTypedValue(genericParamInstance->mTypeConstraint), findName);
  8717. if ((mResult) || (mPropDef != NULL))
  8718. {
  8719. mOrigPropTarget = lookupType;
  8720. return;
  8721. }
  8722. }
  8723. for (auto constraint : genericParamInstance->mInterfaceConstraints)
  8724. {
  8725. mResult = LookupField(nameRight, BfTypedValue(constraint), findName);
  8726. if ((mResult) || (mPropDef != NULL))
  8727. {
  8728. mOrigPropTarget = lookupType;
  8729. return;
  8730. }
  8731. }
  8732. }
  8733. /*if (findName == "base")
  8734. {
  8735. mResult = BfTypedValue(lookupType);
  8736. return;
  8737. }*/
  8738. mResult = LookupField(nameRight, lookupType, findName);
  8739. if ((mResult) || (mPropDef != NULL))
  8740. return;
  8741. if (lookupType.mType != NULL)
  8742. {
  8743. BfTypeInstance* typeInst = lookupType.mType->ToTypeInstance();
  8744. auto compiler = mModule->mCompiler;
  8745. if ((typeInst != NULL) && (compiler->IsAutocomplete()) && (compiler->mResolvePassData->mAutoComplete->CheckFixit(nameRight)))
  8746. {
  8747. FixitAddMember(typeInst, mExpectingType, nameRight->ToString(), true);
  8748. }
  8749. }
  8750. if ((mBfEvalExprFlags & BfEvalExprFlags_NoLookupError) == 0)
  8751. mModule->Fail("Field not found", nameRight);
  8752. return;
  8753. }
  8754. }
  8755. String fieldName = nameRight->ToString();
  8756. if (auto qualifiedLeftName = BfNodeDynCast<BfQualifiedNameNode>(nameLeft))
  8757. LookupQualifiedStaticField(qualifiedLeftName, qualifiedLeftName->mLeft, qualifiedLeftName->mRight, true);
  8758. else if (auto leftName = BfNodeDynCast<BfIdentifierNode>(nameLeft))
  8759. {
  8760. mResult = LookupIdentifier(leftName);
  8761. }
  8762. GetResult();
  8763. if (!mResult)
  8764. {
  8765. if (!ignoreIdentifierNotFoundError)
  8766. mModule->Fail("Identifier not found", nameLeft);
  8767. return;
  8768. }
  8769. if (mResult.mType->IsObject())
  8770. {
  8771. mResult = mModule->LoadValue(mResult);
  8772. }
  8773. else if ((mResult.mType->IsPointer()) && mResult.mType->IsStructOrStructPtr())
  8774. {
  8775. BfPointerType* structPtrType = (BfPointerType*)mResult.mType;
  8776. mResult = mModule->LoadValue(mResult);
  8777. mResult = BfTypedValue(mResult.mValue, structPtrType->mElementType, true);
  8778. }
  8779. if (!mResult)
  8780. return;
  8781. if (!mResult.mType->IsTypeInstance())
  8782. {
  8783. if (mResult.mType->IsSizedArray())
  8784. {
  8785. mResult.mType = mModule->GetWrappedStructType(mResult.mType);
  8786. mResult.mValue = mModule->mBfIRBuilder->CreateBitCast(mResult.mValue, mModule->mBfIRBuilder->MapTypeInstPtr(mResult.mType->ToTypeInstance()));
  8787. }
  8788. else if (mResult.mType->IsWrappableType())
  8789. {
  8790. mResult.mType = mModule->GetWrappedStructType(mResult.mType);
  8791. }
  8792. else
  8793. {
  8794. mModule->Fail(StrFormat("Type '%s' has no fields", mModule->TypeToString(mResult.mType).c_str()), nameLeft);
  8795. return;
  8796. }
  8797. }
  8798. mResult = LookupField(nameRight, mResult, fieldName);
  8799. if ((mResult) || (mPropDef != NULL))
  8800. return;
  8801. mModule->CheckTypeRefFixit(nameLeft);
  8802. mModule->Fail(StrFormat("Unable to find member '%s' in '%s'", fieldName.c_str(), mModule->TypeToString(mResult.mType).c_str()), nameRight);
  8803. }
  8804. void BfExprEvaluator::Visit(BfQualifiedNameNode* nameNode)
  8805. {
  8806. auto autoComplete = GetAutoComplete();
  8807. if (autoComplete != NULL)
  8808. {
  8809. autoComplete->CheckMemberReference(nameNode->mLeft, nameNode->mDot, nameNode->mRight);
  8810. }
  8811. bool hadError = false;
  8812. LookupQualifiedName(nameNode, nameNode->mLeft, nameNode->mRight, true, &hadError);
  8813. if ((mResult) || (mPropDef != NULL))
  8814. return;
  8815. if (hadError)
  8816. return;
  8817. LookupQualifiedStaticField(nameNode, nameNode->mLeft, nameNode->mRight, false);
  8818. }
  8819. void BfExprEvaluator::Visit(BfThisExpression* thisExpr)
  8820. {
  8821. mResult = mModule->GetThis();
  8822. if (!mResult)
  8823. {
  8824. mModule->Fail("Static methods don't have 'this'", thisExpr);
  8825. return;
  8826. }
  8827. auto autoComplete = GetAutoComplete();
  8828. if ((autoComplete != NULL) && (autoComplete->IsAutocompleteNode(thisExpr)))
  8829. autoComplete->SetDefinitionLocation(mModule->mCurTypeInstance->mTypeDef->GetRefNode());
  8830. mResultLocalVar = mModule->GetThisVariable();
  8831. mResultFieldInstance = NULL;
  8832. }
  8833. void BfExprEvaluator::Visit(BfBaseExpression* baseExpr)
  8834. {
  8835. mResult = mModule->GetThis();
  8836. if (!mResult)
  8837. {
  8838. mModule->Fail("Static methods don't have 'base'", baseExpr);
  8839. return;
  8840. }
  8841. if ((mBfEvalExprFlags & BfEvalExprFlags_AllowBase) == 0)
  8842. mModule->Fail("Use of keyword 'base' is not valid in this context", baseExpr);
  8843. auto baseType = mModule->mCurTypeInstance->mBaseType;
  8844. if (baseType == NULL)
  8845. baseType = mModule->mContext->mBfObjectType;
  8846. auto autoComplete = GetAutoComplete();
  8847. if ((autoComplete != NULL) && (autoComplete->IsAutocompleteNode(baseExpr)))
  8848. autoComplete->SetDefinitionLocation(baseType->mTypeDef->GetRefNode());
  8849. mModule->PopulateType(baseType, BfPopulateType_Data);
  8850. mResult = mModule->Cast(baseExpr, mResult, baseType, BfCastFlags_Explicit);
  8851. if (mResult.IsSplat())
  8852. mResult.mKind = BfTypedValueKind_BaseSplatHead;
  8853. else if (mResult.IsAddr())
  8854. mResult.mKind = BfTypedValueKind_BaseAddr;
  8855. else if (mResult)
  8856. mResult.mKind = BfTypedValueKind_BaseValue;
  8857. }
  8858. void BfExprEvaluator::Visit(BfMixinExpression* mixinExpr)
  8859. {
  8860. if (mModule->mCurMethodInstance->mMethodDef->mMethodType == BfMethodType_Mixin)
  8861. {
  8862. auto varType = mModule->GetPrimitiveType(BfTypeCode_Var);
  8863. auto newVar = mModule->AllocFromType(varType, mModule->mCurMethodState->mCurScope);
  8864. mResult = BfTypedValue(newVar, varType, true);
  8865. return;
  8866. }
  8867. auto curMethodState = mModule->mCurMethodState;
  8868. if (curMethodState->mMixinState == NULL)
  8869. {
  8870. mModule->Fail("Mixin references can only be used within mixins", mixinExpr);
  8871. return;
  8872. }
  8873. int localIdx = GetMixinVariable();
  8874. if (localIdx != -1)
  8875. {
  8876. auto varDecl = curMethodState->mLocals[localIdx];
  8877. if (varDecl != NULL)
  8878. {
  8879. BfTypedValue localResult = LoadLocal(varDecl);
  8880. mResult = localResult;
  8881. mResultLocalVar = varDecl;
  8882. mResultFieldInstance = NULL;
  8883. mResultLocalVarRefNode = mixinExpr;
  8884. return;
  8885. }
  8886. }
  8887. if (mModule->mCurMethodInstance->mIsUnspecialized)
  8888. {
  8889. mResult = mModule->GetDefaultTypedValue(mModule->GetPrimitiveType(BfTypeCode_Var));
  8890. return;
  8891. }
  8892. mModule->Fail("Mixin value cannot be inferred", mixinExpr);
  8893. }
  8894. void BfExprEvaluator::Visit(BfSizedArrayCreateExpression* createExpr)
  8895. {
  8896. auto type = mModule->ResolveTypeRef(createExpr->mTypeRef);
  8897. if (type == NULL)
  8898. return;
  8899. if (type->IsArray())
  8900. {
  8901. // If we have a case like 'int[] (1, 2)' then we infer the sized array size from the initializer
  8902. auto arrayType = (BfArrayType*)type;
  8903. if (arrayType->mDimensions == 1)
  8904. {
  8905. int arraySize = 0;
  8906. if (auto arrayInitExpr = BfNodeDynCast<BfCollectionInitializerExpression>(createExpr->mInitializer))
  8907. {
  8908. arraySize = (int)arrayInitExpr->mValues.size();
  8909. }
  8910. type = mModule->CreateSizedArrayType(arrayType->GetUnderlyingType(), arraySize);
  8911. }
  8912. }
  8913. if (!type->IsSizedArray())
  8914. {
  8915. mModule->Fail("Sized array expected", createExpr->mTypeRef);
  8916. return;
  8917. }
  8918. BfSizedArrayType* arrayType = (BfSizedArrayType*)type;
  8919. if (createExpr->mInitializer == NULL)
  8920. {
  8921. mModule->AssertErrorState();
  8922. mResult = mModule->GetDefaultTypedValue(arrayType);
  8923. return;
  8924. }
  8925. InitializedSizedArray(arrayType, createExpr->mInitializer->mOpenBrace, createExpr->mInitializer->mValues, createExpr->mInitializer->mCommas, createExpr->mInitializer->mCloseBrace);
  8926. }
  8927. void BfExprEvaluator::Visit(BfInitializerExpression* initExpr)
  8928. {
  8929. uint64 unassignedFieldFlags = 0;
  8930. if (auto typeRef = BfNodeDynCast<BfTypeReference>(initExpr->mTarget))
  8931. {
  8932. BfType* type = NULL;
  8933. if (auto typeRef = BfNodeDynCast<BfDotTypeReference>(initExpr->mTarget))
  8934. {
  8935. type = mExpectingType;
  8936. }
  8937. if (type == NULL)
  8938. type = mModule->ResolveTypeRef(typeRef);
  8939. if (type != NULL)
  8940. {
  8941. if (type->IsValueType())
  8942. {
  8943. if (mReceivingValue != NULL)
  8944. {
  8945. mResult = *mReceivingValue;
  8946. mReceivingValue = NULL;
  8947. }
  8948. else
  8949. {
  8950. mResult = BfTypedValue(mModule->CreateAlloca(type), type, true);
  8951. }
  8952. auto typeInstance = type->ToTypeInstance();
  8953. if (typeInstance != NULL)
  8954. unassignedFieldFlags = (1 << typeInstance->mMergedFieldDataCount) - 1;
  8955. }
  8956. else
  8957. {
  8958. mModule->Fail("Initializer expressions can only be used on value types or allocated values", initExpr->mTarget);
  8959. }
  8960. }
  8961. }
  8962. else
  8963. VisitChild(initExpr->mTarget);
  8964. if (!mResult)
  8965. mResult = mModule->GetDefaultTypedValue(mModule->mContext->mBfObjectType);
  8966. BfIRBlock initBlock = BfIRBlock();
  8967. if (unassignedFieldFlags != 0)
  8968. {
  8969. initBlock = mModule->mBfIRBuilder->CreateBlock("initStart", true);
  8970. mModule->mBfIRBuilder->CreateBr(initBlock);
  8971. mModule->mBfIRBuilder->SetInsertPoint(initBlock);
  8972. }
  8973. BfTypedValue initValue = GetResult(true);
  8974. bool isFirstAdd = true;
  8975. BfFunctionBindResult addFunctionBindResult;
  8976. addFunctionBindResult.mWantsArgs = true;
  8977. for (auto elementExpr : initExpr->mValues)
  8978. {
  8979. if ((mBfEvalExprFlags & BfEvalExprFlags_Comptime) != 0)
  8980. {
  8981. mModule->Fail("Comptime cannot evaluate initializer expressions", elementExpr);
  8982. break;
  8983. }
  8984. bool wasValidInitKind = false;
  8985. if (auto assignExpr = BfNodeDynCast<BfAssignmentExpression>(elementExpr))
  8986. {
  8987. BfTypedValue fieldResult;
  8988. if (auto identifierNode = BfNodeDynCast<BfIdentifierNode>(assignExpr->mLeft))
  8989. {
  8990. StringT<128> findName;
  8991. identifierNode->ToString(findName);
  8992. mResultFieldInstance = NULL;
  8993. fieldResult = LookupField(identifierNode, initValue, findName, BfLookupFieldFlag_IsImplicitThis);
  8994. if ((fieldResult.mKind == BfTypedValueKind_TempAddr) || (fieldResult.mKind == BfTypedValueKind_RestrictedTempAddr))
  8995. fieldResult.mKind = BfTypedValueKind_Addr;
  8996. if ((mResultFieldInstance != NULL) && (mResultFieldInstance->mMergedDataIdx != -1))
  8997. {
  8998. int resultLocalVarField = 0;
  8999. int resultLocalVarFieldCount = 0;
  9000. mResultFieldInstance->GetDataRange(resultLocalVarField, resultLocalVarFieldCount);
  9001. for (int i = 0; i < resultLocalVarFieldCount; i++)
  9002. unassignedFieldFlags &= ~((int64)1 << (resultLocalVarField - 1 + i));
  9003. }
  9004. wasValidInitKind = true;
  9005. if ((fieldResult) || (mPropDef != NULL))
  9006. {
  9007. if (mResultFieldInstance != NULL)
  9008. {
  9009. auto autoComplete = GetAutoComplete();
  9010. if ((autoComplete != NULL) && (autoComplete->IsAutocompleteNode(identifierNode)))
  9011. {
  9012. auto fieldDef = mResultFieldInstance->GetFieldDef();
  9013. if (fieldDef != NULL)
  9014. autoComplete->SetDefinitionLocation(fieldDef->GetRefNode());
  9015. }
  9016. }
  9017. mResult = fieldResult;
  9018. PerformAssignment(assignExpr, true, BfTypedValue());
  9019. mResult = BfTypedValue();
  9020. }
  9021. else
  9022. {
  9023. mModule->Fail(StrFormat("'%s' does not contain a definition for '%s'", mModule->TypeToString(initValue.mType).c_str(),
  9024. findName.c_str()), identifierNode);
  9025. }
  9026. }
  9027. }
  9028. else
  9029. {
  9030. auto autoComplete = GetAutoComplete();
  9031. if ((autoComplete != NULL) && (autoComplete->IsAutocompleteNode(elementExpr)))
  9032. {
  9033. if (auto identiferNode = BfNodeDynCast<BfIdentifierNode>(elementExpr))
  9034. {
  9035. auto typeInstance = initValue.mType->ToTypeInstance();
  9036. if (typeInstance != NULL)
  9037. {
  9038. String filter;
  9039. identiferNode->ToString(filter);
  9040. autoComplete->AddTypeMembers(typeInstance, false, true, filter, typeInstance, false, true, false);
  9041. }
  9042. }
  9043. }
  9044. bool wasFirstAdd = isFirstAdd;
  9045. if (isFirstAdd)
  9046. {
  9047. BfExprEvaluator exprEvaluator(mModule);
  9048. exprEvaluator.mFunctionBindResult = &addFunctionBindResult;
  9049. SizedArray<BfExpression*, 2> argExprs;
  9050. argExprs.push_back(elementExpr);
  9051. BfSizedArray<BfExpression*> sizedArgExprs(argExprs);
  9052. BfResolvedArgs argValues(&sizedArgExprs);
  9053. exprEvaluator.ResolveArgValues(argValues, BfResolveArgsFlag_DeferParamEval);
  9054. exprEvaluator.MatchMethod(elementExpr, NULL, initValue, false, false, "Add", argValues, NULL);
  9055. if (addFunctionBindResult.mMethodInstance != NULL)
  9056. CreateCall(initExpr, addFunctionBindResult.mMethodInstance, addFunctionBindResult.mFunc, true, addFunctionBindResult.mIRArgs);
  9057. isFirstAdd = false;
  9058. }
  9059. else if ((addFunctionBindResult.mMethodInstance == NULL) || (addFunctionBindResult.mMethodInstance->GetParamCount() == 0))
  9060. {
  9061. mModule->CreateValueFromExpression(elementExpr, NULL, (BfEvalExprFlags)(mBfEvalExprFlags& BfEvalExprFlags_InheritFlags));
  9062. }
  9063. else
  9064. {
  9065. auto argValue = mModule->CreateValueFromExpression(elementExpr, addFunctionBindResult.mMethodInstance->GetParamType(0), (BfEvalExprFlags)(mBfEvalExprFlags & BfEvalExprFlags_InheritFlags));
  9066. if ((argValue) && (!mModule->mBfIRBuilder->mIgnoreWrites))
  9067. {
  9068. SizedArray<BfIRValue, 2> irArgs;
  9069. PushThis(elementExpr, initValue, addFunctionBindResult.mMethodInstance, irArgs);
  9070. PushArg(argValue, irArgs);
  9071. for (int argIdx = (int)irArgs.size(); argIdx < (int)addFunctionBindResult.mIRArgs.size(); argIdx++)
  9072. irArgs.Add(addFunctionBindResult.mIRArgs[argIdx]);
  9073. CreateCall(initExpr, addFunctionBindResult.mMethodInstance, addFunctionBindResult.mFunc, true, irArgs);
  9074. }
  9075. }
  9076. wasValidInitKind = true;
  9077. }
  9078. if (!wasValidInitKind)
  9079. {
  9080. mModule->Fail("Invalid initializer member declarator", initExpr);
  9081. }
  9082. }
  9083. if (unassignedFieldFlags != 0)
  9084. {
  9085. auto curBlock = mModule->mBfIRBuilder->GetInsertBlock();
  9086. mModule->mBfIRBuilder->SetInsertPointAtStart(initBlock);
  9087. mModule->mBfIRBuilder->CreateMemSet(initValue.mValue, mModule->GetConstValue(0, mModule->GetPrimitiveType(BfTypeCode_Int8)),
  9088. mModule->GetConstValue(initValue.mType->mSize), initValue.mType->mAlign);
  9089. mModule->mBfIRBuilder->SetInsertPoint(curBlock);
  9090. }
  9091. mResult = initValue;
  9092. }
  9093. void BfExprEvaluator::Visit(BfCollectionInitializerExpression* arrayInitExpr)
  9094. {
  9095. mModule->Fail("Collection initializer not usable here", arrayInitExpr);
  9096. }
  9097. void BfExprEvaluator::Visit(BfTypeOfExpression* typeOfExpr)
  9098. {
  9099. auto typeType = mModule->ResolveTypeDef(mModule->mCompiler->mTypeTypeDef);
  9100. auto autoComplete = GetAutoComplete();
  9101. if ((autoComplete != NULL) && (typeOfExpr->mTypeRef != NULL))
  9102. {
  9103. autoComplete->CheckTypeRef(typeOfExpr->mTypeRef, false, true);
  9104. }
  9105. BfType* type;
  9106. if (auto genericTypeRef = BfNodeDynCast<BfGenericInstanceTypeRef>(typeOfExpr->mTypeRef))
  9107. {
  9108. type = mModule->ResolveTypeRefAllowUnboundGenerics(typeOfExpr->mTypeRef, BfPopulateType_Identity);
  9109. }
  9110. else
  9111. {
  9112. type = ResolveTypeRef(typeOfExpr->mTypeRef, BfPopulateType_Identity, BfResolveTypeRefFlag_AllowGlobalsSelf);
  9113. }
  9114. if (type == NULL)
  9115. {
  9116. mResult = mModule->GetDefaultTypedValue(mModule->ResolveTypeDef(mModule->mCompiler->mTypeTypeDef));
  9117. return;
  9118. }
  9119. if (type->IsGenericParam())
  9120. {
  9121. mResult = BfTypedValue(mModule->mBfIRBuilder->GetUndefConstValue(mModule->mBfIRBuilder->MapType(typeType)), typeType);
  9122. }
  9123. else
  9124. {
  9125. mModule->AddDependency(type, mModule->mCurTypeInstance, BfDependencyMap::DependencyFlag_ExprTypeReference);
  9126. mResult = BfTypedValue(mModule->CreateTypeDataRef(type), typeType);
  9127. }
  9128. }
  9129. bool BfExprEvaluator::LookupTypeProp(BfTypeOfExpression* typeOfExpr, BfIdentifierNode* propName)
  9130. {
  9131. auto typeType = mModule->ResolveTypeDef(mModule->mCompiler->mTypeTypeDef);
  9132. BfType* type;
  9133. //
  9134. {
  9135. // We ignore errors because we go through the normal Visit(BfTypeOfExpression) if this fails, which will throw the error again
  9136. SetAndRestoreValue<bool> prevIgnoreErrors(mModule->mIgnoreErrors, true);
  9137. if (auto genericTypeRef = BfNodeDynCast<BfGenericInstanceTypeRef>(typeOfExpr->mTypeRef))
  9138. {
  9139. SetAndRestoreValue<bool> prevIgnoreErrors(mModule->mIgnoreErrors, true);
  9140. type = mModule->ResolveTypeRefAllowUnboundGenerics(typeOfExpr->mTypeRef, BfPopulateType_Identity);
  9141. }
  9142. else
  9143. {
  9144. type = ResolveTypeRef(typeOfExpr->mTypeRef, BfPopulateType_Identity, BfResolveTypeRefFlag_IgnoreLookupError);
  9145. }
  9146. }
  9147. if (type == NULL)
  9148. {
  9149. mResult = mModule->GetDefaultTypedValue(mModule->ResolveTypeDef(mModule->mCompiler->mTypeTypeDef));
  9150. return false;
  9151. }
  9152. mModule->AddDependency(type, mModule->mCurTypeInstance, BfDependencyMap::DependencyFlag_ExprTypeReference);
  9153. mModule->PopulateType(type);
  9154. auto typeInstance = type->ToTypeInstance();
  9155. auto _BoolResult = [&](bool val)
  9156. {
  9157. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConst(BfTypeCode_Boolean, val ? 1 : 0), mModule->GetPrimitiveType(BfTypeCode_Boolean));
  9158. };
  9159. auto _Int32Result = [&](int32 val)
  9160. {
  9161. mResult = BfTypedValue(mModule->GetConstValue32(val), mModule->GetPrimitiveType(BfTypeCode_Int32));
  9162. };
  9163. String memberName;
  9164. propName->ToString(memberName);
  9165. bool handled = true;
  9166. if (memberName == "IsTypedPrimitive")
  9167. _BoolResult(type->IsPrimitiveType());
  9168. else if (memberName == "IsObject")
  9169. _BoolResult(type->IsObject());
  9170. else if (memberName == "IsValueType")
  9171. _BoolResult(type->IsValueType());
  9172. else if (memberName == "IsPrimitive")
  9173. _BoolResult(type->IsPrimitiveType());
  9174. else if (memberName == "IsInteger")
  9175. _BoolResult(type->IsInteger());
  9176. else if (memberName == "IsIntegral")
  9177. _BoolResult(type->IsIntegral());
  9178. else if (memberName == "IsSigned")
  9179. _BoolResult(type->IsSigned());
  9180. else if (memberName == "IsFloatingPoint")
  9181. _BoolResult(type->IsFloat());
  9182. else if (memberName == "IsPointer")
  9183. _BoolResult(type->IsPointer());
  9184. else if (memberName == "IsStruct")
  9185. _BoolResult(type->IsStruct());
  9186. else if (memberName == "IsSplattable")
  9187. _BoolResult(type->IsSplattable());
  9188. else if (memberName == "IsUnion")
  9189. _BoolResult(type->IsUnion());
  9190. else if (memberName == "IsBoxed")
  9191. _BoolResult(type->IsBoxed());
  9192. else if (memberName == "IsEnum")
  9193. _BoolResult(type->IsEnum());
  9194. else if (memberName == "IsTuple")
  9195. _BoolResult(type->IsTuple());
  9196. else if (memberName == "IsNullable")
  9197. _BoolResult(type->IsNullable());
  9198. else if (memberName == "IsGenericType")
  9199. _BoolResult(type->IsGenericTypeInstance());
  9200. else if (memberName == "IsArray")
  9201. _BoolResult(type->IsArray());
  9202. else if (memberName == "IsSizedArray")
  9203. _BoolResult(type->IsSizedArray());
  9204. else if (memberName == "TypeId")
  9205. {
  9206. _Int32Result(type->mTypeId);
  9207. mResult.mType = mModule->ResolveTypeDef(mModule->mCompiler->mReflectTypeIdTypeDef);
  9208. }
  9209. else if (memberName == "GenericParamCount")
  9210. {
  9211. auto genericTypeInst = type->ToGenericTypeInstance();
  9212. _Int32Result((genericTypeInst != NULL) ? (int)genericTypeInst->mGenericTypeInfo->mTypeGenericArguments.size() : 0);
  9213. }
  9214. else if (memberName == "Size")
  9215. _Int32Result(type->mSize);
  9216. else if (memberName == "Align")
  9217. _Int32Result(type->mAlign);
  9218. else if (memberName == "Stride")
  9219. _Int32Result(type->GetStride());
  9220. else if (memberName == "InstanceSize")
  9221. _Int32Result((typeInstance != NULL) ? typeInstance->mInstSize : type->mSize);
  9222. else if (memberName == "InstanceAlign")
  9223. _Int32Result((typeInstance != NULL) ? typeInstance->mInstAlign : type->mSize);
  9224. else if (memberName == "InstanceStride")
  9225. _Int32Result((typeInstance != NULL) ? typeInstance->GetInstStride() : type->GetStride());
  9226. else if (memberName == "UnderlyingType")
  9227. {
  9228. auto typeType = mModule->ResolveTypeDef(mModule->mCompiler->mTypeTypeDef);
  9229. if (type->IsGenericParam())
  9230. {
  9231. auto genericParamInstance = mModule->GetGenericParamInstance((BfGenericParamType*)type);
  9232. if (genericParamInstance->IsEnum())
  9233. mResult = BfTypedValue(mModule->mBfIRBuilder->GetUndefConstValue(mModule->mBfIRBuilder->MapType(typeType)), typeType);
  9234. }
  9235. else if (type->IsEnum())
  9236. {
  9237. auto underlyingType = type->GetUnderlyingType();
  9238. if (underlyingType != NULL)
  9239. {
  9240. mModule->AddDependency(underlyingType, mModule->mCurTypeInstance, BfDependencyMap::DependencyFlag_ExprTypeReference);
  9241. mResult = BfTypedValue(mModule->CreateTypeDataRef(underlyingType), typeType);
  9242. }
  9243. }
  9244. }
  9245. else if ((memberName == "MinValue") || (memberName == "MaxValue"))
  9246. {
  9247. bool isMin = memberName == "MinValue";
  9248. BfType* checkType = type;
  9249. if (checkType->IsTypedPrimitive())
  9250. checkType = checkType->GetUnderlyingType();
  9251. if (checkType->IsGenericParam())
  9252. {
  9253. bool foundMatch = false;
  9254. auto genericParamInstance = mModule->GetGenericParamInstance((BfGenericParamType*)checkType);
  9255. if (((genericParamInstance->mGenericParamFlags & BfGenericParamFlag_Enum) != 0) ||
  9256. ((genericParamInstance->mTypeConstraint != NULL) && (genericParamInstance->mTypeConstraint->IsInstanceOf(mModule->mCompiler->mEnumTypeDef))))
  9257. foundMatch = true;
  9258. else
  9259. {
  9260. for (auto constraint : genericParamInstance->mInterfaceConstraints)
  9261. {
  9262. if (constraint->IsInstanceOf(mModule->mCompiler->mIIntegerTypeDef))
  9263. foundMatch = true;
  9264. }
  9265. }
  9266. if ((mModule->mCurMethodInstance != NULL) && (mModule->mCurMethodInstance->mIsUnspecialized) && (mModule->mCurMethodInstance->mMethodInfoEx != NULL))
  9267. {
  9268. for (int genericParamIdx = (int)mModule->mCurMethodInstance->mMethodInfoEx->mMethodGenericArguments.size();
  9269. genericParamIdx < mModule->mCurMethodInstance->mMethodInfoEx->mGenericParams.size(); genericParamIdx++)
  9270. {
  9271. genericParamInstance = mModule->mCurMethodInstance->mMethodInfoEx->mGenericParams[genericParamIdx];
  9272. if (genericParamInstance->mExternType == type)
  9273. {
  9274. if (((genericParamInstance->mGenericParamFlags & BfGenericParamFlag_Enum) != 0) ||
  9275. ((genericParamInstance->mTypeConstraint != NULL) && (genericParamInstance->mTypeConstraint->IsInstanceOf(mModule->mCompiler->mEnumTypeDef))))
  9276. foundMatch = true;
  9277. }
  9278. }
  9279. }
  9280. if (foundMatch)
  9281. {
  9282. mResult = mModule->GetDefaultTypedValue(type, false, Beefy::BfDefaultValueKind_Undef);
  9283. return true;
  9284. }
  9285. }
  9286. if (checkType->IsPrimitiveType())
  9287. {
  9288. auto primType = (BfPrimitiveType*)checkType;
  9289. if ((typeInstance != NULL) && (typeInstance->IsEnum()))
  9290. {
  9291. if (typeInstance->mTypeInfoEx != NULL)
  9292. {
  9293. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConst(primType->mTypeDef->mTypeCode, isMin ? (uint64)typeInstance->mTypeInfoEx->mMinValue : (uint64)typeInstance->mTypeInfoEx->mMaxValue), typeInstance);
  9294. return true;
  9295. }
  9296. }
  9297. else
  9298. {
  9299. switch (primType->mTypeDef->mTypeCode)
  9300. {
  9301. case BfTypeCode_Int8:
  9302. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConst(primType->mTypeDef->mTypeCode, isMin ? -0x80 : 0x7F), primType);
  9303. return true;
  9304. case BfTypeCode_Int16:
  9305. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConst(primType->mTypeDef->mTypeCode, isMin ? -0x8000 : 0x7FFF), primType);
  9306. return true;
  9307. case BfTypeCode_Int32:
  9308. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConst(primType->mTypeDef->mTypeCode, isMin ? (uint64)-0x80000000LL : 0x7FFFFFFF), primType);
  9309. return true;
  9310. case BfTypeCode_Int64:
  9311. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConst(primType->mTypeDef->mTypeCode, isMin ? (uint64)-0x8000000000000000LL : (uint64)0x7FFFFFFFFFFFFFFFLL), primType);
  9312. return true;
  9313. case BfTypeCode_UInt8:
  9314. case BfTypeCode_Char8:
  9315. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConst(primType->mTypeDef->mTypeCode, isMin ? 0 : 0xFF), primType);
  9316. return true;
  9317. case BfTypeCode_UInt16:
  9318. case BfTypeCode_Char16:
  9319. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConst(primType->mTypeDef->mTypeCode, isMin ? 0 : 0xFFFF), primType);
  9320. return true;
  9321. case BfTypeCode_UInt32:
  9322. case BfTypeCode_Char32:
  9323. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConst(primType->mTypeDef->mTypeCode, isMin ? 0 : (uint64)0xFFFFFFFFLL), primType);
  9324. return true;
  9325. case BfTypeCode_UInt64:
  9326. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConst(primType->mTypeDef->mTypeCode, isMin ? 0 : (uint64)0xFFFFFFFFFFFFFFFFLL), primType);
  9327. return true;
  9328. case BfTypeCode_IntPtr:
  9329. if (mModule->mSystem->mPtrSize == 8)
  9330. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConst(primType->mTypeDef->mTypeCode, isMin ? (uint64)-0x8000000000000000LL : (uint64)0x7FFFFFFFFFFFFFFFLL), primType);
  9331. else
  9332. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConst(primType->mTypeDef->mTypeCode, isMin ? (uint64)-0x80000000LL : 0x7FFFFFFF), primType);
  9333. return true;
  9334. case BfTypeCode_UIntPtr:
  9335. if (mModule->mSystem->mPtrSize == 8)
  9336. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConst(primType->mTypeDef->mTypeCode, isMin ? 0 : (uint64)0xFFFFFFFFFFFFFFFFLL), primType);
  9337. else
  9338. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConst(primType->mTypeDef->mTypeCode, isMin ? 0 : (uint64)0xFFFFFFFFLL), primType);
  9339. return true;
  9340. default: break;
  9341. }
  9342. }
  9343. }
  9344. if (type->IsEnum())
  9345. {
  9346. mModule->Fail(StrFormat("'MinValue' cannot be used on enum with payload '%s'", mModule->TypeToString(type).c_str()), propName);
  9347. }
  9348. else
  9349. {
  9350. mModule->Fail(StrFormat("'%s' cannot be used on type '%s'", memberName.c_str(), mModule->TypeToString(type).c_str()), propName);
  9351. }
  9352. }
  9353. else
  9354. return false;
  9355. if (type->IsGenericParam())
  9356. {
  9357. if (mResult.mType != NULL)
  9358. mResult = mModule->GetDefaultTypedValue(mResult.mType, false, Beefy::BfDefaultValueKind_Undef);
  9359. }
  9360. auto autoComplete = GetAutoComplete();
  9361. if ((autoComplete != NULL) && (typeOfExpr->mTypeRef != NULL))
  9362. {
  9363. autoComplete->CheckTypeRef(typeOfExpr->mTypeRef, false, true);
  9364. }
  9365. return true;
  9366. }
  9367. void BfExprEvaluator::DoTypeIntAttr(BfTypeReference* typeRef, BfTokenNode* commaToken, BfIdentifierNode* memberName, BfToken token)
  9368. {
  9369. auto autoComplete = GetAutoComplete();
  9370. auto type = mModule->ResolveTypeRef(typeRef, BfPopulateType_Data, BfResolveTypeRefFlag_AutoComplete);
  9371. if (type == NULL)
  9372. return;
  9373. mModule->AddDependency(type, mModule->mCurTypeInstance, BfDependencyMap::DependencyFlag_LocalUsage); // Local usage ensures it changes when the type data changes
  9374. auto typeInst = type->ToTypeInstance();
  9375. if ((typeInst != NULL) && (typeInst->mTypeDef->mIsOpaque))
  9376. {
  9377. mModule->Fail(StrFormat("Unable to determine attributes for opaque type '%s'", mModule->TypeToString(type).c_str()), typeRef);
  9378. }
  9379. BfType* sizeType = mModule->GetPrimitiveType(BfTypeCode_Int32);
  9380. int attrVal = 0;
  9381. switch (token)
  9382. {
  9383. case BfToken_SizeOf: attrVal = type->mSize; break;
  9384. case BfToken_AlignOf: attrVal = type->mAlign; break;
  9385. case BfToken_StrideOf: attrVal = type->GetStride(); break;
  9386. default: break;
  9387. }
  9388. if (token == BfToken_OffsetOf)
  9389. {
  9390. bool found = false;
  9391. String findName;
  9392. if (memberName != NULL)
  9393. findName = memberName->ToString();
  9394. BfAstNode* refNode = typeRef;
  9395. if (memberName != NULL)
  9396. refNode = memberName;
  9397. auto checkTypeInst = typeInst;
  9398. while (checkTypeInst != NULL)
  9399. {
  9400. checkTypeInst->mTypeDef->PopulateMemberSets();
  9401. String filter;
  9402. if ((autoComplete != NULL) && (autoComplete->InitAutocomplete(commaToken, memberName, filter)))
  9403. {
  9404. auto activeTypeDef = mModule->GetActiveTypeDef();
  9405. mModule->PopulateType(checkTypeInst);
  9406. BfProtectionCheckFlags protectionCheckFlags = BfProtectionCheckFlag_None;
  9407. for (auto fieldDef : checkTypeInst->mTypeDef->mFields)
  9408. {
  9409. if (fieldDef->mIsStatic)
  9410. continue;
  9411. if (!mModule->CheckProtection(protectionCheckFlags, typeInst, fieldDef->mDeclaringType->mProject, fieldDef->mProtection, typeInst))
  9412. continue;
  9413. if ((!typeInst->IsTypeMemberIncluded(fieldDef->mDeclaringType, activeTypeDef, mModule)) ||
  9414. (!typeInst->IsTypeMemberAccessible(fieldDef->mDeclaringType, activeTypeDef)))
  9415. continue;
  9416. auto& fieldInst = checkTypeInst->mFieldInstances[fieldDef->mIdx];
  9417. autoComplete->AddField(checkTypeInst, fieldDef, &fieldInst, filter);
  9418. }
  9419. }
  9420. BfMemberSetEntry* memberSetEntry = NULL;
  9421. if (checkTypeInst->mTypeDef->mFieldSet.TryGetWith(findName, &memberSetEntry))
  9422. {
  9423. auto fieldDef = (BfFieldDef*)memberSetEntry->mMemberDef;
  9424. if (fieldDef != NULL)
  9425. {
  9426. if (fieldDef->mIsStatic)
  9427. mModule->Fail(StrFormat("Cannot generate an offset from static field '%s.%s'", mModule->TypeToString(type).c_str(), fieldDef->mName.c_str()), refNode);
  9428. mModule->PopulateType(checkTypeInst);
  9429. auto& fieldInst = checkTypeInst->mFieldInstances[fieldDef->mIdx];
  9430. attrVal = fieldInst.mDataOffset;
  9431. found = true;
  9432. break;
  9433. }
  9434. }
  9435. checkTypeInst = checkTypeInst->mBaseType;
  9436. }
  9437. if (!found)
  9438. {
  9439. mModule->Fail(StrFormat("Unable to locate field '%s.%s'", mModule->TypeToString(type).c_str(), findName.c_str()), refNode);
  9440. }
  9441. }
  9442. bool isUndefVal = false;
  9443. if (type->IsGenericParam())
  9444. isUndefVal = true;
  9445. if (type->IsSizedArray())
  9446. {
  9447. auto sizedArray = (BfSizedArrayType*)type;
  9448. if (sizedArray->mElementCount == -1)
  9449. isUndefVal = true;
  9450. }
  9451. if (isUndefVal)
  9452. {
  9453. // We do this so we know it's a constant but we can't assume anything about its value
  9454. // We make the value an Int32 which doesn't match the IntPtr type, but it allows us to
  9455. // assume it can be implicitly cased to int32
  9456. mResult = BfTypedValue(mModule->mBfIRBuilder->GetUndefConstValue(mModule->mBfIRBuilder->MapType(sizeType)), sizeType);
  9457. }
  9458. else
  9459. mResult = BfTypedValue(mModule->GetConstValue(attrVal, sizeType), sizeType);
  9460. }
  9461. void BfExprEvaluator::Visit(BfSizeOfExpression* sizeOfExpr)
  9462. {
  9463. DoTypeIntAttr(sizeOfExpr->mTypeRef, NULL, NULL, BfToken_SizeOf);
  9464. }
  9465. void BfExprEvaluator::Visit(BfAlignOfExpression* alignOfExpr)
  9466. {
  9467. DoTypeIntAttr(alignOfExpr->mTypeRef, NULL, NULL, BfToken_AlignOf);
  9468. }
  9469. void BfExprEvaluator::Visit(BfStrideOfExpression* strideOfExpr)
  9470. {
  9471. DoTypeIntAttr(strideOfExpr->mTypeRef, NULL, NULL, BfToken_StrideOf);
  9472. }
  9473. void BfExprEvaluator::Visit(BfOffsetOfExpression* offsetOfExpr)
  9474. {
  9475. DoTypeIntAttr(offsetOfExpr->mTypeRef, offsetOfExpr->mCommaToken, offsetOfExpr->mMemberName, BfToken_OffsetOf);
  9476. }
  9477. void BfExprEvaluator::Visit(BfDefaultExpression* defaultExpr)
  9478. {
  9479. auto autoComplete = GetAutoComplete();
  9480. if (autoComplete != NULL)
  9481. autoComplete->CheckTypeRef(defaultExpr->mTypeRef, false, true);
  9482. BfType* type = NULL;
  9483. if (defaultExpr->mOpenParen == NULL)
  9484. {
  9485. if (mExpectingType)
  9486. {
  9487. type = mExpectingType;
  9488. }
  9489. else
  9490. {
  9491. mModule->Fail("Type cannot be inferred, consider adding explicit type name", defaultExpr);
  9492. return;
  9493. }
  9494. }
  9495. else
  9496. type = mModule->ResolveTypeRef(defaultExpr->mTypeRef);
  9497. if (type == NULL)
  9498. return;
  9499. BfDefaultValueKind defaultKind = BfDefaultValueKind_Const;
  9500. if (type->IsRef())
  9501. {
  9502. mModule->Fail(StrFormat("There is no default value for type '%s'", mModule->TypeToString(type).c_str()), defaultExpr);
  9503. defaultKind = BfDefaultValueKind_Addr;
  9504. }
  9505. mModule->ValidateAllocation(type, defaultExpr->mTypeRef);
  9506. mModule->AddDependency(type, mModule->mCurTypeInstance, BfDependencyMap::DependencyFlag_ExprTypeReference);
  9507. mResult = mModule->GetDefaultTypedValue(type, true, defaultKind);
  9508. }
  9509. void BfExprEvaluator::Visit(BfUninitializedExpression* uninitialziedExpr)
  9510. {
  9511. mModule->Fail("Invalid use of the '?' uninitialized specifier", uninitialziedExpr);
  9512. }
  9513. void BfExprEvaluator::Visit(BfCheckTypeExpression* checkTypeExpr)
  9514. {
  9515. auto targetValue = mModule->CreateValueFromExpression(checkTypeExpr->mTarget, NULL, (BfEvalExprFlags)(mBfEvalExprFlags & BfEvalExprFlags_InheritFlags));
  9516. if (!targetValue)
  9517. return;
  9518. if (checkTypeExpr->mTypeRef == NULL)
  9519. {
  9520. mModule->AssertErrorState();
  9521. return;
  9522. }
  9523. auto autoComplete = GetAutoComplete();
  9524. if (autoComplete != NULL)
  9525. autoComplete->CheckTypeRef(checkTypeExpr->mTypeRef, false, true);
  9526. auto targetType = mModule->ResolveTypeRef(checkTypeExpr->mTypeRef);
  9527. if (!targetType)
  9528. {
  9529. mModule->AssertErrorState();
  9530. return;
  9531. }
  9532. mModule->AddDependency(targetType, mModule->mCurTypeInstance, BfDependencyMap::DependencyFlag_ExprTypeReference);
  9533. auto boolType = mModule->GetPrimitiveType(BfTypeCode_Boolean);
  9534. if (targetValue.mType->IsValueTypeOrValueTypePtr())
  9535. {
  9536. auto typeInstance = targetValue.mType->ToTypeInstance();
  9537. if (targetValue.mType->IsWrappableType())
  9538. typeInstance = mModule->GetWrappedStructType(targetValue.mType);
  9539. bool matches = (targetValue.mType == targetType) || (mModule->mContext->mBfObjectType == targetType);
  9540. if (!matches)
  9541. matches = mModule->TypeIsSubTypeOf(typeInstance, targetType->ToTypeInstance());
  9542. mResult = BfTypedValue(mModule->GetConstValue(matches ? 1 : 0, boolType), boolType);
  9543. return;
  9544. }
  9545. if (targetType->IsValueType())
  9546. {
  9547. if ((targetValue.mType != mModule->mContext->mBfObjectType) && (!targetValue.mType->IsInterface()))
  9548. {
  9549. mResult = BfTypedValue(mModule->GetConstValue(0, boolType), boolType);
  9550. return;
  9551. }
  9552. }
  9553. int wantTypeId = 0;
  9554. if (!targetType->IsGenericParam())
  9555. wantTypeId = targetType->mTypeId;
  9556. auto objectType = mModule->mContext->mBfObjectType;
  9557. mModule->PopulateType(objectType, BfPopulateType_Full);
  9558. targetValue = mModule->LoadValue(targetValue);
  9559. BfTypeInstance* srcTypeInstance = targetValue.mType->ToTypeInstance();
  9560. BfTypeInstance* targetTypeInstance = targetType->ToTypeInstance();
  9561. bool wasGenericParamType = false;
  9562. if ((srcTypeInstance != NULL) && (targetTypeInstance != NULL))
  9563. {
  9564. if (mModule->TypeIsSubTypeOf(srcTypeInstance, targetTypeInstance))
  9565. {
  9566. // We don't give this warning when we have wasGenericParmType set because that indicates we had a generic type constraint,
  9567. // and a type constraint infers that the ACTUAL type used will be equal to or derived from that type and therefore
  9568. // it may be a "necessary cast" indeed
  9569. if ((!wasGenericParamType) && (mModule->mCurMethodState->mMixinState == NULL))
  9570. {
  9571. if (srcTypeInstance == targetType)
  9572. mModule->Warn(BfWarning_BF4203_UnnecessaryDynamicCast, StrFormat("Unnecessary cast, the value is already type '%s'",
  9573. mModule->TypeToString(srcTypeInstance).c_str()), checkTypeExpr->mIsToken);
  9574. else
  9575. mModule->Warn(BfWarning_BF4203_UnnecessaryDynamicCast, StrFormat("Unnecessary cast, '%s' is a subtype of '%s'",
  9576. mModule->TypeToString(srcTypeInstance).c_str(), mModule->TypeToString(targetType).c_str()), checkTypeExpr->mIsToken);
  9577. }
  9578. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConst(BfTypeCode_Boolean, 1), boolType);
  9579. return;
  9580. }
  9581. else if ((!targetType->IsInterface()) && (srcTypeInstance != mModule->mContext->mBfObjectType) && (!mModule->TypeIsSubTypeOf(targetTypeInstance, srcTypeInstance)))
  9582. {
  9583. mModule->Fail(StrFormat("Cannot convert type '%s' to '%s' via any conversion",
  9584. mModule->TypeToString(targetValue.mType).c_str(), mModule->TypeToString(targetTypeInstance).c_str()), checkTypeExpr->mIsToken);
  9585. }
  9586. }
  9587. if (mModule->mCompiler->IsAutocomplete())
  9588. {
  9589. mResult = mModule->GetDefaultTypedValue(boolType, false, BfDefaultValueKind_Addr);
  9590. return;
  9591. }
  9592. auto irb = mModule->mBfIRBuilder;
  9593. auto prevBB = mModule->mBfIRBuilder->GetInsertBlock();
  9594. auto matchBB = mModule->mBfIRBuilder->CreateBlock("is.match");
  9595. auto endBB = mModule->mBfIRBuilder->CreateBlock("is.done");
  9596. BfIRValue boolResult = mModule->CreateAlloca(boolType);
  9597. irb->CreateStore(irb->CreateConst(BfTypeCode_Boolean, 0), boolResult);
  9598. mModule->EmitDynamicCastCheck(targetValue, targetType, matchBB, endBB);
  9599. mModule->AddBasicBlock(matchBB);
  9600. irb->CreateStore(irb->CreateConst(BfTypeCode_Boolean, 1), boolResult);
  9601. irb->CreateBr(endBB);
  9602. mModule->AddBasicBlock(endBB);
  9603. mResult = BfTypedValue(irb->CreateLoad(boolResult), boolType);
  9604. }
  9605. void BfExprEvaluator::Visit(BfDynamicCastExpression* dynCastExpr)
  9606. {
  9607. auto targetValue = mModule->CreateValueFromExpression(dynCastExpr->mTarget);
  9608. auto targetType = mModule->ResolveTypeRefAllowUnboundGenerics(dynCastExpr->mTypeRef, BfPopulateType_Data, false);
  9609. auto autoComplete = GetAutoComplete();
  9610. if (autoComplete != NULL)
  9611. {
  9612. autoComplete->CheckTypeRef(dynCastExpr->mTypeRef, false, true);
  9613. }
  9614. auto origTargetType = targetType;
  9615. if (!targetValue)
  9616. return;
  9617. if (!targetType)
  9618. {
  9619. mModule->AssertErrorState();
  9620. return;
  9621. }
  9622. bool wasGenericParamType = false;
  9623. if (targetType->IsGenericParam())
  9624. {
  9625. //targetType = mModule->ResolveGenericType(targetType);
  9626. //wasGenericParamType = true;
  9627. }
  9628. if ((targetValue.mType->IsMethodRef()) || (targetType->IsMethodRef()))
  9629. {
  9630. // We can never cast a MethodRef to any class type
  9631. mResult = mModule->GetDefaultTypedValue(targetType);
  9632. return;
  9633. }
  9634. if (mModule->mContext->mResolvingVarField)
  9635. {
  9636. mResult = mModule->GetDefaultTypedValue(targetType);
  9637. return;
  9638. }
  9639. mModule->AddDependency(targetType, mModule->mCurTypeInstance, BfDependencyMap::DependencyFlag_ExprTypeReference);
  9640. if (targetType->IsGenericParam())
  9641. {
  9642. wasGenericParamType = true;
  9643. //wasGenericParamType = false; // "was", not "is"
  9644. auto genericParamType = (BfGenericParamType*) targetType;
  9645. auto genericParam = mModule->GetGenericParamInstance(genericParamType);
  9646. auto typeConstraint = genericParam->mTypeConstraint;
  9647. if ((typeConstraint == NULL) && (genericParam->mGenericParamFlags & (BfGenericParamFlag_Class | BfGenericParamFlag_Interface)))
  9648. typeConstraint = mModule->mContext->mBfObjectType;
  9649. if ((typeConstraint == NULL) || (!typeConstraint->IsObject()))
  9650. {
  9651. 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",
  9652. genericParam->GetGenericParamDef()->mName.c_str()), dynCastExpr->mTypeRef);
  9653. return;
  9654. }
  9655. targetType = typeConstraint;
  9656. }
  9657. if ((!targetType->IsObjectOrInterface()) && (!targetType->IsNullable()))
  9658. {
  9659. mModule->Fail(StrFormat("The as operator must be used with a reference type or nullable type ('%s' is a non-nullable value type)",
  9660. mModule->TypeToString(origTargetType).c_str()), dynCastExpr->mTypeRef);
  9661. return;
  9662. }
  9663. if (targetValue.mType->IsGenericParam())
  9664. {
  9665. auto genericParamType = (BfGenericParamType*)targetValue.mType;
  9666. auto genericParam = mModule->GetGenericParamInstance(genericParamType);
  9667. auto typeConstraint = genericParam->mTypeConstraint;
  9668. if (typeConstraint == NULL)
  9669. typeConstraint = mModule->mContext->mBfObjectType;
  9670. if ((typeConstraint->IsDelegate()) && (typeConstraint == targetType))
  9671. {
  9672. // Delegate constraints may be matched by valueless method references, so this won't always match (don't warn)
  9673. mResult = mModule->GetDefaultTypedValue(targetType);
  9674. return;
  9675. }
  9676. targetValue = mModule->GetDefaultTypedValue(typeConstraint);
  9677. }
  9678. auto boolType = mModule->GetPrimitiveType(BfTypeCode_Boolean);
  9679. auto _CheckResult = [&]()
  9680. {
  9681. if ((mResult) && (origTargetType->IsGenericParam()))
  9682. mResult = mModule->GetDefaultTypedValue(origTargetType);
  9683. };
  9684. if ((targetValue.mType->IsNullable()) && (targetType->IsInterface()))
  9685. {
  9686. mResult = mModule->Cast(dynCastExpr, targetValue, targetType, BfCastFlags_SilentFail);
  9687. if (!mResult)
  9688. {
  9689. mModule->Warn(0, StrFormat("Conversion from '%s' to '%s' will always be null",
  9690. mModule->TypeToString(targetValue.mType).c_str(), mModule->TypeToString(origTargetType).c_str()), dynCastExpr->mAsToken);
  9691. mResult = BfTypedValue(mModule->GetDefaultValue(origTargetType), origTargetType);
  9692. }
  9693. _CheckResult();
  9694. return;
  9695. }
  9696. if (targetValue.mType->IsValueTypeOrValueTypePtr())
  9697. {
  9698. mModule->Warn(0, StrFormat("Type '%s' is not applicable for dynamic casting",
  9699. mModule->TypeToString(targetValue.mType).c_str()), dynCastExpr->mAsToken);
  9700. auto typeInstance = targetValue.mType->ToTypeInstance();
  9701. if (targetValue.mType->IsWrappableType())
  9702. typeInstance = mModule->GetWrappedStructType(targetValue.mType);
  9703. bool matches = (targetValue.mType == targetType) || (mModule->mContext->mBfObjectType == targetType);
  9704. if (targetType->IsNullable())
  9705. {
  9706. auto elementType = targetType->GetUnderlyingType();
  9707. if (elementType == targetValue.mType)
  9708. {
  9709. // We match nullable element
  9710. auto allocaInst = mModule->CreateAlloca(targetType);
  9711. auto hasValueAddr = mModule->mBfIRBuilder->CreateInBoundsGEP(allocaInst, 0, 1); // has_value
  9712. mModule->mBfIRBuilder->CreateStore(mModule->GetConstValue(1, boolType), hasValueAddr);
  9713. hasValueAddr = mModule->mBfIRBuilder->CreateInBoundsGEP(allocaInst, 0, 0); // value
  9714. mModule->mBfIRBuilder->CreateStore(targetValue.mValue, hasValueAddr);
  9715. mResult = BfTypedValue(allocaInst, targetType, true);
  9716. _CheckResult();
  9717. return;
  9718. }
  9719. }
  9720. if (!matches)
  9721. matches = mModule->TypeIsSubTypeOf(typeInstance, targetType->ToTypeInstance());
  9722. if (matches)
  9723. mResult = mModule->Cast(dynCastExpr, targetValue, targetType, BfCastFlags_Explicit);
  9724. else if (targetType->IsNullable())
  9725. {
  9726. auto allocaInst = mModule->CreateAlloca(targetType);
  9727. auto allocaBits = mModule->mBfIRBuilder->CreateBitCast(allocaInst, mModule->mBfIRBuilder->GetPrimitiveType(BfTypeCode_NullPtr));
  9728. mModule->mBfIRBuilder->CreateMemSet(allocaBits, mModule->GetConstValue(0, mModule->GetPrimitiveType(BfTypeCode_Int8)),
  9729. mModule->GetConstValue(targetType->mSize), targetType->mAlign);
  9730. mResult = BfTypedValue(allocaInst, targetType, true);
  9731. }
  9732. else
  9733. mResult = BfTypedValue(mModule->GetDefaultValue(targetType), targetType);
  9734. _CheckResult();
  9735. return;
  9736. }
  9737. if (targetType->IsNullable())
  9738. {
  9739. if (autoComplete != NULL)
  9740. {
  9741. mResult = mModule->GetDefaultTypedValue(targetType);
  9742. return;
  9743. }
  9744. auto elementType = targetType->GetUnderlyingType();
  9745. auto allocaInst = mModule->CreateAlloca(targetType);
  9746. auto hasValueAddr = mModule->mBfIRBuilder->CreateInBoundsGEP(allocaInst, 0, elementType->IsValuelessType() ? 1 : 2); // has_value
  9747. mModule->mBfIRBuilder->CreateStore(mModule->GetConstValue(0, boolType), hasValueAddr);
  9748. auto objectType = mModule->mContext->mBfObjectType;
  9749. auto prevBB = mModule->mBfIRBuilder->GetInsertBlock();
  9750. auto matchBB = mModule->mBfIRBuilder->CreateBlock("as.match");
  9751. auto endBB = mModule->mBfIRBuilder->CreateBlock("as.end");
  9752. mModule->EmitDynamicCastCheck(targetValue, elementType, matchBB, endBB);
  9753. BfBoxedType* boxedType = mModule->CreateBoxedType(elementType);
  9754. mModule->AddBasicBlock(matchBB);
  9755. if (elementType->IsValuelessType())
  9756. {
  9757. auto hasValueAddr = mModule->mBfIRBuilder->CreateInBoundsGEP(allocaInst, 0, 1); // has_value
  9758. mModule->mBfIRBuilder->CreateStore(mModule->GetConstValue(1, boolType), hasValueAddr);
  9759. }
  9760. else
  9761. {
  9762. auto hasValueAddr = mModule->mBfIRBuilder->CreateInBoundsGEP(allocaInst, 0, 2); // has_value
  9763. mModule->mBfIRBuilder->CreateStore(mModule->GetConstValue(1, boolType), hasValueAddr);
  9764. auto nullableValueAddr = mModule->mBfIRBuilder->CreateInBoundsGEP(allocaInst, 0, 1); // value
  9765. auto srcBoxedType = mModule->mBfIRBuilder->CreateBitCast(targetValue.mValue, mModule->mBfIRBuilder->MapType(boxedType, BfIRPopulateType_Full));
  9766. auto boxedValueAddr = mModule->mBfIRBuilder->CreateInBoundsGEP(srcBoxedType, 0, 1); // mValue
  9767. auto boxedValue = mModule->mBfIRBuilder->CreateLoad(boxedValueAddr);
  9768. mModule->mBfIRBuilder->CreateStore(boxedValue, nullableValueAddr);
  9769. }
  9770. mModule->mBfIRBuilder->CreateBr(endBB);
  9771. mModule->AddBasicBlock(endBB);
  9772. mResult = BfTypedValue(allocaInst, targetType, true);
  9773. _CheckResult();
  9774. return;
  9775. }
  9776. targetValue = mModule->LoadValue(targetValue);
  9777. if (targetType->IsValueType())
  9778. {
  9779. mModule->Fail("Invalid dynamic cast type", dynCastExpr->mTypeRef);
  9780. return;
  9781. }
  9782. BfTypeInstance* srcTypeInstance = targetValue.mType->ToTypeInstance();
  9783. BfTypeInstance* targetTypeInstance = targetType->ToTypeInstance();
  9784. if (mModule->TypeIsSubTypeOf(srcTypeInstance, targetTypeInstance))
  9785. {
  9786. // We don't give this warning when we have wasGenericParmType set because that indicates we had a generic type constraint,
  9787. // and a type constraint infers that the ACTUAL type used will be equal to or derived from that type and therefore
  9788. // it may be a "necessary cast" indeed
  9789. if ((!wasGenericParamType) && (mModule->mCurMethodState->mMixinState == NULL))
  9790. {
  9791. if (srcTypeInstance == targetType)
  9792. mModule->Warn(BfWarning_BF4203_UnnecessaryDynamicCast, StrFormat("Unnecessary cast, the value is already type '%s'",
  9793. mModule->TypeToString(srcTypeInstance).c_str()), dynCastExpr->mAsToken);
  9794. else
  9795. mModule->Warn(BfWarning_BF4203_UnnecessaryDynamicCast, StrFormat("Unnecessary cast, '%s' is a subtype of '%s'",
  9796. mModule->TypeToString(srcTypeInstance).c_str(), mModule->TypeToString(targetType).c_str()), dynCastExpr->mAsToken);
  9797. }
  9798. auto castedValue = mModule->mBfIRBuilder->CreateBitCast(targetValue.mValue, mModule->mBfIRBuilder->MapType(targetTypeInstance));
  9799. mResult = BfTypedValue(castedValue, targetTypeInstance);
  9800. _CheckResult();
  9801. return;
  9802. }
  9803. else if ((!targetType->IsInterface()) && (!mModule->TypeIsSubTypeOf(targetTypeInstance, srcTypeInstance)))
  9804. {
  9805. if (!mModule->IsInSpecializedSection())
  9806. {
  9807. mModule->Fail(StrFormat("Cannot convert type '%s' to '%s' via any conversion",
  9808. mModule->TypeToString(targetValue.mType).c_str(), mModule->TypeToString(targetTypeInstance).c_str()), dynCastExpr->mAsToken);
  9809. }
  9810. mResult = mModule->GetDefaultTypedValue(targetType);
  9811. return;
  9812. }
  9813. if (autoComplete != NULL)
  9814. {
  9815. mResult = mModule->GetDefaultTypedValue(targetType);
  9816. _CheckResult();
  9817. return;
  9818. }
  9819. auto irb = mModule->mBfIRBuilder;
  9820. auto objectType = mModule->mContext->mBfObjectType;
  9821. mModule->PopulateType(objectType, BfPopulateType_Full);
  9822. auto prevBB = mModule->mBfIRBuilder->GetInsertBlock();
  9823. auto endBB = mModule->mBfIRBuilder->CreateBlock("as.end");
  9824. auto matchBlock = irb->CreateBlock("as.match");
  9825. BfIRValue targetVal = mModule->CreateAlloca(targetType);
  9826. irb->CreateStore(irb->CreateConstNull(irb->MapType(targetType)), targetVal);
  9827. mModule->EmitDynamicCastCheck(targetValue, targetType, matchBlock, endBB);
  9828. mModule->AddBasicBlock(matchBlock);
  9829. BfIRValue castedCallResult = mModule->mBfIRBuilder->CreateBitCast(targetValue.mValue, mModule->mBfIRBuilder->MapType(targetType));
  9830. irb->CreateStore(castedCallResult, targetVal);
  9831. irb->CreateBr(endBB);
  9832. mModule->AddBasicBlock(endBB);
  9833. mResult = BfTypedValue(irb->CreateLoad(targetVal), targetType);
  9834. _CheckResult();
  9835. }
  9836. void BfExprEvaluator::Visit(BfCastExpression* castExpr)
  9837. {
  9838. auto autoComplete = GetAutoComplete();
  9839. if ((autoComplete != NULL) && (castExpr->mTypeRef != NULL))
  9840. {
  9841. // 'mayBeIdentifier' because this may be a misidentified cast - it could be a parenthesized expression
  9842. autoComplete->CheckTypeRef(castExpr->mTypeRef, true, true);
  9843. }
  9844. BfType* resolvedType = NULL;
  9845. if ((BfNodeDynCastExact<BfDotTypeReference>(castExpr->mTypeRef) != NULL) && (mExpectingType != NULL))
  9846. {
  9847. //mModule->SetElementType(castExpr->mTypeRef, BfSourceElementType_TypeRef);
  9848. resolvedType = mExpectingType;
  9849. }
  9850. else
  9851. resolvedType = ResolveTypeRef(castExpr->mTypeRef);
  9852. if (resolvedType != NULL)
  9853. mModule->AddDependency(resolvedType, mModule->mCurTypeInstance, BfDependencyMap::DependencyFlag_LocalUsage);
  9854. // If resolvedType is NULL then that's okay- we just leave the following expression uncasted
  9855. if (castExpr->mExpression == NULL)
  9856. {
  9857. mModule->AssertErrorState();
  9858. return;
  9859. }
  9860. auto exprFlags = (BfEvalExprFlags)((mBfEvalExprFlags & BfEvalExprFlags_NoAutoComplete) | BfEvalExprFlags_ExplicitCast);
  9861. mResult = mModule->CreateValueFromExpression(castExpr->mExpression, resolvedType, exprFlags);
  9862. }
  9863. bool BfExprEvaluator::IsExactMethodMatch(BfMethodInstance* methodA, BfMethodInstance* methodB, bool ignoreImplicitParams)
  9864. {
  9865. if (methodA->mReturnType != methodB->mReturnType)
  9866. return false;
  9867. int implicitParamCountA = methodA->GetImplicitParamCount();
  9868. if (methodA->HasExplicitThis())
  9869. implicitParamCountA++;
  9870. int implicitParamCountB = methodB->GetImplicitParamCount();
  9871. if (methodB->HasExplicitThis())
  9872. implicitParamCountB++;
  9873. if (methodA->GetParamCount() - implicitParamCountA != methodB->GetParamCount() - implicitParamCountB)
  9874. return false;
  9875. for (int i = 0; i < (int)methodA->GetParamCount() - implicitParamCountA; i++)
  9876. {
  9877. auto paramA = methodA->GetParamType(i + implicitParamCountA);
  9878. auto paramB = methodB->GetParamType(i + implicitParamCountB);
  9879. if (paramA != paramB)
  9880. return false;
  9881. }
  9882. return true;
  9883. }
  9884. void BfExprEvaluator::ConstResolve(BfExpression* expr)
  9885. {
  9886. BfConstResolver constResolver(mModule);
  9887. constResolver.Resolve(expr);
  9888. mResult = constResolver.mResult;
  9889. }
  9890. BfTypeInstance* BfExprEvaluator::VerifyBaseDelegateType(BfTypeInstance* baseDelegateType)
  9891. {
  9892. mModule->PopulateType(baseDelegateType, BfPopulateType_DataAndMethods);
  9893. if (baseDelegateType->mFieldInstances.size() != 2)
  9894. {
  9895. mModule->AssertErrorState();
  9896. return NULL;
  9897. }
  9898. return baseDelegateType;
  9899. }
  9900. bool BfExprEvaluator::CanBindDelegate(BfDelegateBindExpression* delegateBindExpr, BfMethodInstance** boundMethod, BfType* origMethodExpectingType, BfTypeVector* methodGenericArgumentsSubstitute)
  9901. {
  9902. if ((mExpectingType == NULL) && (origMethodExpectingType == NULL))
  9903. {
  9904. return false;
  9905. }
  9906. bool isGenericMatch = mExpectingType == NULL;
  9907. auto expectingType = mExpectingType;
  9908. if (expectingType == NULL)
  9909. expectingType = origMethodExpectingType;
  9910. auto typeInstance = expectingType->ToTypeInstance();
  9911. if ((typeInstance == NULL) ||
  9912. ((!typeInstance->mTypeDef->mIsDelegate) && (!typeInstance->mTypeDef->mIsFunction)))
  9913. return false;
  9914. mModule->PopulateType(typeInstance, BfPopulateType_DataAndMethods);
  9915. auto methodInstance = mModule->GetRawMethodInstanceAtIdx(typeInstance, 0, "Invoke");
  9916. if (methodInstance == NULL)
  9917. {
  9918. BF_DBG_FATAL("Invoke not found");
  9919. return false;
  9920. }
  9921. if (delegateBindExpr->mTarget == NULL)
  9922. return false;
  9923. BfAutoParentNodeEntry autoParentNodeEntry(mModule, delegateBindExpr);
  9924. SizedArray<BfTypedValueExpression, 4> typedValueExprs;
  9925. typedValueExprs.resize(methodInstance->GetParamCount());
  9926. SizedArray<BfExpression*, 4> args;
  9927. args.resize(methodInstance->GetParamCount());
  9928. auto _FixType = [&](BfType* type)
  9929. {
  9930. if (!isGenericMatch)
  9931. return type;
  9932. auto fixedType = mModule->ResolveGenericType(type, NULL, methodGenericArgumentsSubstitute);
  9933. if (fixedType != NULL)
  9934. return fixedType;
  9935. return (BfType*)mModule->GetPrimitiveType(BfTypeCode_Var);
  9936. };
  9937. auto _TypeMatches = [&](BfType* lhs, BfType* rhs)
  9938. {
  9939. if (lhs == rhs)
  9940. return true;
  9941. return lhs->IsVar();
  9942. };
  9943. for (int i = 0; i < (int) methodInstance->GetParamCount(); i++)
  9944. {
  9945. auto typedValueExpr = &typedValueExprs[i];
  9946. typedValueExpr->mTypedValue.mValue = BfIRValue(BfIRValueFlags_Value, -1);
  9947. typedValueExpr->mTypedValue.mType = _FixType(methodInstance->GetParamType(i));
  9948. typedValueExpr->mRefNode = NULL;
  9949. args[i] = typedValueExpr;
  9950. }
  9951. BfSizedArray<ASTREF(BfTypeReference*)>* methodGenericArguments = NULL;
  9952. if (delegateBindExpr->mGenericArgs != NULL)
  9953. methodGenericArguments = &delegateBindExpr->mGenericArgs->mGenericArgs;
  9954. BfFunctionBindResult bindResult;
  9955. bindResult.mSkipMutCheck = true; // Allow operating on copies
  9956. bindResult.mBindType = expectingType;
  9957. mFunctionBindResult = &bindResult;
  9958. SetAndRestoreValue<bool> ignoreError(mModule->mIgnoreErrors, true);
  9959. DoInvocation(delegateBindExpr->mTarget, delegateBindExpr, args, methodGenericArguments);
  9960. mFunctionBindResult = NULL;
  9961. if (bindResult.mMethodInstance == NULL)
  9962. return false;
  9963. if (boundMethod != NULL)
  9964. *boundMethod = bindResult.mMethodInstance;
  9965. auto matchedMethod = bindResult.mMethodInstance;
  9966. if (!_TypeMatches(_FixType(methodInstance->mReturnType), matchedMethod->mReturnType))
  9967. return false;
  9968. int implicitParamCountA = methodInstance->GetImplicitParamCount();
  9969. int implicitParamCountB = matchedMethod->GetImplicitParamCount();
  9970. if (methodInstance->GetParamCount() - implicitParamCountA != matchedMethod->GetParamCount() - implicitParamCountB)
  9971. return false;
  9972. for (int i = 0; i < (int)methodInstance->GetParamCount() - implicitParamCountA; i++)
  9973. {
  9974. auto paramA = _FixType(methodInstance->GetParamType(i + implicitParamCountA));
  9975. auto paramB = _FixType(matchedMethod->GetParamType(i + implicitParamCountB));
  9976. if (!_TypeMatches(paramA, paramB))
  9977. return false;
  9978. }
  9979. return true;
  9980. }
  9981. BfTypedValue BfExprEvaluator::DoImplicitArgCapture(BfAstNode* refNode, BfIdentifierNode* identifierNode, int shadowIdx)
  9982. {
  9983. String findName = identifierNode->ToString();
  9984. if (mModule->mCurMethodState != NULL)
  9985. {
  9986. auto rootMethodState = mModule->mCurMethodState->GetRootMethodState();
  9987. auto checkMethodState = mModule->mCurMethodState;
  9988. bool isMixinOuterVariablePass = false;
  9989. int shadowSkip = shadowIdx;
  9990. while (checkMethodState != NULL)
  9991. {
  9992. BP_ZONE("LookupIdentifier:DoImplicitArgCapture");
  9993. BfTypeInstance* closureTypeInst = NULL;
  9994. BfClosureInstanceInfo* closureInstanceInfo = NULL;
  9995. if ((checkMethodState->mClosureState != NULL) && (checkMethodState->mClosureState->mClosureType != NULL) && (!checkMethodState->mClosureState->mCapturing))
  9996. {
  9997. closureTypeInst = mModule->mCurMethodState->mClosureState->mClosureType;
  9998. }
  9999. BfLocalVarEntry* entry;
  10000. if (checkMethodState->mLocalVarSet.TryGetWith<StringImpl&>(findName, &entry))
  10001. {
  10002. auto varDecl = entry->mLocalVar;
  10003. while (varDecl != NULL)
  10004. {
  10005. if (varDecl->mNameNode == identifierNode)
  10006. {
  10007. if (shadowSkip > 0)
  10008. {
  10009. shadowSkip--;
  10010. }
  10011. else
  10012. {
  10013. BfTypedValue localResult = LoadLocal(varDecl);
  10014. if (!isMixinOuterVariablePass)
  10015. {
  10016. mResultLocalVar = varDecl;
  10017. mResultFieldInstance = NULL;
  10018. mResultLocalVarRefNode = identifierNode;
  10019. }
  10020. return localResult;
  10021. }
  10022. }
  10023. varDecl = varDecl->mShadowedLocal;
  10024. }
  10025. }
  10026. // Check for the captured locals. It's important we do it here so we get local-first precedence still
  10027. if (closureTypeInst != NULL)
  10028. {
  10029. closureTypeInst->mTypeDef->PopulateMemberSets();
  10030. BfMemberSetEntry* memberSetEntry = NULL;
  10031. if (closureTypeInst->mTypeDef->mFieldSet.TryGetWith(findName, &memberSetEntry))
  10032. {
  10033. auto fieldDef = (BfFieldDef*)memberSetEntry->mMemberDef;
  10034. while (fieldDef != NULL)
  10035. {
  10036. BfIdentifierNode* fieldNameNode = NULL;
  10037. if (fieldDef->mIdx < (int)checkMethodState->mClosureState->mClosureInstanceInfo->mCaptureEntries.size())
  10038. fieldNameNode = checkMethodState->mClosureState->mClosureInstanceInfo->mCaptureEntries[fieldDef->mIdx].mNameNode;
  10039. if (fieldNameNode == identifierNode)
  10040. {
  10041. auto& field = closureTypeInst->mFieldInstances[fieldDef->mIdx];
  10042. if (!field.mResolvedType->IsValuelessType())
  10043. {
  10044. if (mModule->mCurMethodState->mClosureState->mCapturing)
  10045. {
  10046. mModule->mCurMethodState->mClosureState->mReferencedOuterClosureMembers.Add(&field);
  10047. return mModule->GetDefaultTypedValue(field.mResolvedType);
  10048. }
  10049. auto localVar = mModule->mCurMethodState->mLocals[0];
  10050. auto thisValue = localVar->mValue;
  10051. mModule->mBfIRBuilder->PopulateType(localVar->mResolvedType);
  10052. BfTypedValue result = BfTypedValue(mModule->mBfIRBuilder->CreateInBoundsGEP(thisValue, 0, field.mDataIdx), field.mResolvedType, true);
  10053. if (field.mResolvedType->IsRef())
  10054. {
  10055. auto refType = (BfRefType*)field.mResolvedType;
  10056. auto underlyingType = refType->GetUnderlyingType();
  10057. result = BfTypedValue(mModule->mBfIRBuilder->CreateLoad(result.mValue), underlyingType, true);
  10058. }
  10059. else if (fieldDef->mIsReadOnly)
  10060. result = mModule->LoadValue(result);
  10061. mResultLocalVar = localVar;
  10062. mResultFieldInstance = &field;
  10063. mResultLocalVarField = -(field.mMergedDataIdx + 1);
  10064. return result;
  10065. }
  10066. }
  10067. fieldDef = fieldDef->mNextWithSameName;
  10068. }
  10069. }
  10070. }
  10071. if ((checkMethodState->mClosureState != NULL) && (checkMethodState->mClosureState->mCapturing) /*&& (checkMethodState->mClosureState->mIsLocalMethod)*/)
  10072. {
  10073. checkMethodState = checkMethodState->mPrevMethodState;
  10074. continue;
  10075. }
  10076. // Allow local mixin to see outside variables during its processing -- since we don't actually "capture" those into params
  10077. bool isLocalMixinProcessing = false;
  10078. if ((checkMethodState->mClosureState != NULL) && (!checkMethodState->mClosureState->mCapturing) && (closureTypeInst == NULL) &&
  10079. (mModule->mCurMethodInstance->mMethodDef->mMethodType == BfMethodType_Mixin))
  10080. isLocalMixinProcessing = true;
  10081. if (!isLocalMixinProcessing)
  10082. break;
  10083. isMixinOuterVariablePass = true;
  10084. checkMethodState = checkMethodState->mPrevMethodState;
  10085. }
  10086. }
  10087. return BfTypedValue();
  10088. }
  10089. BfTypedValue BfExprEvaluator::DoImplicitArgCapture(BfAstNode* refNode, BfMethodInstance* methodInstance, int paramIdx, bool& failed, BfImplicitParamKind paramKind, const BfTypedValue& methodRefTarget)
  10090. {
  10091. if ((methodRefTarget) && (methodRefTarget.mValue.mId != BfIRValue::ID_IMPLICIT))
  10092. {
  10093. if (methodRefTarget.mType->IsMethodRef())
  10094. {
  10095. BfMethodRefType* methodRefType = (BfMethodRefType*)methodRefTarget.mType;
  10096. BfMethodInstance* methodRefMethodInst = methodRefType->mMethodRef;
  10097. BF_ASSERT(methodRefMethodInst == methodInstance);
  10098. auto paramType = methodInstance->GetParamType(paramIdx);
  10099. int dataIdx = methodRefType->GetDataIdxFromParamIdx(paramIdx);
  10100. if (dataIdx == -1)
  10101. {
  10102. BF_ASSERT(paramType->IsValuelessType());
  10103. return BfTypedValue(mModule->mBfIRBuilder->GetFakeVal(), paramType);
  10104. }
  10105. if (methodRefTarget.IsSplat())
  10106. {
  10107. if (methodRefType->WantsDataPassedAsSplat(dataIdx))
  10108. {
  10109. BF_ASSERT(paramIdx == -1);
  10110. return BfTypedValue(methodRefTarget.mValue, paramType, BfTypedValueKind_SplatHead);
  10111. }
  10112. else
  10113. {
  10114. int splatIdx = dataIdx;
  10115. if (dataIdx > 0)
  10116. {
  10117. if (methodRefType->WantsDataPassedAsSplat(0))
  10118. splatIdx += methodRefType->GetCaptureType(0)->GetSplatCount() - 1;
  10119. }
  10120. bool isAddr = false;
  10121. BfIRValue value = mModule->ExtractSplatValue(methodRefTarget, splatIdx, paramType, &isAddr);
  10122. // We moved the composite load from ExtractSplatValue to here. Hopefully this is correct.
  10123. // 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)
  10124. // if ((paramType->IsComposite()) && (mModule->IsTargetingBeefBackend()))
  10125. // value = mModule->mBfIRBuilder->CreateLoad(value);
  10126. auto lookupVal = BfTypedValue(value, paramType, isAddr);
  10127. if ((isAddr) && (!lookupVal.mType->IsComposite()))
  10128. lookupVal = mModule->LoadValue(lookupVal);
  10129. return lookupVal;
  10130. }
  10131. }
  10132. if ((paramType->IsComposite()) && (methodRefTarget.IsAddr()))
  10133. return BfTypedValue(mModule->mBfIRBuilder->CreateInBoundsGEP(methodRefTarget.mValue, 0, dataIdx), paramType, true);
  10134. return BfTypedValue(mModule->ExtractValue(methodRefTarget, dataIdx), paramType);
  10135. }
  10136. }
  10137. // 'Default' implicit arg lookup, by identifier. May match field (for lambda), or local variable
  10138. if (paramKind == BfImplicitParamKind_General)
  10139. {
  10140. if (paramIdx == -1)
  10141. {
  10142. if (auto delegateBindExpr = BfNodeDynCast<BfDelegateBindExpression>(refNode))
  10143. {
  10144. BfAstNode* thisNode = NULL;
  10145. BfTypedValue thisValue;
  10146. if (auto memberReferenceExpr = BfNodeDynCast<BfMemberReferenceExpression>(delegateBindExpr->mTarget))
  10147. thisNode = memberReferenceExpr->mTarget;
  10148. else if (auto qualifiedNameNode = BfNodeDynCast<BfQualifiedNameNode>(delegateBindExpr->mTarget))
  10149. thisNode = qualifiedNameNode->mLeft;
  10150. else if (auto identifierNode = BfNodeDynCast<BfIdentifierNode>(delegateBindExpr->mTarget))
  10151. {
  10152. // Implicit
  10153. thisValue = mModule->GetThis();
  10154. }
  10155. if (auto thisExpr = BfNodeDynCast<BfExpression>(thisNode))
  10156. {
  10157. thisValue = mModule->CreateValueFromExpression(thisExpr);
  10158. if (!thisValue)
  10159. return BfTypedValue();
  10160. }
  10161. if (thisValue)
  10162. {
  10163. //TODO: handle 'mut', throw error if trying to capture from a non-mut, etc...
  10164. return thisValue;
  10165. }
  10166. }
  10167. }
  10168. String captureName = methodInstance->GetParamName(paramIdx);
  10169. BfIdentifierNode* identifierNode = methodInstance->GetParamNameNode(paramIdx);
  10170. BfTypedValue lookupVal;
  10171. if (identifierNode != NULL)
  10172. {
  10173. lookupVal = DoImplicitArgCapture(refNode, identifierNode, 0);
  10174. }
  10175. else
  10176. {
  10177. lookupVal = LookupIdentifier(NULL, captureName);
  10178. }
  10179. if (lookupVal)
  10180. {
  10181. auto paramType = methodInstance->GetParamType(paramIdx);
  10182. if (paramType->IsRef())
  10183. {
  10184. auto refType = (BfRefType*)paramType;
  10185. if (mResultLocalVar != NULL)
  10186. {
  10187. // When we are capturing, we need to note that we require capturing by reference here
  10188. auto localVar = mResultLocalVar;
  10189. localVar->mWrittenToId = mModule->mCurMethodState->GetRootMethodState()->mCurAccessId++;
  10190. }
  10191. bool isValid = false;
  10192. if ((refType->mRefKind == BfRefType::RefKind_Mut) && (lookupVal.mKind == BfTypedValueKind_MutableValue))
  10193. isValid = true;
  10194. if ((lookupVal.mType->IsRef()) || (lookupVal.IsAddr()))
  10195. isValid = true;
  10196. if (!isValid)
  10197. {
  10198. // Is there another way this can fail than to be in a lambda?
  10199. auto error = mModule->Fail(StrFormat("Method '%s' requires that '%s' be captured by reference. Consider adding by-reference capture specifier [&] to lambda.",
  10200. mModule->MethodToString(methodInstance).c_str(), captureName.c_str()), refNode, true);
  10201. if ((error != NULL) && (methodInstance->mMethodDef->mMethodDeclaration != NULL))
  10202. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("See method declaration"), methodInstance->mMethodDef->GetRefNode());
  10203. failed = true;
  10204. }
  10205. }
  10206. else
  10207. {
  10208. if (lookupVal.mType->IsRef())
  10209. lookupVal = mModule->RemoveRef(lookupVal);
  10210. if (!lookupVal.mType->IsComposite())
  10211. lookupVal = mModule->LoadValue(lookupVal);
  10212. }
  10213. return lookupVal;
  10214. }
  10215. else
  10216. {
  10217. mModule->Fail(StrFormat("Failed to lookup implicit capture '%s'", captureName.c_str()), refNode, true);
  10218. failed = true;
  10219. return BfTypedValue();
  10220. }
  10221. }
  10222. return BfTypedValue();
  10223. }
  10224. void BfExprEvaluator::Visit(BfDelegateBindExpression* delegateBindExpr)
  10225. {
  10226. BfAutoParentNodeEntry autoParentNodeEntry(mModule, delegateBindExpr);
  10227. if (mExpectingType == NULL)
  10228. {
  10229. mModule->Fail("Cannot infer delegate type", delegateBindExpr);
  10230. return;
  10231. }
  10232. BfTokenNode* newToken = NULL;
  10233. BfAllocTarget allocTarget = ResolveAllocTarget(delegateBindExpr->mNewToken, newToken);
  10234. SizedArray<BfTypedValueExpression, 4> typedValueExprs;
  10235. SizedArray<BfExpression*, 4> args;
  10236. BfTypeInstance* delegateTypeInstance = NULL;
  10237. BfMethodInstance* methodInstance = NULL;
  10238. const char* bindTypeName = NULL;
  10239. bool isMethodRefMatch = false;
  10240. if (mExpectingType->IsMethodRef())
  10241. {
  10242. auto methodRefType = (BfMethodRefType*)mExpectingType;
  10243. BF_ASSERT(delegateBindExpr->mNewToken == NULL);
  10244. methodInstance = methodRefType->mMethodRef;
  10245. isMethodRefMatch = true;
  10246. }
  10247. else
  10248. {
  10249. if (mExpectingType->IsGenericParam())
  10250. {
  10251. auto genericParamInstance = mModule->GetGenericParamInstance((BfGenericParamType*)mExpectingType);
  10252. if ((genericParamInstance->mTypeConstraint != NULL) && (genericParamInstance->mTypeConstraint->IsDelegate()))
  10253. {
  10254. delegateTypeInstance = genericParamInstance->mTypeConstraint->ToTypeInstance();
  10255. }
  10256. }
  10257. else
  10258. delegateTypeInstance = mExpectingType->ToTypeInstance();
  10259. if ((delegateTypeInstance == NULL) ||
  10260. ((!delegateTypeInstance->IsDelegate()) && (!delegateTypeInstance->IsFunction())))
  10261. {
  10262. mModule->Fail(StrFormat("Type '%s' cannot be used for method binding. Only delegate or function types are allowed.", mModule->TypeToString(mExpectingType).c_str()), delegateBindExpr);
  10263. return;
  10264. }
  10265. bindTypeName = (delegateTypeInstance->IsDelegate()) ? "delegate" : "function";
  10266. mModule->PopulateType(delegateTypeInstance, BfPopulateType_DataAndMethods);
  10267. methodInstance = mModule->GetRawMethodInstanceAtIdx(delegateTypeInstance, 0, "Invoke");
  10268. if (methodInstance == NULL)
  10269. {
  10270. BF_DBG_FATAL("Invoke not found");
  10271. return;
  10272. }
  10273. if (auto tokenNode = BfNodeDynCast<BfTokenNode>(delegateBindExpr->mNewToken))
  10274. {
  10275. if (delegateTypeInstance->IsFunction())
  10276. mModule->Fail("Function bindings are direct assignments, allocation specifier is not applicable", delegateBindExpr->mNewToken);
  10277. else if (tokenNode->GetToken() == BfToken_Append)
  10278. {
  10279. mModule->Fail("Append allocation on delegate bind not supported", delegateBindExpr->mNewToken);
  10280. }
  10281. }
  10282. }
  10283. int paramOffset = methodInstance->HasExplicitThis() ? 1 : 0;
  10284. typedValueExprs.resize(methodInstance->GetParamCount() - paramOffset);
  10285. args.resize(methodInstance->GetParamCount() - paramOffset);
  10286. for (int i = 0; i < (int)methodInstance->GetParamCount() - paramOffset; i++)
  10287. {
  10288. auto typedValueExpr = &typedValueExprs[i];
  10289. typedValueExpr->mTypedValue.mValue = BfIRValue(BfIRValueFlags_Value, -1);
  10290. typedValueExpr->mTypedValue.mType = methodInstance->GetParamType(i + paramOffset);
  10291. typedValueExpr->mRefNode = NULL;
  10292. args[i] = typedValueExpr;
  10293. }
  10294. BfSizedArray<ASTREF(BfTypeReference*)>* methodGenericArguments = NULL;
  10295. if (delegateBindExpr->mGenericArgs != NULL)
  10296. methodGenericArguments = &delegateBindExpr->mGenericArgs->mGenericArgs;
  10297. if (delegateBindExpr->mTarget == NULL)
  10298. {
  10299. mModule->AssertErrorState();
  10300. return;
  10301. }
  10302. auto autoComplete = GetAutoComplete();
  10303. if (autoComplete != NULL)
  10304. {
  10305. SetAndRestoreValue<bool> prevForceAllowNonStatic(autoComplete->mForceAllowNonStatic, methodInstance->mMethodDef->mHasExplicitThis);
  10306. GetAutoComplete()->CheckNode(delegateBindExpr->mTarget);
  10307. }
  10308. if ((!delegateBindExpr->mTarget->IsA<BfIdentifierNode>()) &&
  10309. (!delegateBindExpr->mTarget->IsA<BfMemberReferenceExpression>()))
  10310. {
  10311. mModule->Fail(StrFormat("Invalid %s binding target, %s can only bind to method references. Consider wrapping expression in a lambda.", bindTypeName, bindTypeName), delegateBindExpr->mTarget);
  10312. mModule->CreateValueFromExpression(delegateBindExpr->mTarget);
  10313. return;
  10314. }
  10315. BfFunctionBindResult bindResult;
  10316. bindResult.mSkipMutCheck = true; // Allow operating on copies
  10317. bindResult.mBindType = delegateTypeInstance;
  10318. //
  10319. {
  10320. SetAndRestoreValue<BfType*> prevExpectingType(mExpectingType, methodInstance->mReturnType);
  10321. mFunctionBindResult = &bindResult;
  10322. DoInvocation(delegateBindExpr->mTarget, delegateBindExpr, args, methodGenericArguments);
  10323. mFunctionBindResult = NULL;
  10324. }
  10325. SetMethodElementType(delegateBindExpr->mTarget);
  10326. if (bindResult.mMethodInstance == NULL)
  10327. {
  10328. if ((mResult) && (mResult.mType->IsVar()))
  10329. return;
  10330. mResult = BfTypedValue();
  10331. return;
  10332. }
  10333. auto bindMethodInstance = bindResult.mMethodInstance;
  10334. if (isMethodRefMatch)
  10335. {
  10336. // WTF- this was always false, what was it supposed to catch?
  10337. // if (bindMethodInstance != bindResult.mMethodInstance)
  10338. // {
  10339. // mResult = BfTypedValue();
  10340. // return;
  10341. // }
  10342. }
  10343. else
  10344. {
  10345. bool isExactMethodMatch = IsExactMethodMatch(methodInstance, bindMethodInstance, true);
  10346. if ((mExpectingType != NULL) && (mExpectingType->IsFunction()) && (methodInstance->mMethodDef->mIsMutating != bindMethodInstance->mMethodDef->mIsMutating))
  10347. isExactMethodMatch = false;
  10348. if (!isExactMethodMatch)
  10349. {
  10350. if (bindResult.mCheckedMultipleMethods)
  10351. {
  10352. mModule->Fail(StrFormat("No overload for '%s' matches %s '%s'", bindMethodInstance->mMethodDef->mName.c_str(), bindTypeName,
  10353. mModule->TypeToString(delegateTypeInstance).c_str()), delegateBindExpr->mTarget);
  10354. }
  10355. else
  10356. {
  10357. mModule->Fail(StrFormat("Method '%s' does not match %s '%s'", mModule->MethodToString(bindMethodInstance, (BfMethodNameFlags)(BfMethodNameFlag_ResolveGenericParamNames | BfMethodNameFlag_IncludeReturnType | BfMethodNameFlag_IncludeMut)).c_str(), bindTypeName,
  10358. mModule->TypeToString(delegateTypeInstance).c_str()), delegateBindExpr->mTarget);
  10359. }
  10360. mResult = BfTypedValue();
  10361. return;
  10362. }
  10363. }
  10364. bool isDirectFunction = false;
  10365. if ((bindResult.mMethodInstance->GetOwner()->IsFunction()) && (bindResult.mFunc))
  10366. isDirectFunction = true;
  10367. if (bindMethodInstance->mIsIntrinsic)
  10368. {
  10369. 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);
  10370. mResult = BfTypedValue();
  10371. return;
  10372. }
  10373. bool hasIncompatibleCallingConventions = !mModule->mSystem->IsCompatibleCallingConvention(methodInstance->mCallingConvention, bindMethodInstance->mCallingConvention);
  10374. auto _GetInvokeMethodName = [&]()
  10375. {
  10376. String methodName = "Invoke$";
  10377. methodName += mModule->mCurMethodInstance->mMethodDef->mName;
  10378. int prevSepPos = (int)methodName.LastIndexOf('$');
  10379. if (prevSepPos > 6)
  10380. {
  10381. methodName.RemoveToEnd(prevSepPos);
  10382. }
  10383. auto rootMethodState = mModule->mCurMethodState->GetRootMethodState();
  10384. HashContext hashCtx;
  10385. if (mModule->mCurMethodInstance->mMethodDef->mDeclaringType->mPartialIdx != -1)
  10386. hashCtx.Mixin(mModule->mCurMethodInstance->mMethodDef->mDeclaringType->mPartialIdx);
  10387. if (delegateBindExpr->mFatArrowToken != NULL)
  10388. {
  10389. hashCtx.Mixin(delegateBindExpr->mFatArrowToken->GetStartCharId());
  10390. }
  10391. if (rootMethodState->mMethodInstance->mMethodInfoEx != NULL)
  10392. {
  10393. for (auto methodGenericArg : rootMethodState->mMethodInstance->mMethodInfoEx->mMethodGenericArguments)
  10394. {
  10395. StringT<128> genericTypeName;
  10396. BfMangler::Mangle(genericTypeName, mModule->mCompiler->GetMangleKind(), methodGenericArg);
  10397. hashCtx.MixinStr(genericTypeName);
  10398. }
  10399. }
  10400. Val128 hashVal = hashCtx.Finish128();
  10401. methodName += '$';
  10402. methodName += BfTypeUtils::HashEncode64(hashVal.mLow);
  10403. String mangledName;
  10404. BfMangler::MangleMethodName(mangledName, mModule->mCompiler->GetMangleKind(), mModule->mCurTypeInstance, methodName);
  10405. return mangledName;
  10406. };
  10407. if ((delegateBindExpr->mNewToken == NULL) || (delegateTypeInstance->IsFunction()))
  10408. {
  10409. if ((mModule->mCurMethodState != NULL) && (mModule->mCurMethodState->mHotDataReferenceBuilder != NULL))
  10410. {
  10411. BF_ASSERT(bindResult.mMethodInstance->mHotMethod != NULL);
  10412. mModule->mCurMethodState->mHotDataReferenceBuilder->mFunctionPtrs.Add(bindResult.mMethodInstance->mHotMethod);
  10413. }
  10414. if (isDirectFunction)
  10415. {
  10416. //if ((delegateTypeInstance != NULL) && (delegateTypeInstance->IsFunction()))
  10417. if (mExpectingType->IsFunction())
  10418. {
  10419. auto intPtrVal = mModule->mBfIRBuilder->CreatePtrToInt(bindResult.mFunc, BfTypeCode_IntPtr);
  10420. mResult = BfTypedValue(intPtrVal, mExpectingType);
  10421. return;
  10422. }
  10423. }
  10424. if (mExpectingType->IsFunction())
  10425. {
  10426. BfIRValue result;
  10427. if ((hasIncompatibleCallingConventions) && (mModule->HasExecutedOutput()))
  10428. {
  10429. //
  10430. {
  10431. SetAndRestoreValue<bool> prevIgnore(mModule->mBfIRBuilder->mIgnoreWrites, true);
  10432. result = mModule->CastToFunction(delegateBindExpr->mTarget, bindResult.mOrigTarget, bindResult.mMethodInstance, mExpectingType);
  10433. }
  10434. if (result)
  10435. {
  10436. String methodName = _GetInvokeMethodName();
  10437. SizedArray<BfIRType, 8> irParamTypes;
  10438. BfIRType irReturnType;
  10439. methodInstance->GetIRFunctionInfo(mModule, irReturnType, irParamTypes);
  10440. int thisFuncParamIdx = methodInstance->GetThisIdx();
  10441. int thisBindParamIdx = methodInstance->GetThisIdx();
  10442. auto prevActiveFunction = mModule->mBfIRBuilder->GetActiveFunction();
  10443. auto prevInsertBlock = mModule->mBfIRBuilder->GetInsertBlock();
  10444. mModule->mBfIRBuilder->SaveDebugLocation();
  10445. auto funcType = mModule->mBfIRBuilder->CreateFunctionType(irReturnType, irParamTypes);
  10446. auto funcValue = mModule->mBfIRBuilder->CreateFunction(funcType, BfIRLinkageType_External, methodName);
  10447. auto srcCallingConv = mModule->GetIRCallingConvention(methodInstance);
  10448. mModule->mBfIRBuilder->SetFuncCallingConv(funcValue, srcCallingConv);
  10449. mModule->mBfIRBuilder->SetActiveFunction(funcValue);
  10450. auto entryBlock = mModule->mBfIRBuilder->CreateBlock("entry", true);
  10451. mModule->mBfIRBuilder->SetInsertPoint(entryBlock);
  10452. SizedArray<BfIRValue, 8> irArgs;
  10453. for (int paramIdx = 0; paramIdx < irParamTypes.size(); paramIdx++)
  10454. {
  10455. irArgs.push_back(mModule->mBfIRBuilder->GetArgument(paramIdx));
  10456. }
  10457. auto bindFuncVal = bindResult.mFunc;
  10458. if (mModule->mCompiler->mOptions.mAllowHotSwapping)
  10459. bindFuncVal = mModule->mBfIRBuilder->RemapBindFunction(bindFuncVal);
  10460. auto callResult = mModule->mBfIRBuilder->CreateCall(bindFuncVal, irArgs);
  10461. auto destCallingConv = mModule->GetIRCallingConvention(bindMethodInstance);
  10462. if (destCallingConv != BfIRCallingConv_CDecl)
  10463. mModule->mBfIRBuilder->SetCallCallingConv(callResult, destCallingConv);
  10464. if (methodInstance->mReturnType->IsValuelessType())
  10465. mModule->mBfIRBuilder->CreateRetVoid();
  10466. else
  10467. mModule->mBfIRBuilder->CreateRet(callResult);
  10468. mModule->mBfIRBuilder->SetActiveFunction(prevActiveFunction);
  10469. mModule->mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  10470. mModule->mBfIRBuilder->RestoreDebugLocation();
  10471. result = mModule->mBfIRBuilder->CreatePtrToInt(funcValue, BfTypeCode_IntPtr);
  10472. }
  10473. }
  10474. else
  10475. {
  10476. if ((bindResult.mOrigTarget) && (bindResult.mOrigTarget.mType->IsGenericParam()) && (bindResult.mMethodInstance->GetOwner()->IsInterface()))
  10477. {
  10478. bool matching = true;
  10479. if (methodInstance->HasExplicitThis())
  10480. {
  10481. auto thisType = methodInstance->GetParamType(0);
  10482. if (thisType->IsPointer())
  10483. thisType = thisType->GetUnderlyingType();
  10484. if (thisType->IsRef())
  10485. thisType = thisType->GetUnderlyingType();
  10486. matching = thisType == bindResult.mOrigTarget.mType;
  10487. }
  10488. if (matching)
  10489. {
  10490. mResult = BfTypedValue(mModule->mBfIRBuilder->GetFakeVal(), mExpectingType);
  10491. return;
  10492. }
  10493. }
  10494. result = mModule->CastToFunction(delegateBindExpr->mTarget, bindResult.mOrigTarget, bindResult.mMethodInstance, mExpectingType, BfCastFlags_None, bindResult.mFunc);
  10495. }
  10496. if (result)
  10497. mResult = BfTypedValue(result, mExpectingType);
  10498. return;
  10499. }
  10500. if (bindResult.mMethodInstance->mDisallowCalling)
  10501. {
  10502. BF_ASSERT(mModule->mBfIRBuilder->mIgnoreWrites);
  10503. mResult = mModule->GetDefaultTypedValue(mExpectingType, false, BfDefaultValueKind_Addr);
  10504. return;
  10505. }
  10506. auto methodRefType = mModule->CreateMethodRefType(bindResult.mMethodInstance);
  10507. mModule->AddDependency(methodRefType, mModule->mCurTypeInstance, BfDependencyMap::DependencyFlag_Calls);
  10508. mModule->AddCallDependency(bindResult.mMethodInstance);
  10509. if ((bindResult.mOrigTarget) && (bindResult.mOrigTarget.mType->IsMethodRef()))
  10510. {
  10511. mResult = bindResult.mOrigTarget;
  10512. }
  10513. else
  10514. {
  10515. if ((bindResult.mMethodInstance->mMethodDef->mIsLocalMethod) || (!bindResult.mTarget))
  10516. mResult = BfTypedValue(BfIRValue(BfIRValueFlags_Value, BfIRValue::ID_IMPLICIT), methodRefType);
  10517. else
  10518. {
  10519. auto methodRefPtr = mModule->CreateAlloca(methodRefType, "bindResult");
  10520. auto elemPtr = mModule->mBfIRBuilder->CreateInBoundsGEP(methodRefPtr, 0, 0);
  10521. BfTypedValue target;
  10522. if (bindResult.mTarget.IsSplat())
  10523. target = mModule->AggregateSplat(bindResult.mTarget, &bindResult.mIRArgs[0]);
  10524. else
  10525. target = bindResult.mTarget;
  10526. mModule->mBfIRBuilder->CreateStore(target.mValue, elemPtr);
  10527. mResult = BfTypedValue(methodRefPtr, methodRefType, true);
  10528. }
  10529. }
  10530. return;
  10531. }
  10532. int implicitParamCount = bindMethodInstance->GetImplicitParamCount();
  10533. BfTypeInstance* useTypeInstance = delegateTypeInstance;
  10534. BfClosureType* closureTypeInst = NULL;
  10535. auto origTarget = bindResult.mOrigTarget;
  10536. auto target = bindResult.mTarget;
  10537. BfTypedValue methodRefTarget;
  10538. if ((bindResult.mOrigTarget) && (bindResult.mOrigTarget.mType->IsMethodRef()))
  10539. methodRefTarget = bindResult.mOrigTarget;
  10540. bool isStructTarget = (target) && (target.mType->IsStruct());
  10541. bool bindCapturesThis = bindMethodInstance->HasThis() && !isStructTarget;
  10542. bool needsSplat = (isStructTarget) && (!bindMethodInstance->mMethodDef->mIsMutating) && (bindMethodInstance->AllowsSplatting(-1));
  10543. bool captureThisByValue = isStructTarget;
  10544. if (bindMethodInstance->mMethodDef->mIsLocalMethod)
  10545. {
  10546. // Local method captures always capture 'this' by reference
  10547. captureThisByValue = false;
  10548. }
  10549. if ((origTarget.mType != NULL) &&
  10550. ((origTarget.mType->IsRef()) || (origTarget.mType->IsPointer())))
  10551. {
  10552. captureThisByValue = false;
  10553. }
  10554. if (methodRefTarget)
  10555. BF_ASSERT(methodRefTarget.mType->IsMethodRef());
  10556. if (target.IsSplat())
  10557. target = mModule->AggregateSplat(target, &bindResult.mIRArgs[0]);
  10558. bool hasCaptures = false;
  10559. // Do we need a special delegate type for this?
  10560. if (((captureThisByValue) || (needsSplat) || (implicitParamCount > 0) /*|| (hasIncompatibleCallingConventions)*/) &&
  10561. (mModule->HasExecutedOutput()))
  10562. {
  10563. hasCaptures = true;
  10564. auto curProject = mModule->mCurTypeInstance->mTypeDef->mProject;
  10565. if (captureThisByValue)
  10566. target = mModule->LoadValue(target);
  10567. String delegateTypeName = mModule->TypeToString(delegateTypeInstance);
  10568. HashContext hashCtx;
  10569. hashCtx.MixinStr(delegateTypeName);
  10570. // We mix in the project for reasons described in the lambda binding handler
  10571. hashCtx.MixinStr(curProject->mName);
  10572. String structTargetTypeName;
  10573. String structTargetName;
  10574. // Implicit param separator
  10575. for (int implicitParamIdx = bindMethodInstance->HasThis() ? - 1 : 0; implicitParamIdx < implicitParamCount; implicitParamIdx++)
  10576. {
  10577. auto paramType = bindResult.mMethodInstance->GetParamType(implicitParamIdx);
  10578. if ((implicitParamIdx == -1) && (captureThisByValue))
  10579. {
  10580. if (paramType->IsPointer())
  10581. paramType = paramType->GetUnderlyingType();
  10582. }
  10583. structTargetTypeName = mModule->TypeToString(paramType);
  10584. structTargetName = bindResult.mMethodInstance->GetParamName(implicitParamIdx);
  10585. hashCtx.MixinStr(structTargetTypeName);
  10586. hashCtx.MixinStr(structTargetName);
  10587. }
  10588. Val128 hash128 = hashCtx.Finish128();
  10589. BfClosureType* checkClosureType = new BfClosureType(delegateTypeInstance, hash128);
  10590. checkClosureType->mContext = mModule->mContext;
  10591. checkClosureType->mBaseType = delegateTypeInstance;
  10592. BfType* resolvedClosureType = mModule->ResolveType(checkClosureType, BfPopulateType_TypeDef);
  10593. closureTypeInst = (BfClosureType*)resolvedClosureType;
  10594. if (checkClosureType == resolvedClosureType)
  10595. {
  10596. // This is a new closure type
  10597. closureTypeInst->Init(curProject);
  10598. for (int implicitParamIdx = bindMethodInstance->HasThis() ? -1 : 0; implicitParamIdx < implicitParamCount; implicitParamIdx++)
  10599. {
  10600. String fieldName = bindResult.mMethodInstance->GetParamName(implicitParamIdx);
  10601. BfType* paramType = bindResult.mMethodInstance->GetParamType(implicitParamIdx);
  10602. if ((implicitParamIdx == -1) && (captureThisByValue))
  10603. {
  10604. if (paramType->IsPointer())
  10605. paramType = paramType->GetUnderlyingType();
  10606. }
  10607. if (fieldName == "this")
  10608. fieldName = "__this";
  10609. closureTypeInst->AddField(paramType, fieldName);
  10610. }
  10611. closureTypeInst->Finish();
  10612. mModule->PopulateType(resolvedClosureType, BfPopulateType_Declaration);
  10613. }
  10614. else
  10615. {
  10616. // Already had this entry
  10617. delete checkClosureType;
  10618. }
  10619. useTypeInstance = closureTypeInst;
  10620. }
  10621. mModule->PopulateType(useTypeInstance);
  10622. if (delegateBindExpr->mTarget == NULL)
  10623. {
  10624. mModule->AssertErrorState();
  10625. return;
  10626. }
  10627. mResult = BfTypedValue(mModule->AllocFromType(useTypeInstance, allocTarget, BfIRValue(), BfIRValue(), 0, BfAllocFlags_None), useTypeInstance);
  10628. // Do we need specialized calling code for this?
  10629. BfIRValue funcValue;
  10630. if (((needsSplat) || (implicitParamCount > 0) || (hasIncompatibleCallingConventions)) &&
  10631. (mModule->HasExecutedOutput()))
  10632. {
  10633. int fieldIdx = 0;
  10634. for (int implicitParamIdx = bindMethodInstance->HasThis() ? -1 : 0; implicitParamIdx < implicitParamCount; implicitParamIdx++)
  10635. {
  10636. auto fieldInst = &useTypeInstance->mFieldInstances[fieldIdx];
  10637. int gepIdx = fieldInst->mDataIdx;
  10638. auto fieldPtr = mModule->mBfIRBuilder->CreateInBoundsGEP(mResult.mValue, 0, gepIdx);
  10639. auto fieldType = bindMethodInstance->GetParamType(implicitParamIdx);
  10640. if ((implicitParamIdx == -1) && (captureThisByValue))
  10641. {
  10642. if (fieldType->IsPointer())
  10643. fieldType = fieldType->GetUnderlyingType();
  10644. }
  10645. bool failed = false;
  10646. BfTypedValue lookupVal;
  10647. if (implicitParamIdx == -1)
  10648. lookupVal = target;
  10649. else
  10650. lookupVal = DoImplicitArgCapture(delegateBindExpr->mTarget, bindResult.mMethodInstance, implicitParamIdx, failed, BfImplicitParamKind_General, methodRefTarget);
  10651. if (!lookupVal)
  10652. continue;
  10653. if ((fieldType->IsPointer()) && (lookupVal.mType != fieldType))
  10654. {
  10655. BF_ASSERT(fieldType->GetUnderlyingType() == lookupVal.mType);
  10656. BF_ASSERT(lookupVal.IsAddr());
  10657. }
  10658. else if (!fieldType->IsRef())
  10659. lookupVal = mModule->LoadOrAggregateValue(lookupVal);
  10660. if (lookupVal)
  10661. mModule->mBfIRBuilder->CreateStore(lookupVal.mValue, fieldPtr);
  10662. fieldIdx++;
  10663. }
  10664. String methodName = _GetInvokeMethodName();
  10665. SizedArray<BfIRType, 8> irParamTypes;
  10666. BfIRType irReturnType;
  10667. bool hasThis = false;
  10668. if (hasCaptures)
  10669. {
  10670. hasThis = true;
  10671. methodInstance->GetIRFunctionInfo(mModule, irReturnType, irParamTypes);
  10672. int thisIdx = 0;
  10673. if (GetStructRetIdx(methodInstance) == 0)
  10674. thisIdx = 1;
  10675. irParamTypes[thisIdx] = mModule->mBfIRBuilder->MapType(useTypeInstance);
  10676. }
  10677. else
  10678. {
  10679. BF_ASSERT(hasIncompatibleCallingConventions);
  10680. bindMethodInstance->GetIRFunctionInfo(mModule, irReturnType, irParamTypes);
  10681. hasThis = bindMethodInstance->HasThis();
  10682. }
  10683. auto prevActiveFunction = mModule->mBfIRBuilder->GetActiveFunction();
  10684. auto prevInsertBlock = mModule->mBfIRBuilder->GetInsertBlock();
  10685. mModule->mBfIRBuilder->SaveDebugLocation();
  10686. auto funcType = mModule->mBfIRBuilder->CreateFunctionType(irReturnType, irParamTypes);
  10687. funcValue = mModule->mBfIRBuilder->CreateFunction(funcType, BfIRLinkageType_External, methodName);
  10688. if (GetStructRetIdx(methodInstance) != -1)
  10689. {
  10690. mModule->mBfIRBuilder->Func_AddAttribute(funcValue, GetStructRetIdx(methodInstance) + 1, BfIRAttribute_NoAlias);
  10691. mModule->mBfIRBuilder->Func_AddAttribute(funcValue, GetStructRetIdx(methodInstance) + 1, BfIRAttribute_StructRet);
  10692. }
  10693. auto srcCallingConv = mModule->GetIRCallingConvention(methodInstance);
  10694. if ((!hasThis) && (methodInstance->mCallingConvention == BfCallingConvention_Stdcall))
  10695. srcCallingConv = BfIRCallingConv_StdCall;
  10696. else if (methodInstance->mCallingConvention == BfCallingConvention_Fastcall)
  10697. srcCallingConv = BfIRCallingConv_FastCall;
  10698. mModule->mBfIRBuilder->SetFuncCallingConv(funcValue, srcCallingConv);
  10699. mModule->mBfIRBuilder->SetActiveFunction(funcValue);
  10700. auto entryBlock = mModule->mBfIRBuilder->CreateBlock("entry", true);
  10701. mModule->mBfIRBuilder->SetInsertPoint(entryBlock);
  10702. fieldIdx = 0;
  10703. SizedArray<BfIRValue, 8> irArgs;
  10704. int argIdx = 0;
  10705. if (GetStructRetIdx(bindMethodInstance) == 0)
  10706. {
  10707. irArgs.push_back(mModule->mBfIRBuilder->GetArgument(GetStructRetIdx(methodInstance)));
  10708. argIdx++;
  10709. }
  10710. for (int implicitParamIdx = bindMethodInstance->HasThis() ? -1 : 0; implicitParamIdx < implicitParamCount; implicitParamIdx++)
  10711. {
  10712. auto fieldInst = &useTypeInstance->mFieldInstances[fieldIdx];
  10713. int gepIdx = fieldInst->mDataIdx;
  10714. auto fieldType = bindMethodInstance->GetParamType(implicitParamIdx);
  10715. bool disableSplat = false;
  10716. if ((implicitParamIdx == -1) && (captureThisByValue))
  10717. {
  10718. if (fieldType->IsPointer())
  10719. {
  10720. fieldType = fieldType->GetUnderlyingType();
  10721. disableSplat = true;
  10722. }
  10723. }
  10724. int thisIdx = 0;
  10725. if (GetStructRetIdx(methodInstance) == 0)
  10726. thisIdx = 1;
  10727. auto fieldPtr = mModule->mBfIRBuilder->CreateInBoundsGEP(mModule->mBfIRBuilder->GetArgument(thisIdx), 0, gepIdx);
  10728. BfTypedValue typedVal(fieldPtr, fieldType, true);
  10729. PushArg(typedVal, irArgs, disableSplat);
  10730. fieldIdx++;
  10731. }
  10732. if (hasThis)
  10733. argIdx++;
  10734. if (GetStructRetIdx(bindMethodInstance) == 1)
  10735. {
  10736. irArgs.push_back(mModule->mBfIRBuilder->GetArgument(GetStructRetIdx(methodInstance)));
  10737. argIdx++;
  10738. }
  10739. for (int paramIdx = 0; paramIdx < methodInstance->GetParamCount(); paramIdx++)
  10740. {
  10741. auto paramType = methodInstance->GetParamType(paramIdx);
  10742. if ((paramType->IsSplattable()) && (!IsComptime()))
  10743. {
  10744. BfTypeUtils::SplatIterate([&](BfType* checkType) { irArgs.push_back(mModule->mBfIRBuilder->GetArgument(argIdx++)); }, paramType);
  10745. }
  10746. else if (!paramType->IsValuelessType())
  10747. {
  10748. irArgs.push_back(mModule->mBfIRBuilder->GetArgument(argIdx++));
  10749. }
  10750. }
  10751. auto bindFuncVal = bindResult.mFunc;
  10752. if (mModule->mCompiler->mOptions.mAllowHotSwapping)
  10753. bindFuncVal = mModule->mBfIRBuilder->RemapBindFunction(bindFuncVal);
  10754. auto callInst = mModule->mBfIRBuilder->CreateCall(bindFuncVal, irArgs);
  10755. if (GetStructRetIdx(bindMethodInstance) != -1)
  10756. mModule->mBfIRBuilder->Call_AddAttribute(callInst, GetStructRetIdx(bindMethodInstance) + 1, BfIRAttribute_StructRet);
  10757. auto destCallingConv = mModule->GetIRCallingConvention(bindMethodInstance);
  10758. if (destCallingConv != BfIRCallingConv_CDecl)
  10759. mModule->mBfIRBuilder->SetCallCallingConv(callInst, destCallingConv);
  10760. if ((methodInstance->mReturnType->IsValuelessType()) || (GetStructRetIdx(methodInstance) != -1))
  10761. {
  10762. mModule->mBfIRBuilder->CreateRetVoid();
  10763. }
  10764. else
  10765. {
  10766. mModule->mBfIRBuilder->CreateRet(callInst);
  10767. }
  10768. mModule->mBfIRBuilder->SetActiveFunction(prevActiveFunction);
  10769. mModule->mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  10770. mModule->mBfIRBuilder->RestoreDebugLocation();
  10771. }
  10772. else if ((closureTypeInst != NULL) && (captureThisByValue))
  10773. {
  10774. // 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
  10775. auto fieldPtr = mModule->mBfIRBuilder->CreateInBoundsGEP(mResult.mValue, 0, 1);
  10776. target = mModule->LoadValue(target);
  10777. mModule->mBfIRBuilder->CreateStore(target.mValue, fieldPtr);
  10778. target = BfTypedValue(fieldPtr, target.mType, true);
  10779. }
  10780. BfResolvedArgs resolvedArgs;
  10781. MatchConstructor(delegateBindExpr, delegateBindExpr, mResult, useTypeInstance, resolvedArgs, false, false);
  10782. auto baseDelegateType = VerifyBaseDelegateType(delegateTypeInstance->mBaseType);
  10783. auto baseDelegate = mModule->mBfIRBuilder->CreateBitCast(mResult.mValue, mModule->mBfIRBuilder->MapType(baseDelegateType, BfIRPopulateType_Full));
  10784. // >> delegate.mTarget = bindResult.mTarget
  10785. BfIRValue valPtr;
  10786. if (mModule->HasExecutedOutput())
  10787. {
  10788. if ((implicitParamCount > 0) || (needsSplat)) // Point back to self, it contains capture data
  10789. valPtr = mModule->mBfIRBuilder->CreateBitCast(mResult.mValue, mModule->mBfIRBuilder->GetPrimitiveType(BfTypeCode_NullPtr));
  10790. else if (bindResult.mTarget)
  10791. valPtr = mModule->mBfIRBuilder->CreateBitCast(target.mValue, mModule->mBfIRBuilder->GetPrimitiveType(BfTypeCode_NullPtr));
  10792. else
  10793. valPtr = mModule->GetDefaultValue(mModule->GetPrimitiveType(BfTypeCode_NullPtr));
  10794. auto fieldPtr = mModule->mBfIRBuilder->CreateInBoundsGEP(baseDelegate, 0, 2);
  10795. mModule->mBfIRBuilder->CreateStore(valPtr, fieldPtr);
  10796. }
  10797. if (!funcValue)
  10798. {
  10799. funcValue = bindResult.mFunc;
  10800. if (!funcValue)
  10801. {
  10802. if ((mModule->HasExecutedOutput()) && (!mModule->mBfIRBuilder->mIgnoreWrites))
  10803. mModule->AssertErrorState();
  10804. return;
  10805. }
  10806. if ((mModule->mCompiler->mOptions.mAllowHotSwapping) && (!bindResult.mMethodInstance->mMethodDef->mIsVirtual))
  10807. {
  10808. funcValue = mModule->mBfIRBuilder->RemapBindFunction(funcValue);
  10809. }
  10810. }
  10811. // >> delegate.mFuncPtr = bindResult.mFunc
  10812. auto nullPtrType = mModule->GetPrimitiveType(BfTypeCode_NullPtr);
  10813. valPtr = mModule->mBfIRBuilder->CreateBitCast(funcValue, mModule->mBfIRBuilder->MapType(nullPtrType));
  10814. auto fieldPtr = mModule->mBfIRBuilder->CreateInBoundsGEP(baseDelegate, 0, 1);
  10815. mModule->mBfIRBuilder->CreateStore(valPtr, fieldPtr);
  10816. }
  10817. void BfExprEvaluator::VisitLambdaBodies(BfAstNode* body, BfFieldDtorDeclaration* fieldDtor)
  10818. {
  10819. if (auto blockBody = BfNodeDynCast<BfBlock>(body))
  10820. mModule->VisitChild(blockBody);
  10821. else if (auto bodyExpr = BfNodeDynCast<BfExpression>(body))
  10822. {
  10823. auto result = mModule->CreateValueFromExpression(bodyExpr);
  10824. if ((result) && (mModule->mCurMethodState->mClosureState != NULL) &&
  10825. (mModule->mCurMethodState->mClosureState->mReturnTypeInferState == BfReturnTypeInferState_Inferring))
  10826. mModule->mCurMethodState->mClosureState->mReturnType = result.mType;
  10827. }
  10828. while (fieldDtor != NULL)
  10829. {
  10830. mModule->mCurMethodState->mLeftBlockUncond = false;
  10831. mModule->VisitChild(fieldDtor->mBody);
  10832. fieldDtor = fieldDtor->mNextFieldDtor;
  10833. }
  10834. }
  10835. BfLambdaInstance* BfExprEvaluator::GetLambdaInstance(BfLambdaBindExpression* lambdaBindExpr, BfAllocTarget& allocTarget)
  10836. {
  10837. if (mModule->mCurMethodState == NULL)
  10838. return NULL;
  10839. auto rootMethodState = mModule->mCurMethodState->GetRootMethodState();
  10840. BfAstNodeList cacheNodeList;
  10841. cacheNodeList.mList.Add(lambdaBindExpr);
  10842. ///
  10843. {
  10844. auto checkMethodState = mModule->mCurMethodState;
  10845. while (checkMethodState != NULL)
  10846. {
  10847. if (checkMethodState->mMixinState != NULL)
  10848. cacheNodeList.mList.Add(checkMethodState->mMixinState->mSource);
  10849. checkMethodState = checkMethodState->mPrevMethodState;
  10850. }
  10851. }
  10852. bool isInferReturnType = (mBfEvalExprFlags & BfEvalExprFlags_InferReturnType) != 0;
  10853. BfLambdaInstance* lambdaInstance = NULL;
  10854. if ((!isInferReturnType) && (rootMethodState->mLambdaCache.TryGetValue(cacheNodeList, &lambdaInstance)))
  10855. return lambdaInstance;
  10856. static int sBindCount = 0;
  10857. sBindCount++;
  10858. bool isFunctionBind = false;
  10859. BfTypeInstance* delegateTypeInstance = NULL;
  10860. BfMethodInstance* invokeMethodInstance = NULL;
  10861. if (mExpectingType == NULL)
  10862. {
  10863. mModule->Fail("Cannot infer delegate type", lambdaBindExpr);
  10864. delegateTypeInstance = mModule->ResolveTypeDef(mModule->mCompiler->mActionTypeDef)->ToTypeInstance();
  10865. }
  10866. else
  10867. {
  10868. delegateTypeInstance = mExpectingType->ToTypeInstance();
  10869. if ((delegateTypeInstance == NULL) ||
  10870. ((!delegateTypeInstance->mTypeDef->mIsDelegate) && (!delegateTypeInstance->mTypeDef->mIsFunction)))
  10871. {
  10872. if (lambdaBindExpr->mFatArrowToken != NULL)
  10873. mModule->Fail("Can only bind lambdas to delegate types", lambdaBindExpr->mFatArrowToken);
  10874. delegateTypeInstance = mModule->ResolveTypeDef(mModule->mCompiler->mActionTypeDef)->ToTypeInstance();
  10875. }
  10876. else
  10877. {
  10878. invokeMethodInstance = mModule->GetRawMethodInstanceAtIdx(delegateTypeInstance, 0, "Invoke");
  10879. }
  10880. isFunctionBind = delegateTypeInstance->mTypeDef->mIsFunction;
  10881. }
  10882. if (auto tokenNode = BfNodeDynCast<BfTokenNode>(lambdaBindExpr->mNewToken))
  10883. {
  10884. if (isFunctionBind)
  10885. {
  10886. mModule->Fail("Function lambda binding does not require allocation", lambdaBindExpr->mNewToken);
  10887. }
  10888. else if (tokenNode->GetToken() == BfToken_Append)
  10889. {
  10890. mModule->Fail("Append allocation on delegate bind not supported", lambdaBindExpr->mNewToken);
  10891. }
  10892. }
  10893. if (invokeMethodInstance != NULL)
  10894. {
  10895. if ((int)lambdaBindExpr->mParams.size() < invokeMethodInstance->GetParamCount())
  10896. {
  10897. BfAstNode* refNode = lambdaBindExpr->mCloseParen;
  10898. if (refNode == NULL)
  10899. refNode = lambdaBindExpr;
  10900. mModule->Fail(StrFormat("Not enough parameters for delegate type '%s'. Expected %d more.",
  10901. mModule->TypeToString(delegateTypeInstance).c_str(), invokeMethodInstance->GetParamCount() - lambdaBindExpr->mParams.size()), refNode);
  10902. }
  10903. else if ((int)lambdaBindExpr->mParams.size() > invokeMethodInstance->GetParamCount())
  10904. {
  10905. BfAstNode* refNode = lambdaBindExpr->mParams[invokeMethodInstance->GetParamCount()];
  10906. mModule->Fail(StrFormat("Too many parameters for delegate type '%s'. Expected %d fewer.",
  10907. mModule->TypeToString(delegateTypeInstance).c_str(), lambdaBindExpr->mParams.size() - invokeMethodInstance->GetParamCount()), refNode);
  10908. }
  10909. }
  10910. auto autoComplete = GetAutoComplete();
  10911. bool wasCapturingMethodInfo = false;
  10912. if ((autoComplete != NULL) && (invokeMethodInstance != NULL))
  10913. {
  10914. wasCapturingMethodInfo = autoComplete->mIsCapturingMethodMatchInfo;
  10915. autoComplete->CheckInvocation(lambdaBindExpr, lambdaBindExpr->mOpenParen, lambdaBindExpr->mCloseParen, lambdaBindExpr->mCommas);
  10916. if (autoComplete->mIsCapturingMethodMatchInfo)
  10917. {
  10918. autoComplete->mMethodMatchInfo->mInstanceList.Clear();
  10919. auto methodMatchInfo = autoComplete->mMethodMatchInfo;
  10920. BfAutoComplete::MethodMatchEntry methodMatchEntry;
  10921. methodMatchEntry.mTypeInstance = invokeMethodInstance->GetOwner();
  10922. methodMatchEntry.mCurMethodInstance = mModule->mCurMethodInstance;
  10923. methodMatchEntry.mMethodDef = invokeMethodInstance->mMethodDef;
  10924. autoComplete->mMethodMatchInfo->mInstanceList.push_back(methodMatchEntry);
  10925. methodMatchInfo->mBestIdx = 0;
  10926. methodMatchInfo->mMostParamsMatched = 0;
  10927. int cursorIdx = lambdaBindExpr->GetParser()->mCursorIdx;
  10928. if ((lambdaBindExpr->mCloseParen == NULL) || (cursorIdx <= lambdaBindExpr->mCloseParen->GetSrcStart()))
  10929. {
  10930. int paramIdx = 0;
  10931. for (int commaIdx = 0; commaIdx < (int)lambdaBindExpr->mCommas.size(); commaIdx++)
  10932. {
  10933. auto commaNode = lambdaBindExpr->mCommas[commaIdx];
  10934. if ((commaNode != NULL) && (cursorIdx >= commaNode->GetSrcStart()))
  10935. paramIdx = commaIdx + 1;
  10936. }
  10937. bool isEmpty = true;
  10938. if (paramIdx < (int)lambdaBindExpr->mParams.size())
  10939. {
  10940. auto paramNode = lambdaBindExpr->mParams[paramIdx];
  10941. if (paramNode != NULL)
  10942. isEmpty = false;
  10943. }
  10944. if (isEmpty)
  10945. {
  10946. if (paramIdx < (int)invokeMethodInstance->GetParamCount())
  10947. {
  10948. String paramName = invokeMethodInstance->GetParamName(paramIdx);
  10949. autoComplete->mEntriesSet.Clear();
  10950. if (paramName.IsEmpty())
  10951. paramName += StrFormat("val%d", paramIdx + 1);
  10952. autoComplete->AddEntry(AutoCompleteEntry("paramName", paramName));
  10953. autoComplete->mInsertStartIdx = cursorIdx;
  10954. autoComplete->mInsertEndIdx = cursorIdx;
  10955. if ((paramIdx == 0) && (lambdaBindExpr->mParams.IsEmpty()))
  10956. {
  10957. String totalNames;
  10958. for (int checkIdx = 0; checkIdx < (int)invokeMethodInstance->GetParamCount(); checkIdx++)
  10959. {
  10960. if (!totalNames.IsEmpty())
  10961. totalNames += ", ";
  10962. String paramName = invokeMethodInstance->GetParamName(checkIdx);
  10963. if (paramName.IsEmpty())
  10964. paramName += StrFormat("val%d", checkIdx + 1);
  10965. totalNames += paramName;
  10966. }
  10967. autoComplete->AddEntry(AutoCompleteEntry("paramNames", totalNames));
  10968. }
  10969. }
  10970. }
  10971. }
  10972. }
  10973. }
  10974. defer
  10975. (
  10976. {
  10977. if (autoComplete != NULL)
  10978. autoComplete->mIsCapturingMethodMatchInfo = (wasCapturingMethodInfo) && (!autoComplete->mIsCapturingMethodMatchInfo) && (autoComplete->mMethodMatchInfo != NULL);
  10979. }
  10980. );
  10981. if (lambdaBindExpr->mBody == NULL)
  10982. {
  10983. mModule->AssertErrorState();
  10984. return NULL;
  10985. }
  10986. if ((lambdaBindExpr->mNewToken == NULL) && (isInferReturnType))
  10987. {
  10988. // Method ref, but let this follow infer route
  10989. }
  10990. else if ((lambdaBindExpr->mNewToken == NULL) || (isFunctionBind))
  10991. {
  10992. if ((mModule->mCurMethodState != NULL) && (mModule->mCurMethodState->mClosureState != NULL) && (mModule->mCurMethodState->mClosureState->mCapturing))
  10993. {
  10994. SetAndRestoreValue<bool> prevIgnoreErrors(mModule->mIgnoreErrors, true);
  10995. VisitLambdaBodies(lambdaBindExpr->mBody, lambdaBindExpr->mDtor);
  10996. }
  10997. if ((lambdaBindExpr->mNewToken != NULL) && (isFunctionBind))
  10998. mModule->Fail("Binds to functions should do not require allocations.", lambdaBindExpr->mNewToken);
  10999. if (lambdaBindExpr->mDtor != NULL)
  11000. {
  11001. mModule->Fail("Valueless method reference cannot contain destructor. Consider either removing destructor or using an allocated lambda.", lambdaBindExpr->mDtor->mTildeToken);
  11002. // Eat it
  11003. auto fieldDtor = lambdaBindExpr->mDtor;
  11004. while (fieldDtor != NULL)
  11005. {
  11006. mModule->VisitEmbeddedStatement(fieldDtor->mBody);
  11007. fieldDtor = fieldDtor->mNextFieldDtor;
  11008. }
  11009. }
  11010. if (invokeMethodInstance != NULL)
  11011. {
  11012. BfLocalMethod* localMethod = new BfLocalMethod();
  11013. localMethod->mMethodName = "anon";
  11014. localMethod->mSystem = mModule->mSystem;
  11015. localMethod->mModule = mModule;
  11016. localMethod->mExpectedFullName = mModule->GetLocalMethodName(localMethod->mMethodName, lambdaBindExpr->mFatArrowToken, mModule->mCurMethodState, mModule->mCurMethodState->mMixinState);
  11017. localMethod->mLambdaInvokeMethodInstance = invokeMethodInstance;
  11018. localMethod->mLambdaBindExpr = lambdaBindExpr;
  11019. localMethod->mDeclMethodState = mModule->mCurMethodState;
  11020. mModule->mContext->mLocalMethodGraveyard.push_back(localMethod);
  11021. auto moduleMethodInstance = mModule->GetLocalMethodInstance(localMethod, BfTypeVector());
  11022. if (moduleMethodInstance.mMethodInstance->mDisallowCalling)
  11023. {
  11024. mResult = mModule->GetDefaultTypedValue(mExpectingType, false, BfDefaultValueKind_Addr);
  11025. return NULL;
  11026. }
  11027. auto methodRefType = mModule->CreateMethodRefType(moduleMethodInstance.mMethodInstance);
  11028. mModule->AddDependency(methodRefType, mModule->mCurTypeInstance, BfDependencyMap::DependencyFlag_Calls);
  11029. mModule->AddCallDependency(moduleMethodInstance.mMethodInstance);
  11030. mResult = BfTypedValue(BfIRValue(BfIRValueFlags_Value, BfIRValue::ID_IMPLICIT), methodRefType);
  11031. return NULL;
  11032. }
  11033. }
  11034. //SetAndRestoreValue<bool> prevIgnoreIRWrites(mModule->mBfIRBuilder->mIgnoreWrites, mModule->mWantsIRIgnoreWrites);
  11035. SetAndRestoreValue<bool> prevIgnoreIRWrites(mModule->mBfIRBuilder->mIgnoreWrites, mModule->mWantsIRIgnoreWrites || mModule->mCurMethodInstance->mIsUnspecialized);
  11036. BfTypeInstance* outerClosure = NULL;
  11037. if ((mModule->mCurMethodState->mClosureState != NULL) && (!mModule->mCurMethodState->mClosureState->mCapturing))
  11038. outerClosure = mModule->mCurMethodState->mClosureState->mClosureType;
  11039. Val128 val128(delegateTypeInstance->mTypeId);
  11040. bool isConstEval = ((mBfEvalExprFlags & BfEvalExprFlags_Comptime) != 0);
  11041. BfMethodState methodState;
  11042. methodState.mPrevMethodState = mModule->mCurMethodState;
  11043. BfIRFunctionType funcType;
  11044. auto voidType = mModule->GetPrimitiveType(BfTypeCode_None);
  11045. SizedArray<BfIRType, 0> paramTypes;
  11046. funcType = mModule->mBfIRBuilder->CreateFunctionType(mModule->mBfIRBuilder->MapType(voidType), paramTypes, false);
  11047. auto prevInsertBlock = mModule->mBfIRBuilder->GetInsertBlock();
  11048. BF_ASSERT(prevInsertBlock || isConstEval);
  11049. auto prevActiveFunction = mModule->mBfIRBuilder->GetActiveFunction();
  11050. mModule->mBfIRBuilder->SaveDebugLocation();
  11051. SetAndRestoreValue<bool> prevIgnoreWrites(mModule->mBfIRBuilder->mIgnoreWrites, true);
  11052. BfDeferredLocalAssignData deferredLocalAssignData;
  11053. if (mModule->mCurMethodState->mDeferredLocalAssignData != NULL)
  11054. deferredLocalAssignData.ExtendFrom(mModule->mCurMethodState->mDeferredLocalAssignData);
  11055. SetAndRestoreValue<BfMethodState*> prevMethodState(mModule->mCurMethodState, &methodState);
  11056. methodState.mIRHeadBlock = mModule->mBfIRBuilder->CreateBlock("head", true);
  11057. methodState.mIRInitBlock = mModule->mBfIRBuilder->CreateBlock("init", true);
  11058. methodState.mIREntryBlock = mModule->mBfIRBuilder->CreateBlock("entry", true);
  11059. methodState.mCurScope->mDIScope = prevMethodState.mPrevVal->mCurScope->mDIScope;//invokeMethodInstance->mDIFunction;
  11060. methodState.mCurLocalVarId = -1;
  11061. methodState.mIRFunction = prevMethodState.mPrevVal->mIRFunction;
  11062. methodState.mDeferredLocalAssignData = &deferredLocalAssignData;
  11063. mModule->mBfIRBuilder->SetInsertPoint(methodState.mIREntryBlock);
  11064. BfClosureState closureState;
  11065. if (delegateTypeInstance->IsDelegate())
  11066. closureState.mReturnType = mModule->GetDelegateReturnType(delegateTypeInstance);
  11067. else
  11068. closureState.mReturnType = mModule->mContext->mBfObjectType;
  11069. closureState.mCapturing = true;
  11070. closureState.mDeclaringMethodIsMutating = mModule->mCurMethodInstance->mMethodDef->mIsMutating;
  11071. methodState.mClosureState = &closureState;
  11072. closureState.mClosureType = outerClosure;
  11073. BF_ASSERT(methodState.mCurLocalVarId == -1);
  11074. int outerLocalsCount = (int)methodState.mLocals.size();
  11075. // static int sItrCount = 0;
  11076. // ++sItrCount;
  11077. // int itrCount = sItrCount;
  11078. // if ((itrCount == 8) || (itrCount == 10))
  11079. // {
  11080. // NOP;
  11081. // }
  11082. String delegateTypeName = mModule->TypeToString(delegateTypeInstance);
  11083. HashContext hashCtx;
  11084. hashCtx.MixinStr(delegateTypeName);
  11085. BfSource* bfSource = delegateTypeInstance->mTypeDef->mSource;
  11086. BfMethodDef* methodDef = new BfMethodDef();
  11087. methodDef->mDeclaringType = mModule->mCurMethodInstance->mMethodDef->mDeclaringType;
  11088. Val128 closureMethodHash;
  11089. OwnedVector<BfParameterDeclaration> tempParamDecls;
  11090. if ((autoComplete != NULL) && (autoComplete->mMethodMatchInfo != NULL) && (autoComplete->IsAutocompleteNode(lambdaBindExpr->mBody)))
  11091. {
  11092. // Don't show outer method match info when our cursor is inside a lambda expression (being passed as a parameter)
  11093. autoComplete->RemoveMethodMatchInfo();
  11094. }
  11095. if (invokeMethodInstance != NULL)
  11096. {
  11097. for (int paramIdx = 0; paramIdx < (int)invokeMethodInstance->mMethodDef->mParams.size(); paramIdx++)
  11098. {
  11099. auto invokeParamDef = invokeMethodInstance->mMethodDef->mParams[paramIdx];
  11100. BfParameterDef* paramDef = new BfParameterDef();
  11101. paramDef->mParamDeclaration = tempParamDecls.Alloc();
  11102. BfAstNode::Zero(paramDef->mParamDeclaration);
  11103. BfLocalVariable* localVar = new BfLocalVariable();
  11104. if (paramIdx < (int)lambdaBindExpr->mParams.size())
  11105. {
  11106. localVar->mName = lambdaBindExpr->mParams[paramIdx]->ToString();
  11107. localVar->mNameNode = lambdaBindExpr->mParams[paramIdx];
  11108. paramDef->mParamDeclaration->mNameNode = lambdaBindExpr->mParams[paramIdx];
  11109. }
  11110. else
  11111. {
  11112. mModule->AssertErrorState();
  11113. localVar->mName = invokeParamDef->mName;
  11114. paramDef->mParamDeclaration->mNameNode = NULL;
  11115. }
  11116. paramDef->mName = localVar->mName;
  11117. methodDef->mParams.push_back(paramDef);
  11118. localVar->mResolvedType = invokeMethodInstance->GetParamType(paramIdx);
  11119. mModule->PopulateType(localVar->mResolvedType);
  11120. localVar->mAssignedKind = BfLocalVarAssignKind_Unconditional;
  11121. localVar->mReadFromId = 0;
  11122. auto rootMethodState = methodState.GetRootMethodState();
  11123. localVar->mLocalVarId = rootMethodState->mCurLocalVarId++;
  11124. mModule->DoAddLocalVariable(localVar);
  11125. if (autoComplete != NULL)
  11126. autoComplete->CheckLocalDef(BfNodeDynCast<BfIdentifierNode>(paramDef->mParamDeclaration->mNameNode), methodState.mLocals.back());
  11127. auto resolvePassData = mModule->mCompiler->mResolvePassData;
  11128. if (resolvePassData != NULL)
  11129. resolvePassData->HandleLocalReference(BfNodeDynCast<BfIdentifierNode>(paramDef->mParamDeclaration->mNameNode), mModule->mCurTypeInstance->mTypeDef,
  11130. mModule->mCurMethodInstance->mMethodDef, localVar->mLocalVarId);
  11131. }
  11132. }
  11133. bool isAutocomplete = mModule->mCompiler->IsAutocomplete();
  11134. methodDef->mIdx = mModule->mCurMethodInstance->mMethodDef->mIdx;
  11135. methodDef->mBody = lambdaBindExpr->mBody;
  11136. ///
  11137. auto varMethodState = methodState.mPrevMethodState;
  11138. bool hasExplicitCaptureNames = false;
  11139. for (auto& captureEntry : allocTarget.mCaptureInfo.mCaptures)
  11140. {
  11141. if (captureEntry.mNameNode == NULL)
  11142. {
  11143. hasExplicitCaptureNames = false;
  11144. break;
  11145. }
  11146. hasExplicitCaptureNames = true;
  11147. }
  11148. auto _SetNotCapturedFlag = [&](bool notCaptured)
  11149. {
  11150. auto varMethodState = methodState.mPrevMethodState;
  11151. while (varMethodState != NULL)
  11152. {
  11153. for (int localIdx = 0; localIdx < varMethodState->mLocals.size(); localIdx++)
  11154. {
  11155. auto localVar = varMethodState->mLocals[localIdx];
  11156. localVar->mNotCaptured = notCaptured;
  11157. }
  11158. varMethodState = varMethodState->mPrevMethodState;
  11159. if (varMethodState == NULL)
  11160. break;
  11161. if (varMethodState->mMixinState != NULL)
  11162. break;
  11163. if (varMethodState->mClosureState != NULL)
  11164. {
  11165. if (!varMethodState->mClosureState->mCapturing)
  11166. break;
  11167. }
  11168. }
  11169. };
  11170. if (hasExplicitCaptureNames)
  11171. {
  11172. _SetNotCapturedFlag(true);
  11173. auto varMethodState = methodState.mPrevMethodState;
  11174. while (varMethodState != NULL)
  11175. {
  11176. for (auto& captureEntry : allocTarget.mCaptureInfo.mCaptures)
  11177. {
  11178. if (captureEntry.mNameNode != NULL)
  11179. {
  11180. StringT<64> captureName;
  11181. captureEntry.mNameNode->ToString(captureName);
  11182. BfLocalVarEntry* entry;
  11183. if (varMethodState->mLocalVarSet.TryGetWith<StringImpl&>(captureName, &entry))
  11184. {
  11185. auto localVar = entry->mLocalVar;
  11186. while (localVar != NULL)
  11187. {
  11188. if (autoComplete != NULL)
  11189. autoComplete->CheckLocalRef(captureEntry.mNameNode, localVar);
  11190. if (((mModule->mCurMethodState->mClosureState == NULL) || (mModule->mCurMethodState->mClosureState->mCapturing)) &&
  11191. (mModule->mCompiler->mResolvePassData != NULL) && (mModule->mCurMethodInstance != NULL))
  11192. mModule->mCompiler->mResolvePassData->HandleLocalReference(captureEntry.mNameNode, localVar->mNameNode, mModule->mCurTypeInstance->mTypeDef, rootMethodState->mMethodInstance->mMethodDef, localVar->mLocalVarId);
  11193. localVar->mNotCaptured = false;
  11194. localVar = localVar->mShadowedLocal;
  11195. }
  11196. }
  11197. }
  11198. }
  11199. varMethodState = varMethodState->mPrevMethodState;
  11200. if (varMethodState == NULL)
  11201. break;
  11202. if (varMethodState->mMixinState != NULL)
  11203. break;
  11204. if (varMethodState->mClosureState != NULL)
  11205. {
  11206. if (!varMethodState->mClosureState->mCapturing)
  11207. break;
  11208. }
  11209. }
  11210. }
  11211. BfClosureInstanceInfo* closureInstanceInfo = new BfClosureInstanceInfo();
  11212. auto checkInsertBlock = mModule->mBfIRBuilder->GetInsertBlock();
  11213. closureState.mCaptureStartAccessId = methodState.mPrevMethodState->GetRootMethodState()->mCurAccessId;
  11214. closureState.mCaptureVisitingBody = true;
  11215. closureState.mClosureInstanceInfo = closureInstanceInfo;
  11216. if ((mBfEvalExprFlags & BfEvalExprFlags_InferReturnType) != 0)
  11217. {
  11218. closureState.mReturnType = NULL;
  11219. closureState.mReturnTypeInferState = BfReturnTypeInferState_Inferring;
  11220. }
  11221. VisitLambdaBodies(lambdaBindExpr->mBody, lambdaBindExpr->mDtor);
  11222. if (hasExplicitCaptureNames)
  11223. _SetNotCapturedFlag(false);
  11224. // If we ended up being called by a method with a lower captureStartAccessId, propagate that to whoever is calling us, too...
  11225. if ((methodState.mPrevMethodState->mClosureState != NULL) && (methodState.mPrevMethodState->mClosureState->mCapturing))
  11226. {
  11227. auto prevClosureState = methodState.mPrevMethodState->mClosureState;
  11228. if (closureState.mCaptureStartAccessId < prevClosureState->mCaptureStartAccessId)
  11229. prevClosureState->mCaptureStartAccessId = closureState.mCaptureStartAccessId;
  11230. }
  11231. bool earlyExit = false;
  11232. if (isInferReturnType)
  11233. {
  11234. if ((closureState.mReturnTypeInferState == BfReturnTypeInferState_Fail) ||
  11235. (closureState.mReturnType == NULL))
  11236. {
  11237. mResult = BfTypedValue();
  11238. }
  11239. else
  11240. {
  11241. mResult = BfTypedValue(closureState.mReturnType);
  11242. }
  11243. earlyExit = true;
  11244. }
  11245. else if (mModule->mCurMethodInstance->mIsUnspecialized)
  11246. {
  11247. earlyExit = true;
  11248. mResult = mModule->GetDefaultTypedValue(delegateTypeInstance);
  11249. }
  11250. if (earlyExit)
  11251. {
  11252. prevIgnoreWrites.Restore();
  11253. mModule->mBfIRBuilder->RestoreDebugLocation();
  11254. mModule->mBfIRBuilder->SetActiveFunction(prevActiveFunction);
  11255. if (!prevInsertBlock.IsFake())
  11256. mModule->mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  11257. delete methodDef;
  11258. delete closureInstanceInfo;
  11259. return NULL;
  11260. }
  11261. closureState.mCaptureVisitingBody = false;
  11262. prevIgnoreWrites.Restore();
  11263. mModule->mBfIRBuilder->RestoreDebugLocation();
  11264. auto _GetCaptureType = [&](const StringImpl& str)
  11265. {
  11266. if (allocTarget.mCaptureInfo.mCaptures.IsEmpty())
  11267. return BfCaptureType_Copy;
  11268. for (auto& captureEntry : allocTarget.mCaptureInfo.mCaptures)
  11269. {
  11270. if ((captureEntry.mNameNode == NULL) || (captureEntry.mNameNode->Equals(str)))
  11271. {
  11272. captureEntry.mUsed = true;
  11273. return captureEntry.mCaptureType;
  11274. }
  11275. }
  11276. return BfCaptureType_None;
  11277. };
  11278. Array<BfClosureCapturedEntry> capturedEntries;
  11279. bool copyOuterCaptures = false;
  11280. //
  11281. {
  11282. auto varMethodState = methodState.mPrevMethodState;
  11283. while (varMethodState != NULL)
  11284. {
  11285. for (int localIdx = 0; localIdx < varMethodState->mLocals.size(); localIdx++)
  11286. {
  11287. auto localVar = varMethodState->mLocals[localIdx];
  11288. if ((localVar->mReadFromId >= closureState.mCaptureStartAccessId) || (localVar->mWrittenToId >= closureState.mCaptureStartAccessId))
  11289. {
  11290. if ((localVar->mIsThis) && (outerClosure != NULL))
  11291. {
  11292. continue;
  11293. }
  11294. auto outerLocal = localVar;
  11295. if ((localVar->mConstValue) || (localVar->mResolvedType->IsValuelessType()))
  11296. {
  11297. closureState.mConstLocals.push_back(*outerLocal);
  11298. continue;
  11299. }
  11300. BfClosureCapturedEntry capturedEntry;
  11301. auto capturedType = outerLocal->mResolvedType;
  11302. bool captureByRef = false;
  11303. auto captureType = _GetCaptureType(localVar->mName);
  11304. if (captureType == BfCaptureType_None)
  11305. {
  11306. continue;
  11307. }
  11308. if (!capturedType->IsRef())
  11309. {
  11310. if (captureType == BfCaptureType_Reference)
  11311. {
  11312. if (outerLocal->mIsThis)
  11313. {
  11314. if ((outerLocal->mResolvedType->IsValueType()) && (mModule->mCurMethodInstance->mMethodDef->HasNoThisSplat()))
  11315. captureByRef = true;
  11316. }
  11317. else if ((!localVar->mIsReadOnly) && (localVar->mWrittenToId >= closureState.mCaptureStartAccessId))
  11318. captureByRef = true;
  11319. }
  11320. }
  11321. else
  11322. {
  11323. if ((captureType != BfCaptureType_Reference) || (localVar->mWrittenToId < closureState.mCaptureStartAccessId))
  11324. {
  11325. capturedType = ((BfRefType*)capturedType)->mElementType;
  11326. }
  11327. }
  11328. if (captureByRef)
  11329. {
  11330. capturedType = mModule->CreateRefType(capturedType);
  11331. }
  11332. if (captureType == BfCaptureType_Reference)
  11333. capturedEntry.mExplicitlyByReference = true;
  11334. capturedEntry.mType = capturedType;
  11335. capturedEntry.mNameNode = outerLocal->mNameNode;
  11336. if (outerLocal->mName == "this")
  11337. capturedEntry.mName = "__this";
  11338. else
  11339. {
  11340. capturedEntry.mName = outerLocal->mName;
  11341. BfLocalVarEntry* entry = NULL;
  11342. if (varMethodState->mLocalVarSet.TryGetWith<StringImpl&>(capturedEntry.mName, &entry))
  11343. {
  11344. auto startCheckVar = entry->mLocalVar;
  11345. int shadowIdx = 0;
  11346. auto checkVar = startCheckVar;
  11347. while (checkVar != NULL)
  11348. {
  11349. if (checkVar == outerLocal)
  11350. {
  11351. // We only use mShadowIdx when we have duplicate name nodes (ie: in the case of for looks with iterator vs value)
  11352. auto shadowCheckVar = startCheckVar;
  11353. while (shadowCheckVar != checkVar)
  11354. {
  11355. if (shadowCheckVar->mNameNode == checkVar->mNameNode)
  11356. capturedEntry.mShadowIdx++;
  11357. shadowCheckVar = shadowCheckVar->mShadowedLocal;
  11358. }
  11359. for (int i = 0; i < shadowIdx; i++)
  11360. capturedEntry.mName.Insert(0, '@');
  11361. break;
  11362. }
  11363. shadowIdx++;
  11364. checkVar = checkVar->mShadowedLocal;
  11365. }
  11366. }
  11367. }
  11368. capturedEntries.Add(capturedEntry);
  11369. }
  11370. }
  11371. varMethodState = varMethodState->mPrevMethodState;
  11372. if (varMethodState == NULL)
  11373. break;
  11374. if (varMethodState->mMixinState != NULL)
  11375. break;
  11376. if (varMethodState->mClosureState != NULL)
  11377. {
  11378. if (!varMethodState->mClosureState->mCapturing)
  11379. break;
  11380. }
  11381. }
  11382. }
  11383. for (auto& captureEntry : allocTarget.mCaptureInfo.mCaptures)
  11384. {
  11385. if ((!captureEntry.mUsed) && (captureEntry.mNameNode != NULL))
  11386. mModule->Warn(0, "Capture specifier not used", captureEntry.mNameNode);
  11387. }
  11388. for (auto copyField : closureState.mReferencedOuterClosureMembers)
  11389. {
  11390. auto fieldDef = copyField->GetFieldDef();
  11391. auto captureType = _GetCaptureType(fieldDef->mName);
  11392. BfClosureCapturedEntry capturedEntry;
  11393. capturedEntry.mName = fieldDef->mName;
  11394. capturedEntry.mType = copyField->mResolvedType;
  11395. if ((captureType == BfCaptureType_Reference) && (capturedEntry.mType->IsRef()))
  11396. {
  11397. capturedEntry.mExplicitlyByReference = true;
  11398. }
  11399. else if ((captureType != BfCaptureType_Reference) && (capturedEntry.mType->IsRef()))
  11400. {
  11401. auto refType = (BfRefType*)capturedEntry.mType;
  11402. capturedEntry.mType = refType->mElementType;
  11403. }
  11404. else if ((captureType == BfCaptureType_Reference) && (!capturedEntry.mType->IsRef()) && (!fieldDef->mIsReadOnly))
  11405. {
  11406. capturedEntry.mType = mModule->CreateRefType(capturedEntry.mType);
  11407. }
  11408. }
  11409. std::sort(capturedEntries.begin(), capturedEntries.end());
  11410. bool hasCapture = false;
  11411. BfMethodInstanceGroup methodInstanceGroup;
  11412. methodInstanceGroup.mOwner = mModule->mCurTypeInstance;
  11413. methodInstanceGroup.mOnDemandKind = BfMethodOnDemandKind_AlwaysInclude;
  11414. BfMethodInstance* methodInstance = new BfMethodInstance();
  11415. methodInstance->mMethodInstanceGroup = &methodInstanceGroup;
  11416. methodInstance->GetMethodInfoEx()->mClosureInstanceInfo = closureInstanceInfo;
  11417. if (invokeMethodInstance != NULL)
  11418. methodInstance->mParams = invokeMethodInstance->mParams;
  11419. methodInstance->mIsClosure = true;
  11420. // We want the closure ID to match between hot reloads -- otherwise we wouldn't be able to modify them,
  11421. // so we use the charId from the 'fat arrow' token
  11422. int closureId = 0;
  11423. if (lambdaBindExpr->mFatArrowToken != NULL)
  11424. closureId = lambdaBindExpr->mFatArrowToken->GetStartCharId();
  11425. auto curProject = mModule->mCurTypeInstance->mTypeDef->mProject;
  11426. BF_ASSERT(curProject != NULL);
  11427. // We need to make these per-project even though you'd think we might not because we
  11428. // insert generic type specializations in the generic definition's project,
  11429. // BECAUSE: we would need to scan the captured fields the same way we scan the
  11430. // generic arguments to determine if each project can see it or not in the vdata
  11431. BfTypeInstance* useTypeInstance = delegateTypeInstance;
  11432. BfClosureType* closureTypeInst = NULL;
  11433. if ((capturedEntries.size() != 0) || (lambdaBindExpr->mDtor != NULL) || (copyOuterCaptures))
  11434. {
  11435. hashCtx.MixinStr(curProject->mName);
  11436. if (copyOuterCaptures)
  11437. {
  11438. // String typeName = mModule->DoTypeToString(outerClosure, BfTypeNameFlag_DisambiguateDups);
  11439. // hashCtx.MixinStr(typeName);
  11440. hashCtx.Mixin(outerClosure->mTypeId);
  11441. }
  11442. for (auto& capturedEntry : capturedEntries)
  11443. {
  11444. // String typeName = mModule->DoTypeToString(capturedEntry.mType, BfTypeNameFlag_DisambiguateDups);
  11445. // hashCtx.MixinStr(typeName);
  11446. hashCtx.Mixin(capturedEntry.mType->mTypeId);
  11447. hashCtx.MixinStr(capturedEntry.mName);
  11448. hashCtx.Mixin(capturedEntry.mExplicitlyByReference);
  11449. }
  11450. if (lambdaBindExpr->mDtor != NULL)
  11451. {
  11452. // Has DTOR thunk
  11453. bool hasDtorThunk = true;
  11454. hashCtx.Mixin(hasDtorThunk);
  11455. }
  11456. Val128 hash128 = hashCtx.Finish128();
  11457. BfClosureType* checkClosureType = new BfClosureType(delegateTypeInstance, hash128);
  11458. checkClosureType->mContext = mModule->mContext;
  11459. checkClosureType->mBaseType = delegateTypeInstance;
  11460. BfType* resolvedClosureType = mModule->ResolveType(checkClosureType, BfPopulateType_TypeDef);
  11461. closureTypeInst = (BfClosureType*)resolvedClosureType;
  11462. if (checkClosureType == resolvedClosureType)
  11463. {
  11464. // This is a new closure type
  11465. closureTypeInst->Init(curProject);
  11466. closureTypeInst->mTypeDef->mProject = curProject;
  11467. if (copyOuterCaptures)
  11468. {
  11469. for (auto& fieldInstance : outerClosure->mFieldInstances)
  11470. {
  11471. BfFieldDef* origFieldDef = fieldInstance.GetFieldDef();
  11472. BfFieldDef* fieldDef = closureTypeInst->AddField(fieldInstance.mResolvedType, origFieldDef->mName);
  11473. fieldDef->mIsReadOnly = origFieldDef->mIsReadOnly;
  11474. }
  11475. }
  11476. for (auto& capturedEntry : capturedEntries)
  11477. {
  11478. BfFieldDef* fieldDef = closureTypeInst->AddField(capturedEntry.mType, capturedEntry.mName);
  11479. if (!capturedEntry.mExplicitlyByReference)
  11480. fieldDef->mIsReadOnly = true;
  11481. }
  11482. if (lambdaBindExpr->mDtor != NULL)
  11483. {
  11484. auto dtorDef = closureTypeInst->AddDtor();
  11485. auto voidType = mModule->GetPrimitiveType(BfTypeCode_None);
  11486. auto voidPtrType = mModule->CreatePointerType(voidType);
  11487. closureTypeInst->AddField(voidPtrType, "__dtorThunk");
  11488. }
  11489. closureTypeInst->Finish();
  11490. }
  11491. else
  11492. {
  11493. // Already had this entry
  11494. delete checkClosureType;
  11495. }
  11496. useTypeInstance = closureTypeInst;
  11497. }
  11498. mModule->mBfIRBuilder->PopulateType(useTypeInstance);
  11499. mModule->PopulateType(useTypeInstance);
  11500. // If we are allowing hot swapping, we need to always mangle the name to non-static because if we add a capture
  11501. // later then we need to have the mangled names match
  11502. methodDef->mIsStatic = (closureTypeInst == NULL) && (!mModule->mCompiler->mOptions.mAllowHotSwapping);
  11503. SizedArray<BfIRType, 8> origParamTypes;
  11504. BfIRType origReturnType;
  11505. bool forceStatic = false;
  11506. if (invokeMethodInstance != NULL)
  11507. {
  11508. forceStatic = methodDef->mIsStatic;
  11509. auto invokeFunctionType = mModule->mBfIRBuilder->MapMethod(invokeMethodInstance);
  11510. invokeMethodInstance->GetIRFunctionInfo(mModule, origReturnType, origParamTypes, forceStatic);
  11511. }
  11512. else
  11513. {
  11514. origReturnType = mModule->mBfIRBuilder->MapType(mModule->GetPrimitiveType(BfTypeCode_None));
  11515. }
  11516. SizedArray<BfIRType, 3> newTypes;
  11517. if ((invokeMethodInstance != NULL) && (GetStructRetIdx(invokeMethodInstance, forceStatic) == 0))
  11518. newTypes.push_back(origParamTypes[0]);
  11519. if (!methodDef->mIsStatic)
  11520. newTypes.push_back(mModule->mBfIRBuilder->MapType(useTypeInstance));
  11521. if ((invokeMethodInstance != NULL) && (GetStructRetIdx(invokeMethodInstance, forceStatic) == 1))
  11522. newTypes.push_back(origParamTypes[1]);
  11523. int paramStartIdx = 0;
  11524. if ((invokeMethodInstance != NULL) && (GetStructRetIdx(invokeMethodInstance, forceStatic) != -1))
  11525. paramStartIdx++;
  11526. if (!methodDef->mIsStatic)
  11527. paramStartIdx++;
  11528. for (int i = paramStartIdx; i < (int)origParamTypes.size(); i++)
  11529. newTypes.push_back(origParamTypes[i]);
  11530. auto closureFuncType = mModule->mBfIRBuilder->CreateFunctionType(origReturnType, newTypes, false);
  11531. prevMethodState.Restore();
  11532. mModule->mBfIRBuilder->SetActiveFunction(prevActiveFunction);
  11533. if ((prevInsertBlock) && (!prevInsertBlock.IsFake()))
  11534. mModule->mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  11535. // Just a check
  11536. mModule->mBfIRBuilder->GetInsertBlock();
  11537. //auto rootMethodState = mModule->mCurMethodState;
  11538. HashContext closureHashCtx;
  11539. closureHashCtx.Mixin(closureId);
  11540. // When we're a nested lambda, strip off the outer hash and closureTypeInst markers
  11541. methodDef->mName = mModule->mCurMethodInstance->mMethodDef->mName;
  11542. int prevSepPos = (int)methodDef->mName.LastIndexOf('$');
  11543. if (prevSepPos != -1)
  11544. {
  11545. closureHashCtx.Mixin(methodDef->mName.c_str() + prevSepPos, (int)methodDef->mName.length() - prevSepPos);
  11546. methodDef->mName.RemoveToEnd(prevSepPos);
  11547. }
  11548. // Mix in this because this can be emitted multiple times when there's multiple ctors and field initializers with lambdas
  11549. if (mModule->mCurMethodInstance->mMethodDef->mMethodType == BfMethodType_Ctor)
  11550. {
  11551. if (auto ctorDecl = BfNodeDynCast<BfConstructorDeclaration>(mModule->mCurMethodInstance->mMethodDef->mMethodDeclaration))
  11552. {
  11553. if (ctorDecl->mThisToken != NULL)
  11554. closureHashCtx.Mixin(ctorDecl->mThisToken->GetStartCharId());
  11555. }
  11556. }
  11557. auto checkMethodState = mModule->mCurMethodState;
  11558. while (checkMethodState != NULL)
  11559. {
  11560. if (checkMethodState->mMethodInstance != NULL)
  11561. {
  11562. if (checkMethodState->mMethodInstance->mMethodInfoEx != NULL)
  11563. {
  11564. for (auto methodGenericArg : checkMethodState->mMethodInstance->mMethodInfoEx->mMethodGenericArguments)
  11565. {
  11566. StringT<128> genericTypeName;
  11567. BfMangler::Mangle(genericTypeName, mModule->mCompiler->GetMangleKind(), methodGenericArg);
  11568. closureHashCtx.MixinStr(genericTypeName);
  11569. }
  11570. }
  11571. }
  11572. checkMethodState = checkMethodState->mPrevMethodState;
  11573. }
  11574. uint64 closureHash = closureHashCtx.Finish64();
  11575. methodDef->mName += "$";
  11576. methodDef->mName += BfTypeUtils::HashEncode64(closureHash);
  11577. methodInstance->mMethodDef = methodDef;
  11578. if (invokeMethodInstance != NULL)
  11579. {
  11580. methodInstance->mParams = invokeMethodInstance->mParams;
  11581. methodInstance->mReturnType = invokeMethodInstance->mReturnType;
  11582. }
  11583. else
  11584. methodInstance->mReturnType = mModule->GetPrimitiveType(BfTypeCode_None);
  11585. StringT<128> closureFuncName;
  11586. BfMangler::Mangle(closureFuncName, mModule->mCompiler->GetMangleKind(), methodInstance);
  11587. auto closureFunc = mModule->mBfIRBuilder->CreateFunction(closureFuncType, BfIRLinkageType_External, closureFuncName);
  11588. methodInstance->mIRFunction = closureFunc;
  11589. if (methodInstance->mIsReified)
  11590. mModule->CheckHotMethod(methodInstance, closureFuncName);
  11591. if ((methodInstance->mHotMethod != NULL) && (mModule->mCurMethodState->mHotDataReferenceBuilder))
  11592. mModule->mCurMethodState->mHotDataReferenceBuilder->mInnerMethods.Add(methodInstance->mHotMethod);
  11593. methodState.Reset();
  11594. lambdaInstance = new BfLambdaInstance();
  11595. rootMethodState->mLambdaCache[cacheNodeList] = lambdaInstance;
  11596. lambdaInstance->mDelegateTypeInstance = delegateTypeInstance;
  11597. lambdaInstance->mUseTypeInstance = useTypeInstance;
  11598. lambdaInstance->mClosureTypeInstance = closureTypeInst;
  11599. lambdaInstance->mOuterClosure = outerClosure;
  11600. lambdaInstance->mCopyOuterCaptures = copyOuterCaptures;
  11601. lambdaInstance->mDeclaringMethodIsMutating = mModule->mCurMethodInstance->mMethodDef->mIsMutating;
  11602. lambdaInstance->mIsStatic = methodDef->mIsStatic;
  11603. lambdaInstance->mClosureFunc = closureFunc;
  11604. lambdaInstance->mMethodInstance = methodInstance;
  11605. lambdaInstance->mConstLocals = closureState.mConstLocals;
  11606. lambdaInstance->mParamDecls = tempParamDecls;
  11607. lambdaInstance->mDeclMixinState = mModule->mCurMethodState->mMixinState;
  11608. if (lambdaInstance->mDeclMixinState != NULL)
  11609. lambdaInstance->mDeclMixinState->mHasDeferredUsage = true;
  11610. tempParamDecls.ClearWithoutDeleting();
  11611. closureState.mCapturing = false;
  11612. closureState.mClosureType = useTypeInstance;
  11613. closureInstanceInfo->mThisOverride = useTypeInstance;
  11614. mModule->mIncompleteMethodCount++;
  11615. SetAndRestoreValue<BfClosureState*> prevClosureState(mModule->mCurMethodState->mClosureState, &closureState);
  11616. if (mModule->HasExecutedOutput())
  11617. mModule->SetupIRMethod(methodInstance, methodInstance->mIRFunction, methodInstance->mAlwaysInline);
  11618. // This keeps us from giving errors twice. ProcessMethod can give errors when we capture by value but needed to
  11619. // capture by reference, so we still need to do it for resolve-only
  11620. bool processMethods = (mModule->mCompiler->GetAutoComplete() == NULL) && !mModule->mHadBuildError;
  11621. mModule->mBfIRBuilder->SaveDebugLocation();
  11622. //
  11623. {
  11624. BfGetSymbolReferenceKind prevSymbolRefKind = BfGetSymbolReferenceKind_None;
  11625. if (mModule->mCompiler->mResolvePassData != NULL)
  11626. {
  11627. prevSymbolRefKind = mModule->mCompiler->mResolvePassData->mGetSymbolReferenceKind;
  11628. mModule->mCompiler->mResolvePassData->mGetSymbolReferenceKind = BfGetSymbolReferenceKind_None;
  11629. }
  11630. if (processMethods)
  11631. {
  11632. // If we are in an always-ignored block, we will have mIgnoreWrites set
  11633. // SetAndRestoreValue<bool> prevWantsIgnoreWrite(mModule->mWantsIRIgnoreWrites, mModule->mBfIRBuilder->mIgnoreWrites);
  11634. // mModule->ProcessMethod(methodInstance);
  11635. }
  11636. if (mModule->mCompiler->mResolvePassData != NULL)
  11637. mModule->mCompiler->mResolvePassData->mGetSymbolReferenceKind = prevSymbolRefKind;
  11638. }
  11639. mModule->mBfIRBuilder->RestoreDebugLocation();
  11640. if (mModule->IsSkippingExtraResolveChecks())
  11641. closureFunc = BfIRFunction();
  11642. BfIRFunction dtorFunc;
  11643. if (lambdaBindExpr->mDtor != NULL)
  11644. {
  11645. SizedArray<BfIRType, 1> newTypes;
  11646. newTypes.push_back(mModule->mBfIRBuilder->MapType(useTypeInstance));
  11647. auto voidType = mModule->GetPrimitiveType(BfTypeCode_None);
  11648. auto dtorFuncType = mModule->mBfIRBuilder->CreateFunctionType(mModule->mBfIRBuilder->MapType(voidType), newTypes, false);
  11649. BfMethodDef* dtorMethodDef = new BfMethodDef();
  11650. dtorMethodDef->mDeclaringType = mModule->mCurMethodInstance->mMethodDef->mDeclaringType;
  11651. dtorMethodDef->mName = "~this$";
  11652. dtorMethodDef->mName += methodDef->mName;
  11653. dtorMethodDef->mMethodType = BfMethodType_Normal;
  11654. dtorMethodDef->mBody = lambdaBindExpr->mDtor;
  11655. dtorMethodDef->mIdx = mModule->mCurMethodInstance->mMethodDef->mIdx;
  11656. BfMethodInstance* dtorMethodInstance = new BfMethodInstance();
  11657. dtorMethodInstance->mMethodDef = dtorMethodDef;
  11658. dtorMethodInstance->mReturnType = mModule->GetPrimitiveType(BfTypeCode_None);
  11659. dtorMethodInstance->mMethodInstanceGroup = &methodInstanceGroup;
  11660. StringT<128> dtorMangledName;
  11661. BfMangler::Mangle(dtorMangledName, mModule->mCompiler->GetMangleKind(), dtorMethodInstance);
  11662. dtorFunc = mModule->mBfIRBuilder->CreateFunction(dtorFuncType, BfIRLinkageType_External, dtorMangledName);
  11663. mModule->SetupIRMethod(NULL, dtorFunc, false);
  11664. dtorMethodInstance->mIRFunction = dtorFunc;
  11665. mModule->mIncompleteMethodCount++;
  11666. mModule->mBfIRBuilder->SaveDebugLocation();
  11667. //
  11668. if (processMethods)
  11669. {
  11670. // If we are in an always-ignored block, we will have mIgnoreWrites set
  11671. // SetAndRestoreValue<bool> prevWantsIgnoreWrite(mModule->mWantsIRIgnoreWrites, mModule->mBfIRBuilder->mIgnoreWrites);
  11672. // mModule->ProcessMethod(dtorMethodInstance);
  11673. }
  11674. mModule->mBfIRBuilder->RestoreDebugLocation();
  11675. if (mModule->IsSkippingExtraResolveChecks())
  11676. dtorFunc = BfIRFunction();
  11677. if (dtorMethodInstance->mIsReified)
  11678. mModule->CheckHotMethod(dtorMethodInstance, dtorMangledName);
  11679. if ((dtorMethodInstance->mHotMethod != NULL) && (mModule->mCurMethodState->mHotDataReferenceBuilder))
  11680. mModule->mCurMethodState->mHotDataReferenceBuilder->mInnerMethods.Add(dtorMethodInstance->mHotMethod);
  11681. lambdaInstance->mDtorMethodInstance = dtorMethodInstance;
  11682. lambdaInstance->mDtorFunc = dtorFunc;
  11683. dtorMethodInstance->mMethodInstanceGroup = NULL;
  11684. }
  11685. prevClosureState.Restore();
  11686. if ((prevInsertBlock) && (!prevInsertBlock.IsFake()))
  11687. mModule->mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  11688. for (auto& capturedEntry : capturedEntries)
  11689. {
  11690. BfLambdaCaptureInfo lambdaCapture;
  11691. if (capturedEntry.mName == "__this")
  11692. lambdaCapture.mName = "this";
  11693. else
  11694. lambdaCapture.mName = capturedEntry.mName;
  11695. lambdaInstance->mCaptures.Add(lambdaCapture);
  11696. closureInstanceInfo->mCaptureEntries.Add(capturedEntry);
  11697. }
  11698. if (processMethods)
  11699. rootMethodState->mDeferredLambdaInstances.Add(lambdaInstance);
  11700. methodInstance->mMethodInstanceGroup = NULL;
  11701. return lambdaInstance;
  11702. }
  11703. void BfExprEvaluator::Visit(BfLambdaBindExpression* lambdaBindExpr)
  11704. {
  11705. BfTokenNode* newToken = NULL;
  11706. BfAllocTarget allocTarget = ResolveAllocTarget(lambdaBindExpr->mNewToken, newToken);
  11707. if (mModule->mCurMethodInstance == NULL)
  11708. mModule->Fail("Invalid use of lambda bind expression", lambdaBindExpr);
  11709. if (((mModule->mCurMethodState != NULL) && (mModule->mCurMethodState->mClosureState != NULL) && (mModule->mCurMethodState->mClosureState->mBlindCapturing)) ||
  11710. (mModule->mCurMethodInstance == NULL))
  11711. {
  11712. // We're just capturing. We just need to visit the bodies here. This helps infinite recursion with local methods containing lambdas calling each other
  11713. if (lambdaBindExpr->mBody != NULL)
  11714. mModule->VisitChild(lambdaBindExpr->mBody);
  11715. if ((lambdaBindExpr->mDtor != NULL) && (lambdaBindExpr->mDtor->mBody != NULL))
  11716. mModule->VisitChild(lambdaBindExpr->mDtor->mBody);
  11717. return;
  11718. }
  11719. BfLambdaInstance* lambdaInstance = GetLambdaInstance(lambdaBindExpr, allocTarget);
  11720. if (lambdaInstance == NULL)
  11721. return;
  11722. BfTypeInstance* delegateTypeInstance = lambdaInstance->mDelegateTypeInstance;
  11723. BfTypeInstance* useTypeInstance = lambdaInstance->mUseTypeInstance;
  11724. BfTypeInstance* closureTypeInst = lambdaInstance->mClosureTypeInstance;
  11725. mResult = BfTypedValue(mModule->AllocFromType(useTypeInstance, allocTarget, BfIRValue(), BfIRValue(), 0, BfAllocFlags_None), useTypeInstance);
  11726. if (!delegateTypeInstance->IsDelegate())
  11727. {
  11728. mModule->AssertErrorState();
  11729. return;
  11730. }
  11731. auto baseDelegateType = VerifyBaseDelegateType(delegateTypeInstance->mBaseType);
  11732. if (baseDelegateType == NULL)
  11733. {
  11734. mModule->Fail("Invalid delegate type", lambdaBindExpr);
  11735. return;
  11736. }
  11737. mModule->PopulateType(baseDelegateType);
  11738. auto& funcPtrField = baseDelegateType->mFieldInstances[0];
  11739. auto& targetField = baseDelegateType->mFieldInstances[1];
  11740. auto baseDelegate = mModule->mBfIRBuilder->CreateBitCast(mResult.mValue, mModule->mBfIRBuilder->MapType(baseDelegateType));
  11741. // >> delegate.mTarget = bindResult.mTarget
  11742. auto nullPtrType = mModule->GetPrimitiveType(BfTypeCode_NullPtr);
  11743. BfIRValue valPtr;
  11744. if (!lambdaInstance->mIsStatic)
  11745. valPtr = mModule->mBfIRBuilder->CreateBitCast(mResult.mValue, mModule->mBfIRBuilder->MapType(nullPtrType));
  11746. else
  11747. valPtr = mModule->GetDefaultValue(nullPtrType);
  11748. auto fieldPtr = mModule->mBfIRBuilder->CreateInBoundsGEP(baseDelegate, 0, targetField.mDataIdx);
  11749. mModule->mBfIRBuilder->CreateStore(valPtr, fieldPtr);
  11750. // >> delegate.mFuncPtr = bindResult.mFunc
  11751. if (lambdaInstance->mClosureFunc)
  11752. {
  11753. auto nullPtrType = mModule->GetPrimitiveType(BfTypeCode_NullPtr);
  11754. auto valPtr = mModule->mBfIRBuilder->CreateBitCast(lambdaInstance->mClosureFunc, mModule->mBfIRBuilder->MapType(nullPtrType));
  11755. auto fieldPtr = mModule->mBfIRBuilder->CreateInBoundsGEP(baseDelegate, 0, funcPtrField.mDataIdx);
  11756. mModule->mBfIRBuilder->CreateStore(valPtr, fieldPtr);
  11757. }
  11758. mModule->AddDependency(useTypeInstance, mModule->mCurTypeInstance, BfDependencyMap::DependencyFlag_Calls);
  11759. // Copy captures into the delegate
  11760. if (lambdaInstance->mClosureTypeInstance != NULL)
  11761. {
  11762. int fieldIdx = 0;
  11763. if (lambdaInstance->mCopyOuterCaptures)
  11764. {
  11765. for (auto& fieldInstance : lambdaInstance->mOuterClosure->mFieldInstances)
  11766. {
  11767. if (!fieldInstance.mResolvedType->IsValuelessType())
  11768. {
  11769. BF_ASSERT(fieldInstance.mDataIdx == fieldIdx + 1);
  11770. auto localVar = mModule->mCurMethodState->mLocals[0];
  11771. auto capturedValue = mModule->mBfIRBuilder->CreateInBoundsGEP(localVar->mValue, 0, fieldInstance.mDataIdx);
  11772. capturedValue = mModule->mBfIRBuilder->CreateLoad(capturedValue);
  11773. auto fieldPtr = mModule->mBfIRBuilder->CreateInBoundsGEP(mResult.mValue, 0, fieldInstance.mDataIdx);
  11774. mModule->mBfIRBuilder->CreateStore(capturedValue, fieldPtr);
  11775. fieldIdx++;
  11776. }
  11777. }
  11778. }
  11779. int captureIdx = 0;
  11780. for (int captureIdx = 0; captureIdx < (int)lambdaInstance->mCaptures.size(); captureIdx++)
  11781. {
  11782. auto& capturedEntry = lambdaInstance->mCaptures[captureIdx];
  11783. auto& closureCaptureEntry = lambdaInstance->mMethodInstance->mMethodInfoEx->mClosureInstanceInfo->mCaptureEntries[captureIdx];
  11784. BfIdentifierNode* identifierNode = closureCaptureEntry.mNameNode;
  11785. BfIRValue capturedValue;
  11786. auto fieldInstance = &closureTypeInst->mFieldInstances[fieldIdx];
  11787. BfTypedValue capturedTypedVal;
  11788. if (identifierNode != NULL)
  11789. capturedTypedVal = DoImplicitArgCapture(NULL, identifierNode, closureCaptureEntry.mShadowIdx);
  11790. else
  11791. capturedTypedVal = LookupIdentifier(NULL, capturedEntry.mName);
  11792. if (!fieldInstance->mResolvedType->IsRef())
  11793. capturedTypedVal = mModule->LoadOrAggregateValue(capturedTypedVal);
  11794. else if (!capturedTypedVal.IsAddr())
  11795. {
  11796. mModule->Fail(StrFormat("Unable to capture '%s' by reference", capturedEntry.mName.c_str()), lambdaBindExpr);
  11797. break;
  11798. }
  11799. capturedValue = capturedTypedVal.mValue;
  11800. if (capturedValue)
  11801. {
  11802. if (!capturedTypedVal.mType->IsVar())
  11803. {
  11804. auto fieldPtr = mModule->mBfIRBuilder->CreateInBoundsGEP(mResult.mValue, 0, fieldInstance->mDataIdx);
  11805. mModule->mBfIRBuilder->CreateStore(capturedValue, fieldPtr);
  11806. }
  11807. }
  11808. else
  11809. {
  11810. mModule->Fail(StrFormat("Unable to capture '%s'", capturedEntry.mName.c_str()), lambdaBindExpr);
  11811. mModule->AssertErrorState();
  11812. }
  11813. fieldIdx++;
  11814. }
  11815. if (lambdaInstance->mDtorFunc)
  11816. {
  11817. auto fieldPtr = mModule->mBfIRBuilder->CreateInBoundsGEP(mResult.mValue, 0, closureTypeInst->mFieldInstances[fieldIdx].mDataIdx);
  11818. auto voidType = mModule->GetPrimitiveType(BfTypeCode_None);
  11819. auto voidPtrType = mModule->CreatePointerType(voidType);
  11820. auto dtorThunk = mModule->mBfIRBuilder->CreateBitCast(lambdaInstance->mDtorFunc, mModule->mBfIRBuilder->MapType(voidPtrType));
  11821. mModule->mBfIRBuilder->CreateStore(dtorThunk, fieldPtr);
  11822. fieldIdx++;
  11823. }
  11824. }
  11825. }
  11826. void BfExprEvaluator::ProcessArrayInitializer(BfTokenNode* openToken, const BfSizedArray<BfExpression*>& valueExprs, const BfSizedArray<BfTokenNode*>& commas, BfTokenNode* closeToken, int dimensions, SizedArrayImpl<int64>& dimLengths, int dim, bool& hasFailed)
  11827. {
  11828. bool setSize = false;
  11829. if (dim == dimLengths.size())
  11830. {
  11831. dimLengths.push_back((int)valueExprs.size());
  11832. setSize = true;
  11833. }
  11834. else if (dimLengths[dim] == -1)
  11835. {
  11836. dimLengths[dim] = (int)valueExprs.size();
  11837. setSize = true;
  11838. }
  11839. int64 initCountDiff = (int)valueExprs.size() - dimLengths[dim];
  11840. if ((dimLengths[dim] != -1) && (initCountDiff != 0) && (!hasFailed))
  11841. {
  11842. if (initCountDiff > 0)
  11843. {
  11844. mModule->Fail(StrFormat("Too many initializers, expected %d fewer", initCountDiff), valueExprs[(int)dimLengths[dim]]);
  11845. hasFailed = true;
  11846. }
  11847. else
  11848. {
  11849. // If it ends with ", ?) or ",)" then allow unsized
  11850. if (((valueExprs.size() == 0) || (BfNodeDynCast<BfUninitializedExpression>(valueExprs.back()) == NULL)) &&
  11851. (commas.size() < valueExprs.size()))
  11852. {
  11853. BfAstNode* refNode = closeToken;
  11854. if ((refNode == NULL) && (mModule->mParentNodeEntry != NULL))
  11855. refNode = mModule->mParentNodeEntry->mNode;
  11856. mModule->Fail(StrFormat("Too few initializer, expected %d more", -initCountDiff), refNode);
  11857. hasFailed = true;
  11858. }
  11859. }
  11860. }
  11861. for (int i = 0; i < (int)valueExprs.size(); i++)
  11862. {
  11863. BfExpression* expr = valueExprs[i];
  11864. if (auto uninitExpr = BfNodeDynCast<BfUninitializedExpression>(expr))
  11865. {
  11866. continue;
  11867. }
  11868. auto innerInitExpr = BfNodeDynCast<BfCollectionInitializerExpression>(expr);
  11869. if (dim < dimensions - 1)
  11870. {
  11871. if (innerInitExpr == NULL)
  11872. {
  11873. if (auto innerTupleExpr = BfNodeDynCast<BfTupleExpression>(expr))
  11874. {
  11875. ProcessArrayInitializer(innerTupleExpr->mOpenParen, innerTupleExpr->mValues, innerTupleExpr->mCommas, innerTupleExpr->mCloseParen, dimensions, dimLengths, dim + 1, hasFailed);
  11876. }
  11877. else if (auto parenExpr = BfNodeDynCast<BfParenthesizedExpression>(expr))
  11878. {
  11879. SizedArray<BfExpression*, 1> values;
  11880. values.Add(parenExpr->mExpression);
  11881. SizedArray<BfTokenNode*, 1> commas;
  11882. ProcessArrayInitializer(parenExpr->mOpenParen, values, commas, parenExpr->mCloseParen, dimensions, dimLengths, dim + 1, hasFailed);
  11883. }
  11884. else
  11885. {
  11886. hasFailed = true;
  11887. mModule->Fail("A nested array initializer is expected", expr);
  11888. continue;
  11889. }
  11890. }
  11891. else
  11892. ProcessArrayInitializer(innerInitExpr->mOpenBrace, innerInitExpr->mValues, innerInitExpr->mCommas, innerInitExpr->mCloseBrace, dimensions, dimLengths, dim + 1, hasFailed);
  11893. }
  11894. else if (innerInitExpr != NULL)
  11895. {
  11896. hasFailed = true;
  11897. mModule->Fail("Unexpected nested initializer", expr);
  11898. ProcessArrayInitializer(innerInitExpr->mOpenBrace, innerInitExpr->mValues, innerInitExpr->mCommas, innerInitExpr->mCloseBrace, dimensions, dimLengths, dim + 1, hasFailed);
  11899. }
  11900. else
  11901. {
  11902. //mModule->Fail("Expected initializer", )
  11903. }
  11904. }
  11905. }
  11906. void BfExprEvaluator::CheckObjectCreateTypeRef(BfType* expectingType, BfAstNode* afterNode)
  11907. {
  11908. auto autoComplete = GetAutoComplete();
  11909. if ((autoComplete != NULL) && (afterNode != NULL) && (autoComplete->mIsAutoComplete) &&
  11910. (afterNode->IsFromParser(mModule->mCompiler->mResolvePassData->mParser)) &&
  11911. (afterNode->GetParser()->mCursorIdx == afterNode->GetSrcEnd() + 1))
  11912. {
  11913. BfType* expectingType = mExpectingType;
  11914. BfTypeInstance* expectingTypeInst = NULL;
  11915. if (mExpectingType != NULL)
  11916. {
  11917. expectingTypeInst = mExpectingType->ToTypeInstance();
  11918. }
  11919. if ((mExpectingType != NULL) && (((expectingTypeInst == NULL) || (!expectingTypeInst->mTypeDef->mIsDelegate))))
  11920. {
  11921. // Why were we doing this? It floods the autocomplete with every possible type
  11922. //autoComplete->AddTopLevelTypes(NULL);
  11923. autoComplete->mInsertStartIdx = afterNode->GetSourceData()->ToParser()->mCursorIdx;
  11924. BF_ASSERT(autoComplete->mInsertStartIdx != -1);
  11925. auto expectingType = mExpectingType;
  11926. while (expectingType->IsArray())
  11927. {
  11928. auto arrayType = (BfArrayType*)expectingType;
  11929. expectingType = arrayType->mGenericTypeInfo->mTypeGenericArguments[0];
  11930. }
  11931. auto expectingTypeInst = expectingType->ToTypeInstance();
  11932. if (expectingTypeInst != NULL)
  11933. {
  11934. autoComplete->AddTypeInstanceEntry(expectingTypeInst);
  11935. }
  11936. else
  11937. autoComplete->mDefaultSelection = mModule->TypeToString(expectingType);
  11938. }
  11939. }
  11940. }
  11941. void BfExprEvaluator::Visit(BfObjectCreateExpression* objCreateExpr)
  11942. {
  11943. CreateObject(objCreateExpr, objCreateExpr->mNewNode, NULL);
  11944. }
  11945. void BfExprEvaluator::CreateObject(BfObjectCreateExpression* objCreateExpr, BfAstNode* allocNode, BfType* wantAllocType)
  11946. {
  11947. auto autoComplete = GetAutoComplete();
  11948. if ((autoComplete != NULL) && (objCreateExpr != NULL) && (objCreateExpr->mTypeRef != NULL))
  11949. {
  11950. autoComplete->CheckTypeRef(objCreateExpr->mTypeRef, false, true);
  11951. }
  11952. if ((autoComplete != NULL) && (objCreateExpr != NULL) && (objCreateExpr->mOpenToken != NULL) && (objCreateExpr->mCloseToken != NULL) &&
  11953. (objCreateExpr->mOpenToken->mToken == BfToken_LBrace) && (autoComplete->CheckFixit(objCreateExpr->mOpenToken)))
  11954. {
  11955. auto refNode = objCreateExpr->mOpenToken;
  11956. BfParserData* parser = refNode->GetSourceData()->ToParserData();
  11957. if (parser != NULL)
  11958. {
  11959. autoComplete->AddEntry(AutoCompleteEntry("fixit", StrFormat("Change initializer braces to parentheses\treformat|%s|%d-1|(\x01|%s|%d-1|)",
  11960. parser->mFileName.c_str(), refNode->mSrcStart,
  11961. parser->mFileName.c_str(), objCreateExpr->mCloseToken->mSrcStart).c_str()));
  11962. }
  11963. }
  11964. CheckObjectCreateTypeRef(mExpectingType, allocNode);
  11965. BfAttributeState attributeState;
  11966. attributeState.mTarget = BfAttributeTargets_Alloc;
  11967. SetAndRestoreValue<BfAttributeState*> prevAttributeState(mModule->mAttributeState, &attributeState);
  11968. BfTokenNode* newToken = NULL;
  11969. BfAllocTarget allocTarget = ResolveAllocTarget(allocNode, newToken, &attributeState.mCustomAttributes);
  11970. bool isScopeAlloc = newToken->GetToken() == BfToken_Scope;
  11971. bool isAppendAlloc = newToken->GetToken() == BfToken_Append;
  11972. bool isStackAlloc = (newToken->GetToken() == BfToken_Stack) || (isScopeAlloc);
  11973. bool isArrayAlloc = false;// (objCreateExpr->mArraySizeSpecifier != NULL);
  11974. bool isRawArrayAlloc = (objCreateExpr != NULL) && (objCreateExpr->mStarToken != NULL);
  11975. if (isScopeAlloc)
  11976. {
  11977. if ((mBfEvalExprFlags & BfEvalExprFlags_FieldInitializer) != 0)
  11978. {
  11979. mModule->Warn(0, "This allocation will only be in scope during the constructor. Consider using a longer-term allocation such as 'new'", allocNode);
  11980. }
  11981. if (allocNode == newToken) // Scope, no target specified
  11982. {
  11983. if (mModule->mParentNodeEntry != NULL)
  11984. {
  11985. if (auto assignExpr = BfNodeDynCastExact<BfAssignmentExpression>(mModule->mParentNodeEntry->mNode))
  11986. {
  11987. if (mModule->mCurMethodState->mCurScope->mCloseNode == NULL)
  11988. {
  11989. // 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
  11990. if ((mBfEvalExprFlags & BfEvalExprFlags_PendingPropSet) == 0)
  11991. mModule->Warn(0, "This allocation will immediately go out of scope. Consider specifying a wider scope target such as 'scope::'", allocNode);
  11992. }
  11993. }
  11994. }
  11995. }
  11996. }
  11997. BfAutoParentNodeEntry autoParentNodeEntry(mModule, objCreateExpr);
  11998. SizedArray<BfAstNode*, 2> dimLengthRefs;
  11999. SizedArray<BfIRValue, 2> dimLengthVals;
  12000. BfArrayType* arrayType = NULL;
  12001. BfType* unresolvedTypeRef = NULL;
  12002. BfType* resolvedTypeRef = NULL;
  12003. if (wantAllocType != NULL)
  12004. {
  12005. unresolvedTypeRef = wantAllocType;
  12006. resolvedTypeRef = wantAllocType;
  12007. }
  12008. else if (objCreateExpr->mTypeRef == NULL)
  12009. {
  12010. if ((!mExpectingType) || (!mExpectingType->IsArray()))
  12011. {
  12012. mModule->Fail("Cannot imply array type. Explicitly state array type or use array in an assignment to an array type.", objCreateExpr);
  12013. resolvedTypeRef = mModule->mContext->mBfObjectType;
  12014. unresolvedTypeRef = resolvedTypeRef;
  12015. }
  12016. else
  12017. {
  12018. auto arrayType = (BfArrayType*)mExpectingType;
  12019. unresolvedTypeRef = arrayType->GetUnderlyingType();
  12020. resolvedTypeRef = unresolvedTypeRef;
  12021. }
  12022. }
  12023. else
  12024. {
  12025. if ((objCreateExpr->mTypeRef->IsExact<BfDotTypeReference>()) && (mExpectingType != NULL))
  12026. {
  12027. //mModule->SetElementType(objCreateExpr->mTypeRef, BfSourceElementType_TypeRef);
  12028. if ((mExpectingType->IsObject()) || (mExpectingType->IsGenericParam()))
  12029. {
  12030. unresolvedTypeRef = mExpectingType;
  12031. if (unresolvedTypeRef->IsArray())
  12032. {
  12033. arrayType = (BfArrayType*)unresolvedTypeRef;
  12034. unresolvedTypeRef = unresolvedTypeRef->GetUnderlyingType();
  12035. isArrayAlloc = true;
  12036. }
  12037. }
  12038. else if (mExpectingType->IsPointer())
  12039. {
  12040. unresolvedTypeRef = mExpectingType->GetUnderlyingType();
  12041. }
  12042. }
  12043. if (unresolvedTypeRef == NULL)
  12044. {
  12045. if (auto arrayTypeRef = BfNodeDynCast<BfArrayTypeRef>(objCreateExpr->mTypeRef))
  12046. {
  12047. isArrayAlloc = true;
  12048. if (auto dotTypeRef = BfNodeDynCast<BfDotTypeReference>(arrayTypeRef->mElementType))
  12049. {
  12050. if ((mExpectingType != NULL) &&
  12051. ((mExpectingType->IsArray()) || (mExpectingType->IsPointer()) || (mExpectingType->IsSizedArray())))
  12052. unresolvedTypeRef = mExpectingType->GetUnderlyingType();
  12053. }
  12054. if (unresolvedTypeRef == NULL)
  12055. unresolvedTypeRef = mModule->ResolveTypeRef(arrayTypeRef->mElementType);
  12056. if (unresolvedTypeRef == NULL)
  12057. unresolvedTypeRef = mModule->mContext->mBfObjectType;
  12058. int dimensions = 1;
  12059. bool commaExpected = false;
  12060. if (arrayTypeRef->mParams.size() != 0)
  12061. {
  12062. auto intType = mModule->ResolveTypeDef(mModule->mSystem->mTypeIntPtr);
  12063. for (auto arg : arrayTypeRef->mParams)
  12064. {
  12065. if (auto tokenNode = BfNodeDynCastExact<BfTokenNode>(arg))
  12066. {
  12067. if (tokenNode->GetToken() == BfToken_Comma)
  12068. {
  12069. if (isRawArrayAlloc)
  12070. {
  12071. mModule->Fail("Sized arrays cannot be multidimensional.", tokenNode);
  12072. continue;
  12073. }
  12074. dimensions++;
  12075. if (dimensions == 5)
  12076. {
  12077. mModule->Fail("Too many array dimensions, consider using a jagged array.", tokenNode);
  12078. }
  12079. commaExpected = false;
  12080. continue;
  12081. }
  12082. }
  12083. auto expr = BfNodeDynCast<BfExpression>(arg);
  12084. if ((isRawArrayAlloc) && (!dimLengthVals.IsEmpty()))
  12085. {
  12086. mModule->CreateValueFromExpression(expr, intType);
  12087. continue;
  12088. }
  12089. dimLengthRefs.Add(expr);
  12090. BfTypedValue dimLength;
  12091. if (expr == NULL)
  12092. {
  12093. // Not specified
  12094. dimLengthVals.push_back(BfIRValue());
  12095. continue;
  12096. }
  12097. if (arg != NULL)
  12098. {
  12099. dimLength = mModule->CreateValueFromExpression(expr, intType, BfEvalExprFlags_NoCast);
  12100. BfCastFlags castFlags = BfCastFlags_None;
  12101. if ((dimLength) && (dimLength.mType->IsInteger()))
  12102. {
  12103. // Allow uint for size - just force to int
  12104. if (!((BfPrimitiveType*)dimLength.mType)->IsSigned())
  12105. castFlags = BfCastFlags_Explicit;
  12106. }
  12107. if (dimLength)
  12108. dimLength = mModule->Cast(expr, dimLength, intType, castFlags);
  12109. }
  12110. if (commaExpected)
  12111. {
  12112. mModule->AssertErrorState();
  12113. continue;
  12114. }
  12115. if (!dimLength)
  12116. {
  12117. dimLength = mModule->GetDefaultTypedValue(intType);
  12118. }
  12119. dimLengthVals.push_back(dimLength.mValue);
  12120. commaExpected = true;
  12121. }
  12122. }
  12123. if ((arrayTypeRef->mParams.size() == 0) && (objCreateExpr->mOpenToken == NULL))
  12124. mModule->Fail("Array size or array initializer expected", arrayTypeRef->mOpenBracket);
  12125. if (dimensions > 4)
  12126. dimensions = 4;
  12127. if (!isRawArrayAlloc)
  12128. arrayType = mModule->CreateArrayType(unresolvedTypeRef, dimensions);
  12129. }
  12130. if (unresolvedTypeRef == NULL)
  12131. {
  12132. unresolvedTypeRef = ResolveTypeRef(objCreateExpr->mTypeRef, BfPopulateType_Declaration, BfResolveTypeRefFlag_NoResolveGenericParam);
  12133. }
  12134. }
  12135. resolvedTypeRef = unresolvedTypeRef;
  12136. if ((resolvedTypeRef != NULL) && (resolvedTypeRef->IsVar()))
  12137. resolvedTypeRef = unresolvedTypeRef;
  12138. }
  12139. if (resolvedTypeRef == NULL)
  12140. {
  12141. unresolvedTypeRef = mModule->GetPrimitiveType(BfTypeCode_Var);
  12142. resolvedTypeRef = unresolvedTypeRef;
  12143. }
  12144. auto resultType = resolvedTypeRef;
  12145. if ((resolvedTypeRef->IsInterface()) && (!isArrayAlloc))
  12146. {
  12147. mModule->Fail("Cannot create an instance of an interface", objCreateExpr->mTypeRef);
  12148. resolvedTypeRef = mModule->mContext->mBfObjectType;
  12149. }
  12150. BfTypeInstance* typeInstance = resolvedTypeRef->ToTypeInstance();
  12151. int elementSize = resolvedTypeRef->mSize;
  12152. int elementAlign = resolvedTypeRef->mAlign;
  12153. BfIRType allocType = mModule->mBfIRBuilder->MapType(resolvedTypeRef);
  12154. if (typeInstance != NULL)
  12155. {
  12156. if (!mModule->mCurTypeInstance->mResolvingVarField)
  12157. mModule->PopulateType(typeInstance);
  12158. if ((typeInstance->mTypeDef->mIsDelegate) && (!isArrayAlloc))
  12159. mModule->Fail("Delegates must be constructed through delegate binding", objCreateExpr->mTypeRef);
  12160. elementSize = BF_MAX(0, typeInstance->mInstSize);
  12161. elementAlign = typeInstance->mInstAlign;
  12162. allocType = mModule->mBfIRBuilder->MapTypeInst(typeInstance);
  12163. }
  12164. if (isAppendAlloc)
  12165. {
  12166. if (!mModule->mCurTypeInstance->IsObject())
  12167. {
  12168. mModule->Fail("Append allocations are only allowed in classes", allocNode);
  12169. isAppendAlloc = false;
  12170. }
  12171. else if ((mBfEvalExprFlags & BfEvalExprFlags_VariableDeclaration) == 0)
  12172. {
  12173. mModule->Fail("Append allocations are only allowed as local variable initializers in constructor body", allocNode);
  12174. isAppendAlloc = false;
  12175. }
  12176. else
  12177. {
  12178. auto methodDef = mModule->mCurMethodInstance->mMethodDef;
  12179. if (methodDef->mMethodType == BfMethodType_CtorCalcAppend)
  12180. {
  12181. mModule->Fail("Append allocations are only allowed as local variable declarations in the main method body", allocNode);
  12182. isAppendAlloc = false;
  12183. }
  12184. else if (!methodDef->mHasAppend)
  12185. {
  12186. mModule->Fail("Append allocations can only be used on constructors with [AllowAppend] specified", allocNode);
  12187. isAppendAlloc = false;
  12188. }
  12189. else if (methodDef->mMethodType != BfMethodType_Ctor)
  12190. {
  12191. mModule->Fail("Append allocations are only allowed in constructors", allocNode);
  12192. isAppendAlloc = false;
  12193. }
  12194. else if (methodDef->mIsStatic)
  12195. {
  12196. mModule->Fail("Append allocations are only allowed in non-static constructors", allocNode);
  12197. isAppendAlloc = false;
  12198. }
  12199. }
  12200. }
  12201. if (isArrayAlloc)
  12202. {
  12203. const int MAX_DIMENSIONS = 2;
  12204. int dimensions = 1;
  12205. if (arrayType != NULL)
  12206. {
  12207. dimensions = arrayType->mDimensions;
  12208. mModule->AddDependency(arrayType, mModule->mCurTypeInstance, BfDependencyMap::DependencyFlag_Calls);
  12209. }
  12210. bool zeroMemory = true;
  12211. if (objCreateExpr->mOpenToken != NULL)
  12212. {
  12213. if ((objCreateExpr->mArguments.size() == 1) &&
  12214. (BfNodeDynCastExact<BfUninitializedExpression>(objCreateExpr->mArguments[0]) != NULL))
  12215. {
  12216. // Special case for a single "{ ? }"
  12217. zeroMemory = false;
  12218. }
  12219. else
  12220. {
  12221. SizedArray<int64, 2> dimLengths;
  12222. if (dimLengthVals.size() != 0)
  12223. {
  12224. for (int dim = 0; dim < dimensions; dim++)
  12225. {
  12226. BfIRValue dimLengthVal;
  12227. if (dim < (int)dimLengthVals.size())
  12228. dimLengthVal = dimLengthVals[dim];
  12229. if (!dimLengthVal)
  12230. {
  12231. dimLengths.push_back(-1);
  12232. continue;
  12233. }
  12234. auto constant = mModule->mBfIRBuilder->GetConstant(dimLengthVal);
  12235. if ((constant != NULL) && (mModule->mBfIRBuilder->IsInt(constant->mTypeCode)))
  12236. {
  12237. int64 dimLength = constant->mInt64;
  12238. if (dimLength < 0)
  12239. {
  12240. mModule->Fail(StrFormat("Invalid array dimension '%lld'", dimLength), dimLengthRefs[dim]);
  12241. dimLength = -1;
  12242. }
  12243. dimLengths.push_back(dimLength);
  12244. }
  12245. else if ((constant != NULL) && (constant->mConstType == BfConstType_Undef))
  12246. {
  12247. dimLengths.push_back(-1);
  12248. }
  12249. else
  12250. {
  12251. mModule->Fail("A constant length is required when using an initializer", dimLengthRefs[dim]);
  12252. dimLengths.push_back(-1);
  12253. }
  12254. }
  12255. }
  12256. // Ending in an ", )" means we need to zero-fill ending
  12257. zeroMemory = objCreateExpr->mCommas.size() >= objCreateExpr->mArguments.size();
  12258. bool hasFailed = false;
  12259. ProcessArrayInitializer(objCreateExpr->mOpenToken, objCreateExpr->mArguments, objCreateExpr->mCommas, objCreateExpr->mCloseToken, dimensions, dimLengths, 0, hasFailed);
  12260. dimLengthVals.resize(dimLengths.size());
  12261. for (int i = 0; i < (int)dimLengthVals.size(); i++)
  12262. {
  12263. if (!dimLengthVals[i])
  12264. {
  12265. auto intType = mModule->GetPrimitiveType(BfTypeCode_IntPtr);
  12266. dimLengthVals[i] = mModule->GetConstValue(dimLengths[i], intType);
  12267. }
  12268. }
  12269. }
  12270. }
  12271. while ((int)dimLengthVals.size() < dimensions)
  12272. dimLengthVals.push_back(mModule->GetConstValue(0));
  12273. BfTypedValue arrayValue;
  12274. BfIRValue arraySize;
  12275. for (BfIRValue dimSize : dimLengthVals)
  12276. {
  12277. if (!arraySize)
  12278. arraySize = dimSize;
  12279. else
  12280. arraySize = mModule->mBfIRBuilder->CreateMul(arraySize, dimSize);
  12281. }
  12282. BfAllocFlags allocFlags = BfAllocFlags_None;
  12283. if (isRawArrayAlloc)
  12284. allocFlags = (BfAllocFlags)(allocFlags | BfAllocFlags_RawArray);
  12285. int writeIdx = 0;
  12286. struct BfInitContext
  12287. {
  12288. public:
  12289. BfModule* mModule;
  12290. BfType* resultType;
  12291. int dimensions;
  12292. SizedArray<BfIRValue, 2>& dimLengthVals;
  12293. BfIRValue arraySize;
  12294. int& writeIdx;
  12295. BfInitContext(BfModule* module, BfType* resultType, int dimensions, SizedArray<BfIRValue, 2>& dimLengthVals, BfIRValue arraySize, int& writeIdx) :
  12296. mModule(module), resultType(resultType), dimensions(dimensions), dimLengthVals(dimLengthVals), arraySize(arraySize), writeIdx(writeIdx)
  12297. {
  12298. }
  12299. void Handle(BfIRValue addr, int curDim, const BfSizedArray<BfExpression*>& valueExprs)
  12300. {
  12301. int exprIdx = 0;
  12302. int dimWriteIdx = 0;
  12303. bool isUninit = false;
  12304. int dimLength = -1;
  12305. if (dimLengthVals[curDim].IsConst())
  12306. {
  12307. auto constant = mModule->mBfIRBuilder->GetConstant(dimLengthVals[curDim]);
  12308. dimLength = constant->mInt32;
  12309. }
  12310. while (exprIdx < (int)valueExprs.size())
  12311. {
  12312. auto initExpr = valueExprs[exprIdx];
  12313. exprIdx++;
  12314. if (!initExpr)
  12315. break;
  12316. if (auto unintExpr = BfNodeDynCastExact<BfUninitializedExpression>(initExpr))
  12317. {
  12318. isUninit = true;
  12319. break;
  12320. }
  12321. if (exprIdx > dimLength)
  12322. break;
  12323. if (curDim < dimensions - 1)
  12324. {
  12325. if (auto innerTupleExpr = BfNodeDynCast<BfTupleExpression>(initExpr))
  12326. {
  12327. Handle(addr, curDim + 1, innerTupleExpr->mValues);
  12328. }
  12329. else if (auto parenExpr = BfNodeDynCast<BfParenthesizedExpression>(initExpr))
  12330. {
  12331. SizedArray<BfExpression*, 1> values;
  12332. values.Add(parenExpr->mExpression);
  12333. Handle(addr, curDim + 1, values);
  12334. }
  12335. else if (auto innerInitExpr = BfNodeDynCast<BfCollectionInitializerExpression>(initExpr))
  12336. {
  12337. Handle(addr, curDim + 1, innerInitExpr->mValues);
  12338. }
  12339. dimWriteIdx++;
  12340. continue;
  12341. }
  12342. BfIRValue elemAddr;
  12343. if (!resultType->IsValuelessType())
  12344. elemAddr = mModule->CreateIndexedValue(resultType, addr, writeIdx);
  12345. else
  12346. elemAddr = mModule->mBfIRBuilder->GetFakeVal();
  12347. writeIdx++;
  12348. dimWriteIdx++;
  12349. BfTypedValue elemPtrTypedVal = BfTypedValue(elemAddr, resultType, BfTypedValueKind_Addr);
  12350. BfExprEvaluator exprEvaluator(mModule);
  12351. exprEvaluator.mExpectingType = resultType;
  12352. exprEvaluator.mReceivingValue = &elemPtrTypedVal;
  12353. exprEvaluator.Evaluate(initExpr);
  12354. exprEvaluator.GetResult();
  12355. if (exprEvaluator.mReceivingValue == NULL)
  12356. {
  12357. // We wrote directly to the array in-place, we're done with this element
  12358. continue;
  12359. }
  12360. auto storeValue = exprEvaluator.mResult;
  12361. if (!storeValue)
  12362. continue;
  12363. storeValue = mModule->Cast(initExpr, storeValue, resultType);
  12364. if (!storeValue)
  12365. continue;
  12366. if (!resultType->IsValuelessType())
  12367. {
  12368. storeValue = mModule->LoadOrAggregateValue(storeValue);
  12369. mModule->mBfIRBuilder->CreateStore(storeValue.mValue, elemAddr);
  12370. }
  12371. }
  12372. int clearFromIdx = writeIdx;
  12373. int sectionElemCount = 1;
  12374. BfIRValue numElemsLeft = arraySize;
  12375. if (dimLength != -1)
  12376. {
  12377. int clearCount = dimLength - dimWriteIdx;
  12378. if (clearCount > 0)
  12379. {
  12380. for (int checkDim = curDim + 1; checkDim < (int)dimLengthVals.size(); checkDim++)
  12381. {
  12382. if (dimLengthVals[checkDim].IsConst())
  12383. {
  12384. auto constant = mModule->mBfIRBuilder->GetConstant(dimLengthVals[checkDim]);
  12385. clearCount *= constant->mInt32;
  12386. sectionElemCount *= constant->mInt32;
  12387. }
  12388. }
  12389. }
  12390. writeIdx += clearCount;
  12391. numElemsLeft = mModule->GetConstValue(clearCount);
  12392. }
  12393. // Actually leave it alone?
  12394. if ((isUninit) &&
  12395. ((mModule->IsOptimized()) || (mModule->mIsComptimeModule) || (mModule->mBfIRBuilder->mIgnoreWrites)))
  12396. return;
  12397. bool doClear = true;
  12398. if (numElemsLeft.IsConst())
  12399. {
  12400. auto constant = mModule->mBfIRBuilder->GetConstant(numElemsLeft);
  12401. doClear = constant->mInt64 > 0;
  12402. }
  12403. if (doClear)
  12404. {
  12405. // We multiply by GetStride. This relies on the fact that we over-allocate on the array allocation -- the last
  12406. // element doesn't need to be padded out to the element alignment, but we do anyway. Otherwise this would be
  12407. // a more complicated computation
  12408. auto clearBytes = mModule->mBfIRBuilder->CreateMul(numElemsLeft, mModule->GetConstValue(resultType->GetStride()));
  12409. if (isUninit)
  12410. {
  12411. // Limit to a reasonable number of bytes to stomp with 0xCC
  12412. int maxStompBytes = BF_MIN(128, resultType->GetStride() * sectionElemCount);
  12413. if (clearBytes.IsConst())
  12414. {
  12415. auto constant = mModule->mBfIRBuilder->GetConstant(clearBytes);
  12416. if (constant->mInt64 > maxStompBytes)
  12417. clearBytes = mModule->GetConstValue(maxStompBytes);
  12418. }
  12419. else
  12420. {
  12421. auto insertBlock = mModule->mBfIRBuilder->GetInsertBlock();
  12422. auto gtBlock = mModule->mBfIRBuilder->CreateBlock("unint.gt");
  12423. auto contBlock = mModule->mBfIRBuilder->CreateBlock("unint.cont");
  12424. auto cmp = mModule->mBfIRBuilder->CreateCmpLTE(clearBytes, mModule->GetConstValue(maxStompBytes), true);
  12425. mModule->mBfIRBuilder->CreateCondBr(cmp, contBlock, gtBlock);
  12426. mModule->mBfIRBuilder->AddBlock(gtBlock);
  12427. mModule->mBfIRBuilder->SetInsertPoint(gtBlock);
  12428. mModule->mBfIRBuilder->CreateBr(contBlock);
  12429. mModule->mBfIRBuilder->AddBlock(contBlock);
  12430. mModule->mBfIRBuilder->SetInsertPoint(contBlock);
  12431. auto phi = mModule->mBfIRBuilder->CreatePhi(mModule->mBfIRBuilder->MapType(mModule->GetPrimitiveType(BfTypeCode_IntPtr)), 2);
  12432. mModule->mBfIRBuilder->AddPhiIncoming(phi, clearBytes, insertBlock);
  12433. mModule->mBfIRBuilder->AddPhiIncoming(phi, mModule->GetConstValue(maxStompBytes), gtBlock);
  12434. clearBytes = phi;
  12435. }
  12436. }
  12437. mModule->mBfIRBuilder->PopulateType(resultType);
  12438. if (!resultType->IsValuelessType())
  12439. {
  12440. mModule->mBfIRBuilder->CreateMemSet(mModule->CreateIndexedValue(resultType, addr, clearFromIdx),
  12441. mModule->mBfIRBuilder->CreateConst(BfTypeCode_Int8, isUninit ? 0xCC : 0), clearBytes, resultType->mAlign);
  12442. }
  12443. }
  12444. }
  12445. };
  12446. BfInitContext initContext(mModule, resultType, dimensions, dimLengthVals, arraySize, writeIdx);
  12447. if (resultType->IsVar())
  12448. {
  12449. SetAndRestoreValue<bool> prevIgnoreWrites(mModule->mBfIRBuilder->mIgnoreWrites, true);
  12450. mResult = BfTypedValue(BfTypedValue(mModule->mBfIRBuilder->GetFakeVal(), mModule->GetPrimitiveType(BfTypeCode_Var)));
  12451. initContext.Handle(mResult.mValue, 0, objCreateExpr->mArguments);
  12452. return;
  12453. }
  12454. if (isRawArrayAlloc)
  12455. {
  12456. // 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
  12457. BfType* ptrType = mModule->CreatePointerType(resultType);
  12458. if (isAppendAlloc)
  12459. arrayValue = BfTypedValue(mModule->AppendAllocFromType(resultType, BfIRValue(), 0, arraySize, (int)dimLengthVals.size(), isRawArrayAlloc, false), ptrType);
  12460. else
  12461. {
  12462. arrayValue = BfTypedValue(mModule->AllocFromType(resultType, allocTarget, BfIRValue(), arraySize, (int)dimLengthVals.size(), allocFlags, allocTarget.mAlignOverride), ptrType);
  12463. }
  12464. initContext.Handle(arrayValue.mValue, 0, objCreateExpr->mArguments);
  12465. mResult = arrayValue;
  12466. return;
  12467. }
  12468. if (dimLengthVals.size() > 4)
  12469. {
  12470. dimLengthVals.RemoveRange(4, dimLengthVals.size() - 4);
  12471. mModule->Fail("Too many array dimensions, consider using a jagged array.", objCreateExpr);
  12472. }
  12473. if (arrayType == NULL)
  12474. return;
  12475. if (isAppendAlloc)
  12476. arrayValue = BfTypedValue(mModule->AppendAllocFromType(resultType, BfIRValue(), 0, arraySize, (int)dimLengthVals.size(), isRawArrayAlloc, zeroMemory), arrayType);
  12477. else
  12478. {
  12479. arrayValue = BfTypedValue(mModule->AllocFromType(resultType, allocTarget, BfIRValue(), arraySize, (int)dimLengthVals.size(), allocFlags, allocTarget.mAlignOverride), arrayType);
  12480. if (isScopeAlloc)
  12481. {
  12482. // See notes below on "general" SkipObjectAccessCheck usage on why we can do this
  12483. mModule->SkipObjectAccessCheck(arrayValue);
  12484. }
  12485. }
  12486. //mModule->InitTypeInst(arrayValue, scopeData);
  12487. BfAstNode* refNode = objCreateExpr->mTypeRef;
  12488. while (true)
  12489. {
  12490. if (auto arrayRef = BfNodeDynCast<BfElementedTypeRef>(refNode))
  12491. {
  12492. refNode = arrayRef->mElementType;
  12493. continue;
  12494. }
  12495. break;
  12496. }
  12497. BfResolvedArgs resolvedArgs;
  12498. auto rawAutoComplete = mModule->mCompiler->GetAutoComplete();
  12499. if (rawAutoComplete != NULL)
  12500. {
  12501. SetAndRestoreValue<bool> prevCapturing(rawAutoComplete->mIsCapturingMethodMatchInfo, false);
  12502. MatchConstructor(refNode, objCreateExpr, arrayValue, arrayType, resolvedArgs, false, false);
  12503. }
  12504. else
  12505. {
  12506. MatchConstructor(refNode, objCreateExpr, arrayValue, arrayType, resolvedArgs, false, false);
  12507. }
  12508. //TODO: Assert 'length' var is at slot 1
  12509. mModule->PopulateType(arrayType->mBaseType, BfPopulateType_DataAndMethods);
  12510. mModule->mBfIRBuilder->PopulateType(arrayType);
  12511. auto arrayBits = mModule->mBfIRBuilder->CreateBitCast(arrayValue.mValue, mModule->mBfIRBuilder->MapTypeInstPtr(arrayType->mBaseType));
  12512. int arrayLengthBitCount = arrayType->GetLengthBitCount();
  12513. if (arrayLengthBitCount == 0)
  12514. {
  12515. mModule->Fail("INTERNAL ERROR: Unable to find array 'length' field", objCreateExpr);
  12516. return;
  12517. }
  12518. mResult = arrayValue;
  12519. auto lengthFieldInstance = mModule->GetFieldByName(arrayType->mBaseType->ToTypeInstance(), "mLength");
  12520. if (lengthFieldInstance == NULL)
  12521. return;
  12522. auto firstElementFieldInstance = mModule->GetFieldByName(arrayType->ToTypeInstance(), "mFirstElement");
  12523. if (firstElementFieldInstance == NULL)
  12524. return;
  12525. auto addr = mModule->mBfIRBuilder->CreateInBoundsGEP(arrayBits, 0, lengthFieldInstance->mDataIdx);
  12526. if (arrayLengthBitCount == 64)
  12527. mModule->mBfIRBuilder->CreateAlignedStore(arraySize, addr, 8);
  12528. else
  12529. {
  12530. auto arraySize32 = mModule->mBfIRBuilder->CreateNumericCast(arraySize, true, BfTypeCode_Int32);
  12531. mModule->mBfIRBuilder->CreateAlignedStore(arraySize32, addr, 4);
  12532. }
  12533. for (int lowerDim = 1; lowerDim < (int)dimLengthVals.size(); lowerDim++)
  12534. {
  12535. auto length1FieldInstance = mModule->GetFieldByName(arrayType->ToTypeInstance(), "mLength1");
  12536. if (length1FieldInstance == NULL)
  12537. return;
  12538. addr = mModule->mBfIRBuilder->CreateInBoundsGEP(arrayValue.mValue, 0, length1FieldInstance->mDataIdx + lowerDim - 1);
  12539. auto lowerDimVal = mModule->mBfIRBuilder->CreateNumericCast(dimLengthVals[lowerDim], true, (arrayLengthBitCount == 64) ? BfTypeCode_Int64 : BfTypeCode_Int32);
  12540. mModule->mBfIRBuilder->CreateStore(lowerDimVal, addr);
  12541. }
  12542. if (resultType->IsValuelessType())
  12543. addr = mModule->mBfIRBuilder->GetFakeVal();
  12544. else
  12545. addr = mModule->mBfIRBuilder->CreateInBoundsGEP(arrayValue.mValue, 0, firstElementFieldInstance->mDataIdx);
  12546. initContext.Handle(addr, 0, objCreateExpr->mArguments);
  12547. return;
  12548. }
  12549. else
  12550. {
  12551. if (resolvedTypeRef->IsVar())
  12552. {
  12553. // Leave as a var
  12554. }
  12555. else if ((!resolvedTypeRef->IsObjectOrInterface()) && (!resolvedTypeRef->IsGenericParam()))
  12556. {
  12557. resultType = mModule->CreatePointerType(resolvedTypeRef);
  12558. }
  12559. }
  12560. if ((isStackAlloc) && (mModule->mCurMethodState == NULL))
  12561. {
  12562. mModule->Fail("Cannot use 'stack' here", allocNode);
  12563. isStackAlloc = false;
  12564. isScopeAlloc = false;
  12565. }
  12566. bool isGenericParam = unresolvedTypeRef->IsGenericParam();
  12567. if (resolvedTypeRef->IsGenericParam())
  12568. {
  12569. BfGenericParamFlags genericParamFlags = BfGenericParamFlag_None;
  12570. BfType* typeConstraint = NULL;
  12571. auto genericParam = mModule->GetMergedGenericParamData((BfGenericParamType*)resolvedTypeRef, genericParamFlags, typeConstraint);
  12572. if (typeConstraint == NULL)
  12573. {
  12574. if ((genericParamFlags & BfGenericParamFlag_Var) != 0)
  12575. {
  12576. // Allow it
  12577. }
  12578. else
  12579. {
  12580. if ((genericParamFlags & BfGenericParamFlag_New) == 0)
  12581. {
  12582. mModule->Fail(StrFormat("Must add 'where %s : new' constraint to generic parameter to instantiate type", genericParam->GetName().c_str()), objCreateExpr->mTypeRef);
  12583. }
  12584. if (objCreateExpr->mArguments.size() != 0)
  12585. {
  12586. mModule->Fail(StrFormat("Only default parameterless constructors can be called on generic argument '%s'", genericParam->GetName().c_str()), objCreateExpr->mTypeRef);
  12587. }
  12588. }
  12589. }
  12590. if (((typeConstraint != NULL) && (typeConstraint->IsValueType())) ||
  12591. ((genericParamFlags & (BfGenericParamFlag_Struct | BfGenericParamFlag_StructPtr)) != 0))
  12592. {
  12593. resultType = mModule->CreatePointerType(resolvedTypeRef);
  12594. }
  12595. else if (((typeConstraint != NULL) && (!typeConstraint->IsValueType())) ||
  12596. ((genericParamFlags & (BfGenericParamFlag_Class)) != 0))
  12597. {
  12598. // Leave as 'T'
  12599. resultType = resolvedTypeRef;
  12600. }
  12601. else
  12602. resultType = mModule->CreateModifiedTypeType(resolvedTypeRef, BfToken_AllocType);
  12603. mResult.mType = resultType;
  12604. if (typeInstance == NULL)
  12605. {
  12606. mResult = mModule->GetDefaultTypedValue(resultType);
  12607. return;
  12608. }
  12609. }
  12610. else if (resolvedTypeRef->IsSizedArray())
  12611. {
  12612. // Handle the case of "int[3]* val = new .(1, 2, 3)"
  12613. if (auto dotTypeRef = BfNodeDynCastExact<BfDotTypeReference>(objCreateExpr->mTypeRef))
  12614. {
  12615. BfIRValue allocValue;
  12616. if (isAppendAlloc)
  12617. allocValue = mModule->AppendAllocFromType(resolvedTypeRef, BfIRValue(), 0, BfIRValue(), 0, false, false);
  12618. else
  12619. allocValue = mModule->AllocFromType(resolvedTypeRef, allocTarget, BfIRValue(), BfIRValue(), 0, BfAllocFlags_None);
  12620. auto result = BfTypedValue(allocValue, resolvedTypeRef, BfTypedValueKind_Addr);
  12621. InitializedSizedArray((BfSizedArrayType*)resolvedTypeRef, objCreateExpr->mOpenToken, objCreateExpr->mArguments, objCreateExpr->mCommas, objCreateExpr->mCloseToken, &result);
  12622. // Turn from an addr of a sized array to pointer of sized array
  12623. mResult = BfTypedValue(mResult.mValue, resultType);
  12624. return;
  12625. }
  12626. }
  12627. SetAndRestoreValue<bool> prevNoBind(mNoBind, mNoBind || isGenericParam);
  12628. if ((typeInstance != NULL) && (typeInstance->mTypeDef->mIsAbstract))
  12629. {
  12630. mModule->Fail("Cannot create an instance of an abstract class", objCreateExpr->mTypeRef);
  12631. return;
  12632. }
  12633. BfFunctionBindResult bindResult;
  12634. bindResult.mSkipThis = true;
  12635. bindResult.mWantsArgs = true;
  12636. SetAndRestoreValue<BfFunctionBindResult*> prevBindResult(mFunctionBindResult, &bindResult);
  12637. BfIRValue appendSizeValue;
  12638. BfTypedValue emtpyThis(mModule->mBfIRBuilder->GetFakeVal(), resolvedTypeRef, resolvedTypeRef->IsStruct());
  12639. BfResolvedArgs argValues;
  12640. if (objCreateExpr != NULL)
  12641. {
  12642. argValues.Init(objCreateExpr->mOpenToken, &objCreateExpr->mArguments, &objCreateExpr->mCommas, objCreateExpr->mCloseToken);
  12643. ResolveArgValues(argValues, BfResolveArgsFlag_DeferParamEval); ////
  12644. }
  12645. if (typeInstance == NULL)
  12646. {
  12647. // No CTOR needed
  12648. if (objCreateExpr->mArguments.size() != 0)
  12649. {
  12650. mModule->Fail(StrFormat("Only default parameterless constructors can be called on primitive type '%s'", mModule->TypeToString(resolvedTypeRef).c_str()), objCreateExpr->mTypeRef);
  12651. }
  12652. }
  12653. else if ((autoComplete != NULL) && (objCreateExpr != NULL) && (objCreateExpr->mOpenToken != NULL))
  12654. {
  12655. auto wasCapturingMethodInfo = autoComplete->mIsCapturingMethodMatchInfo;
  12656. autoComplete->CheckInvocation(objCreateExpr, objCreateExpr->mOpenToken, objCreateExpr->mCloseToken, objCreateExpr->mCommas);
  12657. MatchConstructor(objCreateExpr->mTypeRef, objCreateExpr, emtpyThis, typeInstance, argValues, false, true);
  12658. if ((wasCapturingMethodInfo) && (!autoComplete->mIsCapturingMethodMatchInfo))
  12659. {
  12660. if (autoComplete->mMethodMatchInfo != NULL)
  12661. autoComplete->mIsCapturingMethodMatchInfo = true;
  12662. }
  12663. else
  12664. autoComplete->mIsCapturingMethodMatchInfo = false;
  12665. }
  12666. else if (!resolvedTypeRef->IsFunction())
  12667. {
  12668. auto refNode = allocNode;
  12669. if (objCreateExpr != NULL)
  12670. refNode = objCreateExpr->mTypeRef;
  12671. MatchConstructor(refNode, objCreateExpr, emtpyThis, typeInstance, argValues, false, true);
  12672. }
  12673. if (objCreateExpr != NULL)
  12674. mModule->ValidateAllocation(typeInstance, objCreateExpr->mTypeRef);
  12675. prevBindResult.Restore();
  12676. int allocAlign = resolvedTypeRef->mAlign;
  12677. if (typeInstance != NULL)
  12678. allocAlign = typeInstance->mInstAlign;
  12679. int appendAllocAlign = 0;
  12680. if ((bindResult.mMethodInstance != NULL) && (bindResult.mMethodInstance->mMethodDef->mHasAppend))
  12681. {
  12682. if (!bindResult.mFunc)
  12683. {
  12684. BF_ASSERT((!mModule->HasExecutedOutput()) || (mModule->mBfIRBuilder->mIgnoreWrites));
  12685. appendSizeValue = mModule->GetConstValue(0);
  12686. }
  12687. else
  12688. {
  12689. auto calcAppendMethodModule = mModule->GetMethodInstanceAtIdx(bindResult.mMethodInstance->GetOwner(), bindResult.mMethodInstance->mMethodDef->mIdx + 1, BF_METHODNAME_CALCAPPEND);
  12690. SizedArray<BfIRValue, 2> irArgs;
  12691. if (bindResult.mIRArgs.size() > 1)
  12692. irArgs.Insert(0, &bindResult.mIRArgs[1], bindResult.mIRArgs.size() - 1);
  12693. BfTypedValue appendSizeTypedValue = mModule->TryConstCalcAppend(calcAppendMethodModule.mMethodInstance, irArgs);
  12694. if (!appendSizeTypedValue)
  12695. {
  12696. BF_ASSERT(calcAppendMethodModule.mFunc);
  12697. appendSizeTypedValue = CreateCall(objCreateExpr, calcAppendMethodModule.mMethodInstance, calcAppendMethodModule.mFunc, false, irArgs);
  12698. BF_ASSERT(appendSizeTypedValue.mType == mModule->GetPrimitiveType(BfTypeCode_IntPtr));
  12699. }
  12700. appendSizeValue = appendSizeTypedValue.mValue;
  12701. allocAlign = BF_MAX(allocAlign, calcAppendMethodModule.mMethodInstance->mAppendAllocAlign);
  12702. appendAllocAlign = calcAppendMethodModule.mMethodInstance->mAppendAllocAlign;
  12703. }
  12704. if (appendAllocAlign != 0)
  12705. {
  12706. int endingAlign = typeInstance->GetEndingInstanceAlignment();
  12707. if (endingAlign % appendAllocAlign != 0)
  12708. {
  12709. int extraSize = appendAllocAlign - (endingAlign % appendAllocAlign);
  12710. appendSizeValue = mModule->mBfIRBuilder->CreateAdd(appendSizeValue, mModule->GetConstValue(extraSize));
  12711. }
  12712. }
  12713. }
  12714. // WTF? I'm not even sure this is correct - add more tests
  12715. appendAllocAlign = BF_MAX(appendAllocAlign, allocAlign);
  12716. BfIRValue allocValue;
  12717. if (resolvedTypeRef->IsVar())
  12718. {
  12719. mResult = mModule->GetDefaultTypedValue(resultType);
  12720. return;
  12721. }
  12722. else
  12723. {
  12724. if (isAppendAlloc)
  12725. {
  12726. allocValue = mModule->AppendAllocFromType(resolvedTypeRef, appendSizeValue, appendAllocAlign);
  12727. }
  12728. else
  12729. {
  12730. allocValue = mModule->AllocFromType(resolvedTypeRef, allocTarget, appendSizeValue, BfIRValue(), 0, BfAllocFlags_None, allocAlign);
  12731. }
  12732. if (((mBfEvalExprFlags & BfEvalExprFlags_Comptime) != 0) && (mModule->mCompiler->mCEMachine != NULL))
  12733. {
  12734. mModule->mCompiler->mCEMachine->SetAppendAllocInfo(mModule, allocValue, appendSizeValue);
  12735. }
  12736. mResult = BfTypedValue(allocValue, resultType);
  12737. }
  12738. if (isScopeAlloc)
  12739. {
  12740. // This allows readonly (ie: 'let') local usage to not require an access check. No matter what scope the alloc is tied to, the
  12741. // lifetime of the local variable will be no longer than that of the allocated value
  12742. mModule->SkipObjectAccessCheck(mResult);
  12743. }
  12744. /*if (typeInstance != NULL)
  12745. {
  12746. mModule->InitTypeInst(mResult, scopeData, true);
  12747. }
  12748. if (isStackAlloc)
  12749. {
  12750. mModule->AddStackAlloc(mResult, objCreateExpr, scopeData);
  12751. }*/
  12752. if (mResult)
  12753. {
  12754. if (bindResult.mMethodInstance == NULL)
  12755. {
  12756. // Why did we have this? It was already zeroed right?
  12757. // Zero
  12758. //mModule->mBfIRBuilder->CreateMemSet(mResult.mValue, mModule->GetConstValue8(0), mModule->GetConstValue(resolvedTypeRef->mSize), resolvedTypeRef->mAlign);
  12759. }
  12760. else if (bindResult.mFunc)
  12761. {
  12762. if (typeInstance->IsObject())
  12763. {
  12764. bool hasRealtimeLeakCheck = (mModule->mCompiler->mOptions.mEnableRealtimeLeakCheck) && (!IsComptime());
  12765. bool wantsCtorClear = true;
  12766. if (hasRealtimeLeakCheck)
  12767. {
  12768. // Dbg_ObjectAlloc clears internally so we don't need to call CtorClear for those
  12769. if ((!isStackAlloc) && (!isAppendAlloc) && (!allocTarget.mCustomAllocator) && (allocTarget.mScopedInvocationTarget == NULL))
  12770. wantsCtorClear = false;
  12771. }
  12772. if (wantsCtorClear)
  12773. {
  12774. auto ctorClear = mModule->GetMethodByName(typeInstance, "__BfCtorClear");
  12775. if (!ctorClear)
  12776. {
  12777. mModule->AssertErrorState();
  12778. }
  12779. else if ((mBfEvalExprFlags & BfEvalExprFlags_Comptime) == 0)
  12780. {
  12781. SizedArray<BfIRValue, 1> irArgs;
  12782. irArgs.push_back(mResult.mValue);
  12783. CreateCall(objCreateExpr, ctorClear.mMethodInstance, ctorClear.mFunc, false, irArgs);
  12784. }
  12785. }
  12786. if ((!mModule->mIsComptimeModule) && (isStackAlloc) && (hasRealtimeLeakCheck))
  12787. {
  12788. BfMethodInstance* markMethod = mModule->GetRawMethodByName(mModule->mContext->mBfObjectType, "GCMarkMembers");
  12789. BF_ASSERT(markMethod != NULL);
  12790. if (markMethod != NULL)
  12791. {
  12792. auto& vtableEntry = typeInstance->mVirtualMethodTable[markMethod->mVirtualTableIdx];
  12793. if (vtableEntry.mImplementingMethod.mTypeInstance != mModule->mContext->mBfObjectType)
  12794. {
  12795. auto impMethodInstance = (BfMethodInstance*)vtableEntry.mImplementingMethod;
  12796. bool needsCall = false;
  12797. if (impMethodInstance != NULL)
  12798. {
  12799. needsCall = impMethodInstance->mMethodDef->mBody != NULL;
  12800. }
  12801. else
  12802. {
  12803. needsCall = true;
  12804. BF_ASSERT(vtableEntry.mImplementingMethod.mKind == BfMethodRefKind_AmbiguousRef);
  12805. }
  12806. if (needsCall)
  12807. {
  12808. SizedArray<BfIRValue, 1> irArgs;
  12809. irArgs.push_back(mModule->mBfIRBuilder->CreateBitCast(mResult.mValue, mModule->mBfIRBuilder->MapType(mModule->mContext->mBfObjectType)));
  12810. auto gcType = mModule->ResolveTypeDef(mModule->mCompiler->mGCTypeDef);
  12811. BF_ASSERT(gcType != NULL);
  12812. if (gcType != NULL)
  12813. {
  12814. auto addStackObjMethod = mModule->GetMethodByName(gcType->ToTypeInstance(), "AddStackMarkableObject", 1);
  12815. BF_ASSERT(addStackObjMethod);
  12816. if (addStackObjMethod)
  12817. {
  12818. mModule->mBfIRBuilder->CreateCall(addStackObjMethod.mFunc, irArgs);
  12819. }
  12820. auto removeStackObjMethod = mModule->GetMethodByName(gcType->ToTypeInstance(), "RemoveStackMarkableObject", 1);
  12821. BF_ASSERT(removeStackObjMethod);
  12822. if (removeStackObjMethod)
  12823. {
  12824. mModule->AddDeferredCall(removeStackObjMethod, irArgs, allocTarget.mScopeData, allocNode);
  12825. }
  12826. }
  12827. }
  12828. }
  12829. }
  12830. }
  12831. }
  12832. if ((bindResult.mMethodInstance->mMethodDef->mHasAppend) && (mResult.mType->IsObject()))
  12833. {
  12834. BF_ASSERT(bindResult.mIRArgs[0].IsFake());
  12835. auto typeInst = mResult.mType->ToTypeInstance();
  12836. auto intPtrType = mModule->GetPrimitiveType(BfTypeCode_IntPtr);
  12837. auto thisVal = mResult;
  12838. BfIRValue intPtrVal = mModule->CreateAlloca(intPtrType);
  12839. auto intPtrThisVal = mModule->mBfIRBuilder->CreatePtrToInt(thisVal.mValue, (intPtrType->mSize == 4) ? BfTypeCode_Int32 : BfTypeCode_Int64);
  12840. auto curValPtr = mModule->mBfIRBuilder->CreateAdd(intPtrThisVal, mModule->GetConstValue(typeInst->mInstSize, intPtrType));
  12841. mModule->mBfIRBuilder->CreateStore(curValPtr, intPtrVal);
  12842. bindResult.mIRArgs[0] = intPtrVal;
  12843. }
  12844. if (!typeInstance->IsValuelessType())
  12845. bindResult.mIRArgs.Insert(0, mResult.mValue);
  12846. auto result = CreateCall(objCreateExpr, bindResult.mMethodInstance, bindResult.mFunc, false, bindResult.mIRArgs);
  12847. if ((result) && (!result.mType->IsVoid()))
  12848. mResult = result;
  12849. }
  12850. }
  12851. if (((mBfEvalExprFlags & BfEvalExprFlags_Comptime) != 0) && (mModule->mCompiler->mCEMachine != NULL))
  12852. {
  12853. mModule->mCompiler->mCEMachine->ClearAppendAllocInfo();
  12854. }
  12855. }
  12856. void BfExprEvaluator::Visit(BfBoxExpression* boxExpr)
  12857. {
  12858. /*if ((boxExpr->mAllocNode == NULL) || (boxExpr->mExpression == NULL))
  12859. {
  12860. mModule->AssertErrorState();
  12861. return;
  12862. }*/
  12863. BfTokenNode* newToken = NULL;
  12864. BfAllocTarget allocTarget = ResolveAllocTarget(boxExpr->mAllocNode, newToken);
  12865. if ((boxExpr->mAllocNode != NULL) && (boxExpr->mAllocNode->mToken == BfToken_Scope))
  12866. {
  12867. if ((mBfEvalExprFlags & BfEvalExprFlags_FieldInitializer) != 0)
  12868. {
  12869. mModule->Warn(0, "This allocation will only be in scope during the constructor. Consider using a longer-term allocation such as 'new'", boxExpr->mAllocNode);
  12870. }
  12871. }
  12872. if (boxExpr->mExpression == NULL)
  12873. {
  12874. mModule->AssertErrorState();
  12875. return;
  12876. }
  12877. auto exprValue = mModule->CreateValueFromExpression(boxExpr->mExpression);
  12878. if (exprValue)
  12879. {
  12880. bool doFail = false;
  12881. bool doWarn = false;
  12882. if (exprValue.mType->IsGenericParam())
  12883. {
  12884. BF_ASSERT(mModule->mCurMethodInstance->mIsUnspecialized);
  12885. auto genericParamTarget = (BfGenericParamType*)exprValue.mType;
  12886. auto genericParamInstance = mModule->GetGenericParamInstance(genericParamTarget);
  12887. if ((genericParamInstance->mGenericParamFlags & (BfGenericParamFlag_Struct | BfGenericParamFlag_StructPtr | BfGenericParamFlag_Class)) == BfGenericParamFlag_Class)
  12888. doWarn = true;
  12889. if ((genericParamInstance->mTypeConstraint != NULL) && (genericParamInstance->mTypeConstraint->IsObjectOrInterface()))
  12890. doWarn = true;
  12891. }
  12892. else
  12893. {
  12894. doFail = !exprValue.mType->IsValueTypeOrValueTypePtr();
  12895. doWarn = exprValue.mType->IsObjectOrInterface();
  12896. }
  12897. if (doWarn)
  12898. {
  12899. mModule->Warn(0, StrFormat("Boxing is unnecessary since type '%s' is already a reference type.", mModule->TypeToString(exprValue.mType).c_str()), boxExpr->mExpression);
  12900. mResult = exprValue;
  12901. return;
  12902. }
  12903. if (doFail)
  12904. {
  12905. 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);
  12906. return;
  12907. }
  12908. BfType* boxedType = mModule->CreateBoxedType(exprValue.mType);
  12909. if (boxedType == NULL)
  12910. boxedType = mModule->mContext->mBfObjectType;
  12911. mResult = mModule->BoxValue(boxExpr->mExpression, exprValue, boxedType, allocTarget);
  12912. if (!mResult)
  12913. {
  12914. mModule->Fail(StrFormat("Type '%s' is not boxable", mModule->TypeToString(exprValue.mType).c_str()), boxExpr->mExpression);
  12915. return;
  12916. }
  12917. }
  12918. }
  12919. BfAllocTarget BfExprEvaluator::ResolveAllocTarget(BfAstNode* allocNode, BfTokenNode*& newToken, BfCustomAttributes** outCustomAttributes)
  12920. {
  12921. auto autoComplete = GetAutoComplete();
  12922. BfAttributeDirective* attributeDirective = NULL;
  12923. BfAllocTarget allocTarget;
  12924. allocTarget.mRefNode = allocNode;
  12925. newToken = BfNodeDynCast<BfTokenNode>(allocNode);
  12926. if (newToken == NULL)
  12927. {
  12928. if (auto scopeNode = BfNodeDynCast<BfScopeNode>(allocNode))
  12929. {
  12930. newToken = scopeNode->mScopeToken;
  12931. allocTarget.mScopeData = mModule->FindScope(scopeNode->mTargetNode, true);
  12932. if (autoComplete != NULL)
  12933. {
  12934. auto targetIdentifier = BfNodeDynCast<BfIdentifierNode>(scopeNode->mTargetNode);
  12935. if ((scopeNode->mTargetNode == NULL) || (targetIdentifier != NULL))
  12936. autoComplete->CheckLabel(targetIdentifier, scopeNode->mColonToken, allocTarget.mScopeData);
  12937. }
  12938. attributeDirective = scopeNode->mAttributes;
  12939. }
  12940. if (auto newNode = BfNodeDynCast<BfNewNode>(allocNode))
  12941. {
  12942. newToken = newNode->mNewToken;
  12943. if (auto allocExpr = BfNodeDynCast<BfExpression>(newNode->mAllocNode))
  12944. {
  12945. allocTarget.mCustomAllocator = mModule->CreateValueFromExpression(allocExpr);
  12946. allocTarget.mRefNode = allocExpr;
  12947. }
  12948. else if (auto scopedInvocationTarget = BfNodeDynCast<BfScopedInvocationTarget>(newNode->mAllocNode))
  12949. {
  12950. allocTarget.mScopedInvocationTarget = scopedInvocationTarget;
  12951. }
  12952. attributeDirective = newNode->mAttributes;
  12953. }
  12954. }
  12955. else if (newToken->GetToken() == BfToken_Scope)
  12956. {
  12957. if (mModule->mCurMethodState != NULL)
  12958. allocTarget.mScopeData = mModule->mCurMethodState->mCurScope->GetTargetable();
  12959. }
  12960. else if (newToken->GetToken() == BfToken_Stack)
  12961. {
  12962. if (mModule->mCurMethodState != NULL)
  12963. allocTarget.mScopeData = &mModule->mCurMethodState->mHeadScope;
  12964. }
  12965. if (attributeDirective != NULL)
  12966. {
  12967. auto customAttrs = mModule->GetCustomAttributes(attributeDirective, BfAttributeTargets_Alloc, BfGetCustomAttributesFlags_AllowNonConstArgs, &allocTarget.mCaptureInfo);
  12968. if (customAttrs != NULL)
  12969. {
  12970. for (auto& attrib : customAttrs->mAttributes)
  12971. {
  12972. if (attrib.mType->IsInstanceOf(mModule->mCompiler->mAlignAttributeTypeDef))
  12973. {
  12974. allocTarget.mAlignOverride = 16; // System conservative default
  12975. if (!attrib.mCtorArgs.IsEmpty())
  12976. {
  12977. BfIRConstHolder* constHolder = mModule->mCurTypeInstance->mConstHolder;
  12978. auto constant = constHolder->GetConstant(attrib.mCtorArgs[0]);
  12979. if (constant != NULL)
  12980. {
  12981. int alignOverride = (int)BF_MAX(1, constant->mInt64);
  12982. if ((alignOverride & (alignOverride - 1)) == 0)
  12983. allocTarget.mAlignOverride = alignOverride;
  12984. else
  12985. mModule->Fail("Alignment must be a power of 2", attrib.GetRefNode());
  12986. }
  12987. }
  12988. }
  12989. else if (attrib.mType->IsInstanceOf(mModule->mCompiler->mFriendAttributeTypeDef))
  12990. allocTarget.mIsFriend = true;
  12991. }
  12992. if (outCustomAttributes != NULL)
  12993. *outCustomAttributes = customAttrs;
  12994. else
  12995. delete customAttrs;
  12996. }
  12997. }
  12998. return allocTarget;
  12999. }
  13000. BfTypedValue BfExprEvaluator::MakeCallableTarget(BfAstNode* targetSrc, BfTypedValue target)
  13001. {
  13002. if ((target.mType->IsRef()) || (target.mType->IsPointer()))
  13003. {
  13004. auto underlying = target.mType->GetUnderlyingType();
  13005. bool underlyingIsStruct = underlying->IsStruct();
  13006. // if (underlying->IsGenericParam())
  13007. // {
  13008. // auto genericParam = mModule->GetGenericParamInstance((BfGenericParamType*)underlying);
  13009. // if (((genericParam->mTypeConstraint != NULL) && (genericParam->mTypeConstraint->IsValueType())) ||
  13010. // ((genericParam->mGenericParamFlags & (BfGenericParamFlag_Struct)) != 0))
  13011. // underlyingIsStruct = true;
  13012. // }
  13013. if (underlyingIsStruct)
  13014. {
  13015. auto pointerType = (BfPointerType*)target.mType;
  13016. target = mModule->LoadValue(target);
  13017. target.mType = pointerType->mElementType;
  13018. target.mKind = BfTypedValueKind_Addr;
  13019. }
  13020. }
  13021. if ((target.mType->IsStruct()) && (!target.IsAddr()))
  13022. {
  13023. if (IsComptimeEntry())
  13024. return target;
  13025. target = mModule->MakeAddressable(target);
  13026. }
  13027. if (target.mType->IsVar())
  13028. {
  13029. target.mType = mModule->mContext->mBfObjectType;
  13030. return target;
  13031. }
  13032. if (target.mType->IsWrappableType())
  13033. {
  13034. auto primStructType = mModule->GetWrappedStructType(target.mType);
  13035. if (primStructType != NULL)
  13036. {
  13037. mModule->PopulateType(primStructType);
  13038. if (primStructType->IsTypedPrimitive())
  13039. {
  13040. // Type is already the same
  13041. target.mType = primStructType;
  13042. }
  13043. else if (target.IsAddr())
  13044. {
  13045. auto ptrType = mModule->CreatePointerType(primStructType);
  13046. target = BfTypedValue(mModule->mBfIRBuilder->CreateBitCast(target.mValue, mModule->mBfIRBuilder->MapType(ptrType)), primStructType, true);
  13047. }
  13048. else if ((primStructType->IsSplattable()) && (target.IsSplat()) && (!IsComptime()))
  13049. {
  13050. target.mType = primStructType;
  13051. target.mKind = BfTypedValueKind_SplatHead;
  13052. }
  13053. else
  13054. {
  13055. auto allocPtr = mModule->CreateAlloca(primStructType);
  13056. auto srcPtrType = mModule->mBfIRBuilder->CreateBitCast(allocPtr, mModule->mBfIRBuilder->GetPointerTo(mModule->mBfIRBuilder->MapType(target.mType)));
  13057. mModule->mBfIRBuilder->CreateStore(target.mValue, srcPtrType);
  13058. target = BfTypedValue(allocPtr, primStructType, true);
  13059. }
  13060. }
  13061. return target;
  13062. }
  13063. if (target.mType->IsGenericParam())
  13064. {
  13065. target.mType = mModule->mContext->mBfObjectType;
  13066. return target;
  13067. }
  13068. if ((!target.mType->IsTypeInstance()) && (!target.mType->IsConcreteInterfaceType()))
  13069. {
  13070. mModule->Fail(StrFormat("Methods cannot be called on type '%s'", mModule->TypeToString(target.mType).c_str()), targetSrc);
  13071. return BfTypedValue();
  13072. }
  13073. return target;
  13074. }
  13075. int BfExprEvaluator::GetMixinVariable()
  13076. {
  13077. auto curMethodState = mModule->mCurMethodState;
  13078. for (int localIdx = (int)curMethodState->mLocals.size() - 1; localIdx >= 0; localIdx--)
  13079. {
  13080. auto varDecl = curMethodState->mLocals[localIdx];
  13081. if (varDecl->mName == "mixin")
  13082. return localIdx;
  13083. }
  13084. return -1;
  13085. }
  13086. BfModuleMethodInstance BfExprEvaluator::GetSelectedMethod(BfAstNode* targetSrc, BfTypeInstance* curTypeInst, BfMethodDef* methodDef, BfMethodMatcher& methodMatcher, BfType** overrideReturnType)
  13087. {
  13088. bool failed = false;
  13089. BfTypeVector resolvedGenericArguments;
  13090. BfMethodState* rootMethodState = NULL;
  13091. if (mModule->mCurMethodState != NULL)
  13092. rootMethodState = mModule->mCurMethodState->GetRootMethodState();
  13093. int localInferrableGenericArgCount = -1;
  13094. if ((methodMatcher.mBestMethodGenericArguments.size() == 0) && (!methodMatcher.mExplicitMethodGenericArguments.IsEmpty()))
  13095. {
  13096. int uniqueGenericStartIdx = mModule->GetLocalInferrableGenericArgCount(methodDef);
  13097. int64 genericArgCountDiff = (int)methodMatcher.mExplicitMethodGenericArguments.size() + uniqueGenericStartIdx - (int)methodDef->mGenericParams.size();
  13098. BfInvocationExpression* invocationExpr = NULL;
  13099. if (mModule->mParentNodeEntry != NULL)
  13100. {
  13101. invocationExpr = BfNodeDynCast<BfInvocationExpression>(mModule->mParentNodeEntry->mNode);
  13102. }
  13103. if (genericArgCountDiff > 0)
  13104. {
  13105. BfAstNode* errorNode = targetSrc;
  13106. if ((invocationExpr != NULL) && (invocationExpr->mGenericArgs != NULL))
  13107. {
  13108. errorNode = invocationExpr->mGenericArgs->mGenericArgs[(int)methodDef->mGenericParams.size()];
  13109. if (errorNode == NULL)
  13110. invocationExpr->mGenericArgs->mCommas.GetSafe((int)methodDef->mGenericParams.size() - 1, errorNode);
  13111. if (errorNode == NULL)
  13112. errorNode = targetSrc;
  13113. }
  13114. mModule->Fail(StrFormat("Too many generic arguments, expected %d fewer", genericArgCountDiff), errorNode);
  13115. }
  13116. else if (genericArgCountDiff < 0)
  13117. {
  13118. BfAstNode* errorNode = targetSrc;
  13119. if ((invocationExpr != NULL) && (invocationExpr->mGenericArgs != NULL) && (invocationExpr->mGenericArgs->mCloseChevron != NULL))
  13120. errorNode = invocationExpr->mGenericArgs->mCloseChevron;
  13121. mModule->Fail(StrFormat("Too few generic arguments, expected %d more", -genericArgCountDiff), errorNode);
  13122. }
  13123. methodMatcher.mBestMethodGenericArguments.resize(methodDef->mGenericParams.size());
  13124. for (int i = 0; i < std::min(methodDef->mGenericParams.size() - uniqueGenericStartIdx, methodMatcher.mExplicitMethodGenericArguments.size()); i++)
  13125. {
  13126. methodMatcher.mBestMethodGenericArguments[i + uniqueGenericStartIdx] = methodMatcher.mExplicitMethodGenericArguments[i];
  13127. }
  13128. }
  13129. BfMethodInstance* unspecializedMethod = NULL;
  13130. bool hasVarGenerics = false;
  13131. for (int checkGenericIdx = 0; checkGenericIdx < (int)methodMatcher.mBestMethodGenericArguments.size(); checkGenericIdx++)
  13132. {
  13133. BfMethodInstance* outerMethodInstance = NULL;
  13134. auto& genericArg = methodMatcher.mBestMethodGenericArguments[checkGenericIdx];
  13135. if (genericArg == NULL)
  13136. {
  13137. if ((methodDef->mIsLocalMethod) && (checkGenericIdx < mModule->mCurMethodInstance->GetNumGenericArguments()))
  13138. {
  13139. // If the root method is generic and we need that param then use that...
  13140. auto rootMethodInstance = rootMethodState->mMethodInstance;
  13141. if ((rootMethodInstance->mMethodInfoEx != NULL) && (checkGenericIdx < rootMethodInstance->mMethodInfoEx->mMethodGenericArguments.size()))
  13142. {
  13143. genericArg = rootMethodInstance->mMethodInfoEx->mMethodGenericArguments[checkGenericIdx];
  13144. }
  13145. else
  13146. {
  13147. if (localInferrableGenericArgCount == -1)
  13148. localInferrableGenericArgCount = mModule->GetLocalInferrableGenericArgCount(methodDef);
  13149. // Otherwise we can only infer generics at the level that the called method was contained
  13150. if (checkGenericIdx < localInferrableGenericArgCount)
  13151. genericArg = mModule->mCurMethodInstance->mMethodInfoEx->mMethodGenericArguments[checkGenericIdx];
  13152. }
  13153. }
  13154. }
  13155. if (genericArg == NULL)
  13156. {
  13157. if (unspecializedMethod == NULL)
  13158. unspecializedMethod = mModule->GetRawMethodInstance(curTypeInst, methodDef);
  13159. auto genericParam = unspecializedMethod->mMethodInfoEx->mGenericParams[checkGenericIdx];
  13160. if ((genericParam->mTypeConstraint != NULL) && (genericParam->mTypeConstraint->IsDelegate()))
  13161. {
  13162. // The only other option was to bind to a MethodRef
  13163. genericArg = mModule->ResolveGenericType(genericParam->mTypeConstraint, NULL, &methodMatcher.mBestMethodGenericArguments);
  13164. }
  13165. else
  13166. {
  13167. if (((genericParam->mGenericParamFlags & BfGenericParamFlag_Const) != 0) && (genericParam->mTypeConstraint != NULL))
  13168. {
  13169. for (int paramIdx = 0; paramIdx < (int)unspecializedMethod->mDefaultValues.size(); paramIdx++)
  13170. {
  13171. auto defaultVal = unspecializedMethod->mDefaultValues[paramIdx];
  13172. if (!defaultVal)
  13173. continue;
  13174. auto& param = unspecializedMethod->mParams[paramIdx];
  13175. if (param.mResolvedType->IsGenericParam())
  13176. {
  13177. auto genericParamType = (BfGenericParamType*)param.mResolvedType;
  13178. if ((genericParamType->mGenericParamKind == BfGenericParamKind_Method) && (genericParamType->mGenericParamIdx == checkGenericIdx))
  13179. {
  13180. BfTypedValue constExprVal;
  13181. constExprVal.mType = genericParam->mTypeConstraint;
  13182. auto constant = curTypeInst->mConstHolder->GetConstant(defaultVal.mValue);
  13183. constExprVal.mValue = mModule->ConstantToCurrent(constant, curTypeInst->mConstHolder, genericParam->mTypeConstraint);
  13184. genericArg = mModule->CreateConstExprValueType(constExprVal);
  13185. }
  13186. }
  13187. }
  13188. }
  13189. }
  13190. if (genericArg == NULL)
  13191. {
  13192. BfGenericInferContext genericInferContext;
  13193. genericInferContext.mModule = mModule;
  13194. genericInferContext.mCheckMethodGenericArguments = &methodMatcher.mBestMethodGenericArguments;
  13195. genericInferContext.InferGenericArguments(unspecializedMethod);
  13196. }
  13197. if (genericArg == NULL)
  13198. {
  13199. failed = true;
  13200. BfError* error = mModule->Fail(StrFormat("Unable to determine generic argument '%s'", methodDef->mGenericParams[checkGenericIdx]->mName.c_str()).c_str(), targetSrc);
  13201. if ((genericParam->mTypeConstraint != NULL) && (!genericParam->mTypeConstraint->IsUnspecializedType()))
  13202. genericArg = genericParam->mTypeConstraint;
  13203. else
  13204. genericArg = mModule->mContext->mBfObjectType;
  13205. if (error != NULL)
  13206. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("See method declaration"), unspecializedMethod->mMethodDef->GetRefNode());
  13207. }
  13208. }
  13209. if (genericArg->IsVar())
  13210. {
  13211. BF_ASSERT(methodMatcher.mHasVarArguments);
  13212. hasVarGenerics = true;
  13213. }
  13214. if (genericArg->IsIntUnknown())
  13215. genericArg = mModule->FixIntUnknown(genericArg);
  13216. auto resolvedGenericArg = genericArg;
  13217. resolvedGenericArguments.push_back(genericArg);
  13218. }
  13219. BfTypeInstance* foreignType = NULL;
  13220. BfGetMethodInstanceFlags flags = BfGetMethodInstanceFlag_None;
  13221. if ((mModule->mAttributeState != NULL) && (mModule->mAttributeState->mCustomAttributes != NULL) && (mModule->mAttributeState->mCustomAttributes->Contains(mModule->mCompiler->mInlineAttributeTypeDef)))
  13222. {
  13223. flags = (BfGetMethodInstanceFlags)(flags | BfGetMethodInstanceFlag_ForceInline);
  13224. mModule->mAttributeState->mUsed = true;
  13225. }
  13226. if ((!mModule->mCurTypeInstance->IsInterface()) && (methodDef->mBody != NULL))
  13227. {
  13228. if ((methodMatcher.mBypassVirtual) && (methodMatcher.mBestMethodTypeInstance->IsInterface()))
  13229. {
  13230. // This is an explicit 'base' call to a default interface method. We pull the methodDef into our own concrete type.
  13231. foreignType = curTypeInst;
  13232. curTypeInst = mModule->mCurTypeInstance;
  13233. flags = (BfGetMethodInstanceFlags)(flags | BfGetMethodInstanceFlag_ForeignMethodDef);
  13234. }
  13235. else if ((methodDef->mIsStatic) && (curTypeInst->IsInterface()))
  13236. {
  13237. if (mModule->TypeIsSubTypeOf(mModule->mCurTypeInstance, curTypeInst))
  13238. {
  13239. // This is an explicit call to a default static interface method. We pull the methodDef into our own concrete type.
  13240. foreignType = curTypeInst;
  13241. curTypeInst = mModule->mCurTypeInstance;
  13242. flags = (BfGetMethodInstanceFlags)(flags | BfGetMethodInstanceFlag_ForeignMethodDef);
  13243. }
  13244. }
  13245. }
  13246. if (hasVarGenerics)
  13247. return BfModuleMethodInstance();
  13248. BfModuleMethodInstance moduleMethodInstance;
  13249. if (methodMatcher.mBestMethodInstance)
  13250. {
  13251. moduleMethodInstance = methodMatcher.mBestMethodInstance;
  13252. }
  13253. else
  13254. {
  13255. moduleMethodInstance = mModule->GetMethodInstance(curTypeInst, methodDef, resolvedGenericArguments, flags, foreignType);
  13256. }
  13257. if (mModule->IsSkippingExtraResolveChecks())
  13258. {
  13259. //BF_ASSERT(methodInstance.mFunc == NULL);
  13260. }
  13261. if (moduleMethodInstance.mMethodInstance == NULL)
  13262. return NULL;
  13263. if (methodDef->IsEmptyPartial())
  13264. return moduleMethodInstance;
  13265. if (moduleMethodInstance.mMethodInstance->mMethodInfoEx != NULL)
  13266. {
  13267. for (int checkGenericIdx = 0; checkGenericIdx < (int)moduleMethodInstance.mMethodInstance->mMethodInfoEx->mGenericParams.size(); checkGenericIdx++)
  13268. {
  13269. auto genericParams = moduleMethodInstance.mMethodInstance->mMethodInfoEx->mGenericParams[checkGenericIdx];
  13270. BfTypeVector* checkMethodGenericArgs = NULL;
  13271. BfType* genericArg = NULL;
  13272. if (checkGenericIdx < (int)methodMatcher.mBestMethodGenericArguments.size())
  13273. {
  13274. genericArg = methodMatcher.mBestMethodGenericArguments[checkGenericIdx];
  13275. }
  13276. else
  13277. {
  13278. checkMethodGenericArgs = &methodMatcher.mBestMethodGenericArguments;
  13279. genericArg = genericParams->mExternType;
  13280. auto owner = moduleMethodInstance.mMethodInstance->GetOwner();
  13281. BfTypeVector* typeGenericArguments = NULL;
  13282. if (owner->mGenericTypeInfo != NULL)
  13283. typeGenericArguments = &owner->mGenericTypeInfo->mTypeGenericArguments;
  13284. //genericArg = mModule->ResolveGenericType(genericArg, typeGenericArguments, checkMethodGenericArgs);
  13285. }
  13286. if (genericArg->IsVar())
  13287. continue;
  13288. BfAstNode* paramSrc;
  13289. if (checkGenericIdx >= methodMatcher.mBestMethodGenericArgumentSrcs.size())
  13290. {
  13291. paramSrc = targetSrc;
  13292. }
  13293. else
  13294. paramSrc = methodMatcher.mArguments[methodMatcher.mBestMethodGenericArgumentSrcs[checkGenericIdx]].mExpression;
  13295. // Note: don't pass methodMatcher.mBestMethodGenericArguments into here, this method is already specialized
  13296. BfError* error = NULL;
  13297. if (!mModule->CheckGenericConstraints(BfGenericParamSource(moduleMethodInstance.mMethodInstance), genericArg, paramSrc, genericParams, NULL,
  13298. failed ? NULL : &error))
  13299. {
  13300. if (moduleMethodInstance.mMethodInstance->IsSpecializedGenericMethod())
  13301. {
  13302. // We mark this as failed to make sure we don't try to process a method that doesn't even follow the constraints
  13303. moduleMethodInstance.mMethodInstance->mFailedConstraints = true;
  13304. }
  13305. if (moduleMethodInstance.mMethodInstance->mMethodDef->mMethodDeclaration != NULL)
  13306. {
  13307. if (error != NULL)
  13308. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("See method declaration"), moduleMethodInstance.mMethodInstance->mMethodDef->GetRefNode());
  13309. }
  13310. }
  13311. }
  13312. }
  13313. else
  13314. BF_ASSERT(methodMatcher.mBestMethodGenericArguments.IsEmpty());
  13315. if ((overrideReturnType != NULL) && (moduleMethodInstance.mMethodInstance->mIsUnspecializedVariation) &&
  13316. ((moduleMethodInstance.mMethodInstance->mReturnType->IsUnspecializedTypeVariation()) || (moduleMethodInstance.mMethodInstance->mReturnType->IsVar())))
  13317. {
  13318. if (unspecializedMethod == NULL)
  13319. unspecializedMethod = mModule->GetRawMethodInstance(curTypeInst, methodDef);
  13320. BfTypeVector* typeGenericArgs = NULL;
  13321. auto typeUnspecMethodInstance = unspecializedMethod;
  13322. if (curTypeInst->IsUnspecializedTypeVariation())
  13323. {
  13324. typeUnspecMethodInstance = mModule->GetUnspecializedMethodInstance(typeUnspecMethodInstance, true);
  13325. typeGenericArgs = &curTypeInst->mGenericTypeInfo->mTypeGenericArguments;
  13326. }
  13327. BfType* specializedReturnType = mModule->ResolveGenericType(typeUnspecMethodInstance->mReturnType, typeGenericArgs, &methodMatcher.mBestMethodGenericArguments);
  13328. if (specializedReturnType != NULL)
  13329. *overrideReturnType = specializedReturnType;
  13330. }
  13331. return moduleMethodInstance;
  13332. }
  13333. void BfExprEvaluator::CheckLocalMethods(BfAstNode* targetSrc, BfTypeInstance* typeInstance, const StringImpl& methodName, BfMethodMatcher& methodMatcher, BfMethodType methodType)
  13334. {
  13335. auto _GetNodeId = [&]()
  13336. {
  13337. auto parser = targetSrc->GetSourceData()->ToParserData();
  13338. return ((int64)parser->mDataId << 32) + targetSrc->GetSrcStart();
  13339. };
  13340. BfMethodState* ctxMethodState = NULL;
  13341. BfClosureInstanceInfo* ctxClosureInstanceInfo = NULL;
  13342. if ((mModule->mCurMethodState != NULL) && (mModule->mCurMethodState->mClosureState != NULL))
  13343. {
  13344. ctxClosureInstanceInfo = mModule->mCurMethodState->mClosureState->mClosureInstanceInfo;
  13345. ctxMethodState = mModule->mCurMethodState;
  13346. }
  13347. bool atCtxMethodState = false;
  13348. auto checkMethodState = mModule->mCurMethodState;
  13349. auto rootMethodState = checkMethodState;
  13350. while (checkMethodState != NULL)
  13351. {
  13352. rootMethodState = checkMethodState;
  13353. if (checkMethodState == ctxMethodState)
  13354. atCtxMethodState = true;
  13355. if ((ctxClosureInstanceInfo != NULL) && (!ctxMethodState->mClosureState->mCapturing))
  13356. {
  13357. BfMethodDef* localMethodDef = NULL;
  13358. if (ctxClosureInstanceInfo->mLocalMethodBindings.TryGetValue(_GetNodeId(), &localMethodDef))
  13359. {
  13360. methodMatcher.CheckMethod(mModule->mCurTypeInstance, mModule->mCurTypeInstance, localMethodDef, true);
  13361. BF_ASSERT(methodMatcher.mBestMethodDef != NULL);
  13362. return;
  13363. }
  13364. }
  13365. else
  13366. {
  13367. BfLocalMethod* matchedLocalMethod = NULL;
  13368. BfLocalMethod* localMethod = NULL;
  13369. if (checkMethodState->mLocalMethodMap.TryGetValue(methodName, &localMethod))
  13370. {
  13371. auto typeInst = mModule->mCurTypeInstance;
  13372. if (checkMethodState->mMixinState != NULL)
  13373. typeInst = checkMethodState->mMixinState->mMixinMethodInstance->GetOwner();
  13374. while (localMethod != NULL)
  13375. {
  13376. auto methodDef = mModule->GetLocalMethodDef(localMethod);
  13377. if (methodDef->mMethodType == methodType)
  13378. {
  13379. methodMatcher.CheckMethod(mModule->mCurTypeInstance, typeInst, methodDef, true);
  13380. if (methodMatcher.mBestMethodDef == methodDef)
  13381. matchedLocalMethod = localMethod;
  13382. }
  13383. localMethod = localMethod->mNextWithSameName;
  13384. }
  13385. }
  13386. if (matchedLocalMethod != NULL)
  13387. {
  13388. if ((mModule->mCurMethodState != NULL) && (mModule->mCurMethodState->mClosureState != NULL) && (mModule->mCurMethodState->mClosureState->mCapturing))
  13389. {
  13390. BfModuleMethodInstance moduleMethodInstance = GetSelectedMethod(targetSrc, typeInstance, matchedLocalMethod->mMethodDef, methodMatcher);
  13391. if (moduleMethodInstance)
  13392. {
  13393. auto methodInstance = moduleMethodInstance.mMethodInstance;
  13394. if ((methodInstance->mMethodInfoEx != NULL) && (methodInstance->mMethodInfoEx->mClosureInstanceInfo->mCaptureClosureState != NULL))
  13395. {
  13396. // The called method is calling us from its mLocalMethodRefs set. Stretch our mCaptureStartAccessId back to incorporate its
  13397. // captures as well
  13398. if (methodInstance->mMethodInfoEx->mClosureInstanceInfo->mCaptureClosureState->mCaptureStartAccessId < mModule->mCurMethodState->mClosureState->mCaptureStartAccessId)
  13399. mModule->mCurMethodState->mClosureState->mCaptureStartAccessId = methodInstance->mMethodInfoEx->mClosureInstanceInfo->mCaptureClosureState->mCaptureStartAccessId;
  13400. }
  13401. else
  13402. {
  13403. if (methodInstance->mDisallowCalling) // We need to process the captures from this guy
  13404. {
  13405. if (mModule->mCurMethodState->mClosureState->mLocalMethodRefSet.Add(methodInstance))
  13406. mModule->mCurMethodState->mClosureState->mLocalMethodRefs.Add(methodInstance);
  13407. }
  13408. }
  13409. }
  13410. }
  13411. if (ctxClosureInstanceInfo != NULL)
  13412. {
  13413. BF_ASSERT(mModule->mCurMethodState->mClosureState->mCapturing);
  13414. ctxClosureInstanceInfo->mLocalMethodBindings[_GetNodeId()] = methodMatcher.mBestMethodDef;
  13415. }
  13416. break;
  13417. }
  13418. }
  13419. checkMethodState = checkMethodState->mPrevMethodState;
  13420. }
  13421. }
  13422. void BfExprEvaluator::InjectMixin(BfAstNode* targetSrc, BfTypedValue target, bool allowImplicitThis, const StringImpl& name, const BfSizedArray<BfExpression*>& arguments, BfSizedArray<ASTREF(BfTypeReference*)>* methodGenericArgs)
  13423. {
  13424. if (mModule->mCurMethodState == NULL)
  13425. return;
  13426. if (mDeferCallRef != NULL)
  13427. {
  13428. mModule->Fail("Mixins cannot be directly deferred. Consider wrapping in a block.", targetSrc);
  13429. }
  13430. BfAstNode* origTargetSrc = targetSrc;
  13431. BfScopedInvocationTarget* scopedInvocationTarget = NULL;
  13432. if (mModule->mParentNodeEntry != NULL)
  13433. {
  13434. if (auto invocationExpr = BfNodeDynCast<BfInvocationExpression>(mModule->mParentNodeEntry->mNode))
  13435. {
  13436. scopedInvocationTarget = BfNodeDynCast<BfScopedInvocationTarget>(invocationExpr->mTarget);
  13437. }
  13438. }
  13439. auto targetNameNode = targetSrc;
  13440. if (scopedInvocationTarget != NULL)
  13441. targetNameNode = scopedInvocationTarget->mTarget;
  13442. BfTypeInstance* mixinClass = NULL;
  13443. if (target.mType != NULL)
  13444. mixinClass = target.mType->ToTypeInstance();
  13445. int inLine = mModule->mCurFilePosition.mCurLine;
  13446. SizedArray<BfResolvedArg, 4> args;
  13447. SizedArray<BfExprEvaluator*, 8> argExprEvaluators;
  13448. defer
  13449. (
  13450. {
  13451. for (auto exprEvaluator : argExprEvaluators)
  13452. delete exprEvaluator;
  13453. }
  13454. );
  13455. auto _AddArg = [&](BfExpression* argExpr)
  13456. {
  13457. BfResolvedArg resolvedArg;
  13458. argExprEvaluators.push_back(new BfExprEvaluator(mModule));
  13459. BfExprEvaluator* exprEvaluator = argExprEvaluators.back();
  13460. exprEvaluator->mResolveGenericParam = false;
  13461. exprEvaluator->mBfEvalExprFlags = (BfEvalExprFlags)(exprEvaluator->mBfEvalExprFlags | BfEvalExprFlags_NoCast | BfEvalExprFlags_AllowRefExpr | BfEvalExprFlags_AllowOutExpr);
  13462. bool deferExpr = false;
  13463. if (auto variableDecl = BfNodeDynCast<BfVariableDeclaration>(argExpr))
  13464. {
  13465. deferExpr = true;
  13466. resolvedArg.mArgFlags = (BfArgFlags)(resolvedArg.mArgFlags | BfArgFlag_VariableDeclaration);
  13467. }
  13468. if (deferExpr)
  13469. {
  13470. //
  13471. }
  13472. else if (argExpr != NULL)
  13473. exprEvaluator->Evaluate(argExpr, false, false, true);
  13474. else
  13475. mModule->Fail("Missing argument", targetSrc);
  13476. auto argValue = exprEvaluator->mResult;
  13477. mModule->FixIntUnknown(argValue);
  13478. if (argValue)
  13479. {
  13480. if (argValue.mType->IsRef())
  13481. {
  13482. exprEvaluator->FinishExpressionResult();
  13483. }
  13484. }
  13485. resolvedArg.mTypedValue = argValue;
  13486. resolvedArg.mExpression = argExpr;
  13487. args.push_back(resolvedArg);
  13488. };
  13489. for (BfExpression* argExpr : arguments)
  13490. {
  13491. _AddArg(argExpr);
  13492. }
  13493. auto autoComplete = GetAutoComplete();
  13494. if ((autoComplete != NULL) && (autoComplete->mIsCapturingMethodMatchInfo) && (autoComplete->mMethodMatchInfo != NULL) && (autoComplete->mMethodMatchInfo->mInstanceList.size() != 0))
  13495. autoComplete->mIsCapturingMethodMatchInfo = false;
  13496. BfMethodMatcher methodMatcher(targetSrc, mModule, name, args, methodGenericArgs);
  13497. methodMatcher.mMethodType = BfMethodType_Mixin;
  13498. methodMatcher.mSkipImplicitParams = true;
  13499. auto curTypeInst = mModule->mCurTypeInstance;
  13500. if (mixinClass != NULL)
  13501. curTypeInst = mixinClass;
  13502. if (target.mType == NULL)
  13503. {
  13504. CheckLocalMethods(targetSrc, curTypeInst, name, methodMatcher, BfMethodType_Mixin);
  13505. }
  13506. if (methodMatcher.mBestMethodDef == NULL)
  13507. methodMatcher.mBestMethodDef = methodMatcher.mBackupMethodDef;
  13508. if (methodMatcher.mBestMethodDef == NULL)
  13509. {
  13510. if (mixinClass != NULL)
  13511. methodMatcher.CheckType(mixinClass, BfTypedValue(), false);
  13512. else
  13513. methodMatcher.CheckType(mModule->mCurTypeInstance, BfTypedValue(), false);
  13514. }
  13515. if ((methodMatcher.mBestMethodDef == NULL) && (target.mType == NULL) && (mModule->mContext->mCurTypeState != NULL))
  13516. {
  13517. BF_ASSERT(mModule->mCurTypeInstance == mModule->mContext->mCurTypeState->mType);
  13518. BfGlobalLookup globalLookup;
  13519. globalLookup.mKind = BfGlobalLookup::Kind_Method;
  13520. globalLookup.mName = name;
  13521. mModule->PopulateGlobalContainersList(globalLookup);
  13522. for (auto& globalContainer : mModule->mContext->mCurTypeState->mGlobalContainers)
  13523. {
  13524. if (globalContainer.mTypeInst == NULL)
  13525. continue;
  13526. methodMatcher.CheckType(globalContainer.mTypeInst, BfTypedValue(), false);
  13527. if (methodMatcher.mBestMethodDef != NULL)
  13528. break;
  13529. }
  13530. }
  13531. if (methodMatcher.mBestMethodDef == NULL)
  13532. {
  13533. mModule->Fail("Cannot find mixin", targetSrc);
  13534. return;
  13535. }
  13536. auto resolvePassData = mModule->mCompiler->mResolvePassData;
  13537. if ((autoComplete != NULL) && (autoComplete->IsAutocompleteNode(targetNameNode)) && (autoComplete->mDefType == NULL))
  13538. {
  13539. autoComplete->mInsertStartIdx = targetNameNode->GetSrcStart();
  13540. autoComplete->mInsertEndIdx = targetNameNode->GetSrcEnd();
  13541. autoComplete->mDefType = methodMatcher.mBestMethodTypeInstance->mTypeDef;
  13542. autoComplete->mDefMethod = methodMatcher.mBestMethodDef;
  13543. autoComplete->SetDefinitionLocation(methodMatcher.mBestMethodDef->GetMethodDeclaration()->mNameNode);
  13544. }
  13545. if ((mModule->mCompiler->mResolvePassData != NULL) && (mModule->mCompiler->mResolvePassData->mGetSymbolReferenceKind == BfGetSymbolReferenceKind_Method))
  13546. {
  13547. targetNameNode->SetSrcEnd(targetNameNode->GetSrcEnd() - 1);
  13548. mModule->mCompiler->mResolvePassData->HandleMethodReference(targetNameNode, methodMatcher.mBestMethodTypeInstance->mTypeDef, methodMatcher.mBestMethodDef);
  13549. targetNameNode->SetSrcEnd(targetNameNode->GetSrcEnd() + 1);
  13550. }
  13551. auto curMethodState = mModule->mCurMethodState;
  13552. //
  13553. // Why was this required? It doesn't check for matching generic args (we only want to throw an error if we call back into a mixin with the same generic args as before)
  13554. // {
  13555. // bool hasCircularRef = false;
  13556. //
  13557. // auto checkMethodState = curMethodState;
  13558. // while (checkMethodState != NULL)
  13559. // {
  13560. // auto curMixinState = checkMethodState->mMixinState;
  13561. // while (curMixinState != NULL)
  13562. // {
  13563. // if (curMixinState->mSource == targetSrc)
  13564. // hasCircularRef = true;
  13565. // curMixinState = curMixinState->mPrevMixinState;
  13566. // }
  13567. //
  13568. // if ((checkMethodState->mClosureState != NULL) && (checkMethodState->mClosureState->mActiveDeferredLocalMethod != NULL))
  13569. // {
  13570. // for (auto& mixinRecord : checkMethodState->mClosureState->mActiveDeferredLocalMethod->mMixinStateRecords)
  13571. // {
  13572. // if (mixinRecord.mSource == targetSrc)
  13573. // hasCircularRef = true;
  13574. // }
  13575. // }
  13576. //
  13577. // checkMethodState = checkMethodState->mPrevMethodState;
  13578. // }
  13579. //
  13580. // if (hasCircularRef)
  13581. // {
  13582. // mModule->Fail("Circular reference detected between mixins", targetSrc);
  13583. // return;
  13584. // }
  13585. // }
  13586. auto moduleMethodInstance = GetSelectedMethod(targetSrc, methodMatcher.mBestMethodTypeInstance, methodMatcher.mBestMethodDef, methodMatcher);
  13587. if (!moduleMethodInstance)
  13588. {
  13589. if (methodMatcher.mHasVarArguments)
  13590. {
  13591. mResult = mModule->GetDefaultTypedValue(mModule->GetPrimitiveType(BfTypeCode_Var));
  13592. return;
  13593. }
  13594. mModule->Fail("Failed to get selected mixin", targetSrc);
  13595. return;
  13596. }
  13597. if (!mModule->CheckUseMethodInstance(moduleMethodInstance.mMethodInstance, targetSrc))
  13598. return;
  13599. auto methodInstance = moduleMethodInstance.mMethodInstance;
  13600. PerformCallChecks(methodInstance, targetSrc);
  13601. for (int checkGenericIdx = 0; checkGenericIdx < (int)methodMatcher.mBestMethodGenericArguments.size(); checkGenericIdx++)
  13602. {
  13603. auto& genericParams = methodInstance->mMethodInfoEx->mGenericParams;
  13604. auto genericArg = methodMatcher.mBestMethodGenericArguments[checkGenericIdx];
  13605. if (genericArg->IsVar())
  13606. continue;
  13607. BfAstNode* paramSrc;
  13608. if (methodMatcher.mBestMethodGenericArgumentSrcs.size() == 0)
  13609. paramSrc = targetSrc;
  13610. else
  13611. paramSrc = methodMatcher.mArguments[methodMatcher.mBestMethodGenericArgumentSrcs[checkGenericIdx]].mExpression;
  13612. // Note: don't pass methodMatcher.mBestMethodGenericArguments into here, this method is already specialized
  13613. BfError* error = NULL;
  13614. if (!mModule->CheckGenericConstraints(BfGenericParamSource(methodInstance), genericArg, paramSrc, genericParams[checkGenericIdx], NULL, &error))
  13615. {
  13616. if (methodInstance->mMethodDef->mMethodDeclaration != NULL)
  13617. {
  13618. if (error != NULL)
  13619. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("See method declaration"), methodInstance->mMethodDef->GetRefNode());
  13620. }
  13621. }
  13622. }
  13623. // Check circular ref based on methodInstance
  13624. {
  13625. bool hasCircularRef = false;
  13626. auto checkMethodState = curMethodState;
  13627. while (checkMethodState != NULL)
  13628. {
  13629. if (checkMethodState->mMethodInstance == methodInstance)
  13630. hasCircularRef = true;
  13631. auto curMixinState = checkMethodState->mMixinState;
  13632. while (curMixinState != NULL)
  13633. {
  13634. if (curMixinState->mMixinMethodInstance == methodInstance)
  13635. hasCircularRef = true;
  13636. curMixinState = curMixinState->mPrevMixinState;
  13637. }
  13638. checkMethodState = checkMethodState->mPrevMethodState;
  13639. }
  13640. if (hasCircularRef)
  13641. {
  13642. mModule->Fail("Circular reference detected between mixins", targetSrc);
  13643. return;
  13644. }
  13645. }
  13646. AddCallDependencies(methodInstance);
  13647. if (!methodMatcher.mBestMethodDef->mIsStatic)
  13648. {
  13649. if ((!target) && (allowImplicitThis))
  13650. target = mModule->GetThis();
  13651. if (!target)
  13652. {
  13653. BfError* error = mModule->Fail(StrFormat("An instance reference is required to invoke the non-static mixin '%s'",
  13654. mModule->MethodToString(methodInstance).c_str()), targetSrc);
  13655. if ((error != NULL) && (methodInstance->mMethodDef->GetRefNode() != NULL))
  13656. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("See method declaration"), methodInstance->mMethodDef->GetRefNode());
  13657. }
  13658. }
  13659. else
  13660. {
  13661. if (target)
  13662. {
  13663. BfError* error = mModule->Fail(StrFormat("Mixin '%s' cannot be accessed with an instance reference; qualify it with a type name instead",
  13664. mModule->MethodToString(methodInstance).c_str()), targetSrc);
  13665. if ((error != NULL) && (methodInstance->mMethodDef->GetRefNode() != NULL))
  13666. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("See method declaration"), methodInstance->mMethodDef->GetRefNode());
  13667. }
  13668. }
  13669. int methodParamCount = (int)methodInstance->GetParamCount();
  13670. // Implicit params are ignored for calling- they should be resolved at the injection site
  13671. int implicitParamCount = methodInstance->GetImplicitParamCount();
  13672. int explicitParamCount = methodParamCount - implicitParamCount;
  13673. while ((int)args.size() < explicitParamCount)
  13674. {
  13675. int argIdx = (int)args.size();
  13676. BfExpression* expr = methodInstance->GetParamInitializer(argIdx);
  13677. if (expr == NULL)
  13678. break;
  13679. _AddArg(expr);
  13680. }
  13681. if ((int)args.size() < explicitParamCount)
  13682. {
  13683. BfError* error = mModule->Fail(StrFormat("Not enough arguments specified, expected %d more.", explicitParamCount - (int)arguments.size()), targetSrc);
  13684. if ((error != NULL) && (methodInstance->mMethodDef->GetRefNode() != NULL))
  13685. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("See method declaration"), methodInstance->mMethodDef->GetRefNode());
  13686. return;
  13687. }
  13688. else if ((int)args.size() > explicitParamCount)
  13689. {
  13690. BfError* error = mModule->Fail(StrFormat("Too many arguments specified, expected %d fewer.", (int)arguments.size() - explicitParamCount), targetSrc);
  13691. if ((error != NULL) && (methodInstance->mMethodDef->GetRefNode() != NULL))
  13692. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("See method declaration"), methodInstance->mMethodDef->GetRefNode());
  13693. return;
  13694. }
  13695. int paramIdx = implicitParamCount;
  13696. auto argExprEvaluatorItr = argExprEvaluators.begin();
  13697. for (int argIdx = 0; argIdx < (int)args.size(); argIdx++)
  13698. {
  13699. auto exprEvaluator = *argExprEvaluatorItr;
  13700. //auto paramType = methodInstance->GetParamKind(paramIdx);
  13701. BfType* wantType = methodInstance->mParams[paramIdx].mResolvedType;
  13702. auto& arg = args[argIdx];
  13703. if ((arg.mArgFlags & BfArgFlag_VariableDeclaration) != 0)
  13704. {
  13705. arg.mTypedValue = ResolveArgValue(arg, wantType);
  13706. }
  13707. if (wantType->IsGenericParam())
  13708. {
  13709. //
  13710. }
  13711. else if (!wantType->IsVar())
  13712. {
  13713. if (arg.mTypedValue.mType == NULL)
  13714. {
  13715. mModule->AssertErrorState();
  13716. return;
  13717. }
  13718. if (arg.mTypedValue.mType != wantType)
  13719. {
  13720. exprEvaluator->FinishExpressionResult();
  13721. arg.mTypedValue = mModule->LoadValue(arg.mTypedValue);
  13722. arg.mTypedValue = mModule->Cast(arg.mExpression, arg.mTypedValue, wantType);
  13723. /*// Do this to generate default implicit cast error
  13724. mModule->Fail(StrFormat("Mixin argument type '%s' must match parameter type '%s'.",
  13725. mModule->TypeToString(arg.mTypedValue.mType).c_str(),
  13726. mModule->TypeToString(wantType).c_str()), arg.mExpression);
  13727. return;*/
  13728. }
  13729. }
  13730. paramIdx++;
  13731. argExprEvaluatorItr++;
  13732. }
  13733. mModule->AddDependency(methodInstance->GetOwner(), mModule->mCurTypeInstance, BfDependencyMap::DependencyFlag_InlinedCall);
  13734. auto startBlock = mModule->mBfIRBuilder->CreateBlock("mixinStart");
  13735. mModule->mBfIRBuilder->CreateBr(startBlock);
  13736. mModule->mBfIRBuilder->AddBlock(startBlock);
  13737. mModule->mBfIRBuilder->SetInsertPoint(startBlock);
  13738. //auto prevDebugLoc = mModule->mBfIRBuilder->getCurrentDebugLocation();
  13739. // This is so when we debug we can hit a steppoint on the inlined "call line"
  13740. mModule->EmitEnsureInstructionAt();
  13741. auto rootMethodState = mModule->mCurMethodState->GetRootMethodState();
  13742. BfMixinState* mixinState = rootMethodState->mMixinStates.Alloc();
  13743. mixinState->mInjectFilePosition = mModule->mCurFilePosition;
  13744. mixinState->mPrevMixinState = curMethodState->mMixinState;
  13745. mixinState->mLocalsStartIdx = (int)mModule->mCurMethodState->mLocals.size();
  13746. mixinState->mMixinMethodInstance = methodInstance;
  13747. mixinState->mSource = origTargetSrc;
  13748. mixinState->mCallerScope = mModule->mCurMethodState->mCurScope;
  13749. mixinState->mTargetScope = mixinState->mCallerScope;
  13750. mixinState->mResultExpr = NULL;
  13751. mixinState->mHasDeferredUsage = false;
  13752. mixinState->mUsedInvocationScope = false;
  13753. mixinState->mTarget = target;
  13754. auto checkNode = origTargetSrc;
  13755. if (scopedInvocationTarget != NULL)
  13756. {
  13757. auto targetScope = mModule->FindScope(scopedInvocationTarget->mScopeName, curMethodState->mMixinState);
  13758. if (targetScope != NULL)
  13759. {
  13760. mixinState->mTargetScope = targetScope;
  13761. if (autoComplete != NULL)
  13762. {
  13763. if (auto identifer = BfNodeDynCast<BfIdentifierNode>(scopedInvocationTarget->mScopeName))
  13764. autoComplete->CheckLabel(identifer, NULL, targetScope);
  13765. }
  13766. }
  13767. }
  13768. mModule->mBfIRBuilder->SaveDebugLocation();
  13769. SetAndRestoreValue<BfMixinState*> prevMixinState(curMethodState->mMixinState, mixinState);
  13770. BfGetSymbolReferenceKind prevSymbolRefKind = BfGetSymbolReferenceKind_None;
  13771. if (mModule->mCompiler->mResolvePassData != NULL)
  13772. {
  13773. prevSymbolRefKind = mModule->mCompiler->mResolvePassData->mGetSymbolReferenceKind;
  13774. mModule->mCompiler->mResolvePassData->mGetSymbolReferenceKind = BfGetSymbolReferenceKind_None;
  13775. }
  13776. defer
  13777. (
  13778. {
  13779. if (mModule->mCompiler->mResolvePassData != NULL)
  13780. mModule->mCompiler->mResolvePassData->mGetSymbolReferenceKind = prevSymbolRefKind;
  13781. }
  13782. );
  13783. auto methodDef = methodInstance->mMethodDef;
  13784. auto methodDeclaration = methodDef->GetMethodDeclaration();
  13785. BfScopeData scopeData;
  13786. scopeData.mCloseNode = methodDeclaration->mBody;
  13787. if (auto block = BfNodeDynCast<BfBlock>(methodDeclaration->mBody))
  13788. {
  13789. if (block->mCloseBrace != NULL)
  13790. scopeData.mCloseNode = block->mCloseBrace;
  13791. }
  13792. curMethodState->AddScope(&scopeData);
  13793. curMethodState->mCurScope->mMixinDepth++;
  13794. // We can't flush scope state because we extend params in as arbitrary values
  13795. mModule->NewScopeState(true, false);
  13796. bool wantsDIData = (mModule->mBfIRBuilder->DbgHasInfo()) && (mModule->mHasFullDebugInfo);
  13797. DISubprogram* diFunction = NULL;
  13798. int startLocalIdx = (int)mModule->mCurMethodState->mLocals.size();
  13799. int endLocalIdx = startLocalIdx;
  13800. if (wantsDIData)
  13801. {
  13802. BfIRMDNode diFuncType = mModule->mBfIRBuilder->DbgCreateSubroutineType(methodInstance);
  13803. //int defLine = mModule->mCurFilePosition.mCurLine;
  13804. int flags = 0;
  13805. curMethodState->mCurScope->mDIInlinedAt = mModule->mBfIRBuilder->DbgGetCurrentLocation();
  13806. // 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
  13807. // definitions, so we need to be consistent and use the actual line
  13808. mModule->UpdateSrcPos(methodDeclaration->mNameNode, BfSrcPosFlag_NoSetDebugLoc);
  13809. int defLine = mModule->mCurFilePosition.mCurLine;
  13810. auto diParentType = mModule->mBfIRBuilder->DbgGetTypeInst(methodInstance->GetOwner());
  13811. if (!mModule->mBfIRBuilder->mIgnoreWrites)
  13812. {
  13813. String methodName = methodDef->mName;
  13814. methodName += "!";
  13815. BfMangler::Mangle(methodName, mModule->mCompiler->GetMangleKind(), methodInstance);
  13816. curMethodState->mCurScope->mDIScope = mModule->mBfIRBuilder->DbgCreateFunction(diParentType, methodName, "", mModule->mCurFilePosition.mFileInstance->mDIFile,
  13817. defLine + 1, diFuncType, false, true, mModule->mCurFilePosition.mCurLine + 1, flags, false, BfIRValue());
  13818. scopeData.mAltDIFile = mModule->mCurFilePosition.mFileInstance->mDIFile;
  13819. }
  13820. }
  13821. if (methodDef->mBody != NULL)
  13822. mModule->UpdateSrcPos(methodDef->mBody);
  13823. mModule->SetIllegalSrcPos();
  13824. auto _AddLocalVariable = [&](BfLocalVariable* newLocalVar, BfExprEvaluator* exprEvaluator)
  13825. {
  13826. mModule->SetIllegalSrcPos();
  13827. bool hasConstValue = newLocalVar->mConstValue;
  13828. if (hasConstValue)
  13829. {
  13830. auto constant = mModule->mBfIRBuilder->GetConstant(newLocalVar->mConstValue);
  13831. hasConstValue = constant->mConstType < BfConstType_GlobalVar;
  13832. }
  13833. if ((exprEvaluator != NULL) && (exprEvaluator->mResultLocalVar != NULL) && (exprEvaluator->mResultLocalVarField == 0))
  13834. {
  13835. mModule->UpdateSrcPos(methodDeclaration->mNameNode);
  13836. mModule->AddLocalVariableDef(newLocalVar, hasConstValue);
  13837. auto inLocalVar = exprEvaluator->mResultLocalVar;
  13838. newLocalVar->mAssignedKind = inLocalVar->mAssignedKind;
  13839. newLocalVar->mUnassignedFieldFlags = inLocalVar->mUnassignedFieldFlags;
  13840. newLocalVar->mReadFromId = inLocalVar->mReadFromId;
  13841. newLocalVar->mIsReadOnly = inLocalVar->mIsReadOnly;
  13842. if ((newLocalVar->mAssignedKind == BfLocalVarAssignKind_None) && (mModule->mCurMethodState->mDeferredLocalAssignData != NULL))
  13843. {
  13844. for (auto deferredAssign : mModule->mCurMethodState->mDeferredLocalAssignData->mAssignedLocals)
  13845. {
  13846. if (deferredAssign.mLocalVar == inLocalVar)
  13847. newLocalVar->mAssignedKind = BfLocalVarAssignKind_Unconditional;
  13848. }
  13849. }
  13850. }
  13851. else
  13852. {
  13853. mModule->AddLocalVariableDef(newLocalVar, hasConstValue);
  13854. }
  13855. if ((wantsDIData) && (!mModule->mBfIRBuilder->mIgnoreWrites))
  13856. {
  13857. mModule->UpdateSrcPos(methodDeclaration->mNameNode);
  13858. if (hasConstValue)
  13859. {
  13860. // Already handled
  13861. }
  13862. else if (newLocalVar->mIsSplat)
  13863. {
  13864. bool found = false;
  13865. auto checkMethodState = mModule->mCurMethodState;
  13866. while ((checkMethodState != NULL) && (!found))
  13867. {
  13868. for (auto localVar : checkMethodState->mLocals)
  13869. {
  13870. if (localVar == newLocalVar)
  13871. continue;
  13872. if (!localVar->mIsSplat)
  13873. continue;
  13874. if (newLocalVar->mValue != localVar->mAddr)
  13875. continue;
  13876. String name = "$";
  13877. name += newLocalVar->mName;
  13878. name += "$alias$";
  13879. name += localVar->mName;
  13880. // auto fakeValue = mModule->mBfIRBuilder->CreateConst(BfTypeCode_Int32, 0);
  13881. // auto diType = mModule->mBfIRBuilder->DbgGetType(mModule->GetPrimitiveType(BfTypeCode_Int32));
  13882. // auto diVariable = mModule->mBfIRBuilder->DbgCreateAutoVariable(mModule->mCurMethodState->mCurScope->mDIScope,
  13883. // name, mModule->mCurFilePosition.mFileInstance->mDIFile, mModule->mCurFilePosition.mCurLine, diType);
  13884. // mModule->mBfIRBuilder->DbgInsertValueIntrinsic(fakeValue, diVariable);
  13885. auto diType = mModule->mBfIRBuilder->DbgGetType(mModule->GetPrimitiveType(BfTypeCode_NullPtr));
  13886. auto diVariable = mModule->mBfIRBuilder->DbgCreateAutoVariable(mModule->mCurMethodState->mCurScope->mDIScope,
  13887. name, mModule->mCurFilePosition.mFileInstance->mDIFile, mModule->mCurFilePosition.mCurLine, diType);
  13888. mModule->mBfIRBuilder->DbgInsertValueIntrinsic(mModule->mBfIRBuilder->CreateConstNull(), diVariable);
  13889. found = true;
  13890. break;
  13891. }
  13892. checkMethodState = checkMethodState->mPrevMethodState;
  13893. }
  13894. }
  13895. else if (mModule->IsTargetingBeefBackend())
  13896. {
  13897. mModule->UpdateSrcPos(methodDeclaration->mNameNode);
  13898. mModule->SetIllegalSrcPos();
  13899. // With the Beef backend we can assign two variables to the same value, but LLVM does not allow this
  13900. // so we have to create a ref to that variable
  13901. auto diType = mModule->mBfIRBuilder->DbgGetType(newLocalVar->mResolvedType);
  13902. auto diVariable = mModule->mBfIRBuilder->DbgCreateAutoVariable(mModule->mCurMethodState->mCurScope->mDIScope,
  13903. newLocalVar->mName, mModule->mCurFilePosition.mFileInstance->mDIFile, mModule->mCurFilePosition.mCurLine, diType);
  13904. if (newLocalVar->mIsSplat)
  13905. {
  13906. //TODO: Implement
  13907. }
  13908. else if (newLocalVar->mResolvedType->IsValuelessType())
  13909. {
  13910. // Do nothing
  13911. }
  13912. else
  13913. {
  13914. BfIRValue value = newLocalVar->mValue;
  13915. if (newLocalVar->mAddr)
  13916. value = newLocalVar->mAddr;
  13917. else if (newLocalVar->mConstValue)
  13918. value = newLocalVar->mConstValue;
  13919. auto aliasValue = mModule->mBfIRBuilder->CreateAliasValue(value);
  13920. if (mModule->WantsLifetimes())
  13921. scopeData.mDeferredLifetimeEnds.Add(aliasValue);
  13922. if (newLocalVar->mAddr)
  13923. mModule->mBfIRBuilder->DbgInsertDeclare(aliasValue, diVariable);
  13924. else
  13925. {
  13926. mModule->mBfIRBuilder->DbgInsertValueIntrinsic(aliasValue, diVariable);
  13927. //mModule->mBfIRBuilder->DbgInsertValueIntrinsic(newLocalVar->mValue, diVariable);
  13928. }
  13929. }
  13930. }
  13931. else if (newLocalVar->mAddr)
  13932. {
  13933. mModule->UpdateSrcPos(methodDeclaration->mNameNode);
  13934. mModule->SetIllegalSrcPos();
  13935. auto refType = mModule->CreateRefType(newLocalVar->mResolvedType);
  13936. auto allocaVal = mModule->CreateAlloca(refType);
  13937. mModule->mBfIRBuilder->CreateStore(newLocalVar->mAddr, allocaVal);
  13938. if (!mModule->mBfIRBuilder->mIgnoreWrites)
  13939. {
  13940. auto diType = mModule->mBfIRBuilder->DbgGetType(refType);
  13941. auto diVariable = mModule->mBfIRBuilder->DbgCreateAutoVariable(mModule->mCurMethodState->mCurScope->mDIScope,
  13942. newLocalVar->mName, mModule->mCurFilePosition.mFileInstance->mDIFile, mModule->mCurFilePosition.mCurLine, diType);
  13943. mModule->mBfIRBuilder->DbgInsertDeclare(allocaVal, diVariable);
  13944. }
  13945. }
  13946. else if (newLocalVar->mValue)
  13947. {
  13948. mModule->UpdateSrcPos(methodDeclaration->mNameNode);
  13949. mModule->SetIllegalSrcPos();
  13950. auto localVal = LoadLocal(newLocalVar);
  13951. localVal = mModule->LoadValue(localVal);
  13952. localVal = mModule->AggregateSplat(localVal);
  13953. BfType* allocType = localVal.mType;
  13954. auto allocaVal = mModule->CreateAlloca(allocType);
  13955. mModule->mBfIRBuilder->CreateStore(localVal.mValue, allocaVal);
  13956. if (!mModule->mBfIRBuilder->mIgnoreWrites)
  13957. {
  13958. if (newLocalVar->mIsSplat)
  13959. {
  13960. //TODO: Implement
  13961. }
  13962. else
  13963. {
  13964. auto diType = mModule->mBfIRBuilder->DbgGetType(allocType);
  13965. auto diVariable = mModule->mBfIRBuilder->DbgCreateAutoVariable(mModule->mCurMethodState->mCurScope->mDIScope,
  13966. newLocalVar->mName, mModule->mCurFilePosition.mFileInstance->mDIFile, mModule->mCurFilePosition.mCurLine, diType);
  13967. mModule->mBfIRBuilder->DbgInsertDeclare(allocaVal, diVariable);
  13968. }
  13969. }
  13970. }
  13971. }
  13972. newLocalVar->mParamIdx = -3;
  13973. };
  13974. argExprEvaluatorItr = argExprEvaluators.begin();
  13975. for (int argIdx = methodDef->mIsStatic ? 0 : -1; argIdx < (int)explicitParamCount; argIdx++)
  13976. {
  13977. int paramIdx = argIdx;
  13978. auto exprEvaluator = *argExprEvaluatorItr;
  13979. BfTypedValue argValue;
  13980. BfLocalVariable* localVar = new BfLocalVariable();
  13981. if (argIdx == -1)
  13982. {
  13983. argValue = target;
  13984. localVar->mName = "this";
  13985. localVar->mIsThis = true;
  13986. localVar->mAssignedKind = BfLocalVarAssignKind_Unconditional;
  13987. }
  13988. else
  13989. {
  13990. auto arg = &args[argIdx];
  13991. auto paramDef = methodDef->mParams[paramIdx];
  13992. localVar->mName = paramDef->mName;
  13993. if (!arg->mTypedValue)
  13994. {
  13995. auto wantType = methodInstance->GetParamType(paramIdx);
  13996. if (wantType->IsVar())
  13997. wantType = mModule->mContext->mBfObjectType;
  13998. arg->mTypedValue = mModule->GetDefaultTypedValue(wantType);
  13999. }
  14000. argValue = arg->mTypedValue;
  14001. }
  14002. if (!argValue)
  14003. continue;
  14004. localVar->mResolvedType = argValue.mType;
  14005. if (argValue.mType->IsRef())
  14006. {
  14007. auto refType = (BfRefType*)localVar->mResolvedType;
  14008. localVar->mAddr = mModule->LoadValue(argValue).mValue;
  14009. localVar->mResolvedType = argValue.mType->GetUnderlyingType();
  14010. localVar->mAssignedKind = (refType->mRefKind != BfRefType::RefKind_Out) ? BfLocalVarAssignKind_Unconditional : BfLocalVarAssignKind_None;
  14011. }
  14012. else if (argValue.IsAddr())
  14013. localVar->mAddr = argValue.mValue;
  14014. else
  14015. {
  14016. if (!argValue.mValue)
  14017. {
  14018. // Untyped value
  14019. }
  14020. else if (argValue.mValue.IsConst())
  14021. {
  14022. localVar->mConstValue = argValue.mValue;
  14023. }
  14024. else if (argValue.IsSplat())
  14025. {
  14026. localVar->mValue = argValue.mValue;
  14027. localVar->mIsSplat = true;
  14028. }
  14029. else
  14030. {
  14031. if (argValue.IsAddr())
  14032. localVar->mAddr = argValue.mValue;
  14033. else
  14034. localVar->mValue = argValue.mValue;
  14035. }
  14036. localVar->mIsReadOnly = argValue.IsReadOnly();
  14037. }
  14038. if (argValue.IsReadOnly())
  14039. localVar->mIsReadOnly = true;
  14040. if (argIdx == -1)
  14041. {
  14042. _AddLocalVariable(localVar, NULL);
  14043. }
  14044. else
  14045. {
  14046. _AddLocalVariable(localVar, exprEvaluator);
  14047. endLocalIdx++;
  14048. ++argExprEvaluatorItr;
  14049. }
  14050. }
  14051. if (auto blockBody = BfNodeDynCast<BfBlock>(methodDef->mBody))
  14052. {
  14053. mModule->VisitCodeBlock(blockBody);
  14054. if (mixinState->mResultExpr != NULL)
  14055. {
  14056. if (auto exprNode = BfNodeDynCast<BfExpression>(mixinState->mResultExpr))
  14057. {
  14058. if (!exprNode->IsA<BfBlock>())
  14059. {
  14060. // Mixin expression result
  14061. mModule->UpdateSrcPos(exprNode);
  14062. VisitChild(exprNode);
  14063. FinishExpressionResult();
  14064. ResolveGenericType();
  14065. }
  14066. }
  14067. }
  14068. GetResult();
  14069. }
  14070. else if (auto expr = BfNodeDynCast<BfExpression>(methodDef->mBody))
  14071. {
  14072. mModule->UpdateSrcPos(expr);
  14073. mResult = mModule->CreateValueFromExpression(expr);
  14074. }
  14075. if (!mResult)
  14076. {
  14077. // If we didn't have an expression body then just make the result "void"
  14078. mResult = BfTypedValue(BfIRValue(), mModule->GetPrimitiveType(BfTypeCode_None));
  14079. }
  14080. int localIdx = startLocalIdx;
  14081. argExprEvaluatorItr = argExprEvaluators.begin();
  14082. for (; localIdx < endLocalIdx; localIdx++)
  14083. {
  14084. auto exprEvaluator = *argExprEvaluatorItr;
  14085. BfLocalVariable* localVar = curMethodState->mLocals[localIdx];
  14086. //TODO: Merge unassigned flags together
  14087. if ((exprEvaluator != NULL) && (exprEvaluator->mResultLocalVar != NULL))
  14088. {
  14089. auto inLocalVar = exprEvaluator->mResultLocalVar;
  14090. if (localVar->mAssignedKind != BfLocalVarAssignKind_None)
  14091. inLocalVar->mAssignedKind = BfLocalVarAssignKind_Unconditional;
  14092. if (localVar->mReadFromId != -1)
  14093. inLocalVar->mReadFromId = mModule->mCurMethodState->GetRootMethodState()->mCurAccessId++;
  14094. }
  14095. ++argExprEvaluatorItr;
  14096. }
  14097. if (auto blockBody = BfNodeDynCast<BfBlock>(methodDef->mBody))
  14098. {
  14099. if (blockBody->mCloseBrace != NULL)
  14100. mModule->UpdateSrcPos(blockBody->mCloseBrace);
  14101. }
  14102. else if (auto methodDeclaration = BfNodeDynCast<BfMethodDeclaration>(methodDef->mMethodDeclaration))
  14103. {
  14104. if (methodDeclaration->mFatArrowToken != NULL)
  14105. mModule->UpdateSrcPos(methodDeclaration->mFatArrowToken);
  14106. }
  14107. mModule->RestoreScopeState();
  14108. prevMixinState.Restore();
  14109. if ((scopedInvocationTarget != NULL) && (scopedInvocationTarget->mScopeName != NULL) && (!mixinState->mUsedInvocationScope))
  14110. {
  14111. mModule->Warn(0, "Scope specifier was not referenced in mixin", scopedInvocationTarget->mScopeName);
  14112. }
  14113. if (mixinState->mHasDeferredUsage)
  14114. {
  14115. // if (target)
  14116. // {
  14117. // if (target.mType->IsValuelessType())
  14118. // mixinState->mTarget = target;
  14119. // else
  14120. // {
  14121. // target = mModule->LoadValue(target);
  14122. // auto savedTarget = BfTypedValue(mModule->CreateAlloca(target.mType, false), target.mType, true);
  14123. // mModule->mBfIRBuilder->CreateStore(target.mValue, savedTarget.mValue);
  14124. // mixinState->mTarget = savedTarget;
  14125. // }
  14126. // }
  14127. mixinState->mTarget = BfTypedValue();
  14128. }
  14129. else
  14130. {
  14131. BF_ASSERT(rootMethodState->mMixinStates.back() == mixinState);
  14132. rootMethodState->mMixinStates.pop_back();
  14133. delete mixinState;
  14134. }
  14135. mModule->mBfIRBuilder->RestoreDebugLocation();
  14136. mModule->mBfIRBuilder->DupDebugLocation();
  14137. }
  14138. void BfExprEvaluator::SetMethodElementType(BfAstNode* target)
  14139. {
  14140. if (auto delegateBindExpr = BfNodeDynCast<BfDelegateBindExpression>(target))
  14141. {
  14142. SetMethodElementType(delegateBindExpr->mTarget);
  14143. return;
  14144. }
  14145. if (auto lambdaBindExpr = BfNodeDynCast<BfLambdaBindExpression>(target))
  14146. {
  14147. return;
  14148. }
  14149. if (auto attributedIdentifierNode = BfNodeDynCast<BfAttributedIdentifierNode>(target))
  14150. {
  14151. if (attributedIdentifierNode->mIdentifier != NULL)
  14152. mModule->SetElementType(attributedIdentifierNode->mIdentifier, BfSourceElementType_Method);
  14153. }
  14154. else if (auto memberReferenceExpr = BfNodeDynCast<BfMemberReferenceExpression>(target))
  14155. {
  14156. if (memberReferenceExpr->mMemberName != NULL)
  14157. SetMethodElementType(memberReferenceExpr->mMemberName);
  14158. }
  14159. else if (auto qualifiedNameNode = BfNodeDynCast<BfQualifiedNameNode>(target))
  14160. SetMethodElementType(qualifiedNameNode->mRight);
  14161. else
  14162. mModule->SetElementType(target, BfSourceElementType_Method);
  14163. }
  14164. void BfExprEvaluator::DoInvocation(BfAstNode* target, BfMethodBoundExpression* methodBoundExpr, const BfSizedArray<BfExpression*>& args, BfSizedArray<ASTREF(BfTypeReference*)>* methodGenericArguments, BfTypedValue* outCascadeValue)
  14165. {
  14166. // Just a check
  14167. mModule->mBfIRBuilder->GetInsertBlock();
  14168. bool wasCapturingMethodInfo = false;
  14169. auto autoComplete = GetAutoComplete();
  14170. if ((autoComplete != NULL) && (methodGenericArguments != NULL))
  14171. {
  14172. for (BfTypeReference* methodGenericArg : *methodGenericArguments)
  14173. autoComplete->CheckTypeRef(methodGenericArg, false, true);
  14174. }
  14175. if ((autoComplete != NULL) && (autoComplete->mIsCapturingMethodMatchInfo))
  14176. {
  14177. // We don't want to capture a call within the target node
  14178. wasCapturingMethodInfo = true;
  14179. autoComplete->mIsCapturingMethodMatchInfo = false;
  14180. }
  14181. bool allowImplicitThis = false;
  14182. BfAstNode* methodNodeSrc = target;
  14183. BfAttributeState attributeState;
  14184. attributeState.mTarget = (BfAttributeTargets)(BfAttributeTargets_Invocation | BfAttributeTargets_MemberAccess);
  14185. if (auto scopedTarget = BfNodeDynCast<BfScopedInvocationTarget>(target))
  14186. {
  14187. target = scopedTarget->mTarget;
  14188. if (autoComplete != NULL)
  14189. {
  14190. if (auto identifier = BfNodeDynCast<BfIdentifierNode>(scopedTarget->mScopeName))
  14191. autoComplete->CheckLabel(identifier, scopedTarget->mColonToken, NULL);
  14192. }
  14193. //mModule->FindScope(scopedTarget->mScopeName);
  14194. }
  14195. bool isCascade = false;
  14196. BfAstNode* cascadeOperatorToken = NULL;
  14197. bool bypassVirtual = false;
  14198. bool gaveUnqualifiedDotError = false;
  14199. String targetFunctionName;
  14200. BfTypedValue thisValue;
  14201. //TODO: This may just be a fully qualified static method name, so let's check that also
  14202. if (auto memberRefExpression = BfNodeDynCast<BfMemberReferenceExpression>(target))
  14203. {
  14204. if (autoComplete != NULL)
  14205. {
  14206. if (memberRefExpression->mTarget != NULL)
  14207. autoComplete->CheckMemberReference(memberRefExpression->mTarget, memberRefExpression->mDotToken, memberRefExpression->mMemberName, false, mExpectingType);
  14208. else if (mExpectingType != NULL)
  14209. {
  14210. String filter;
  14211. if ((autoComplete != NULL) && (autoComplete->InitAutocomplete(memberRefExpression->mDotToken, memberRefExpression->mMemberName, filter)))
  14212. {
  14213. auto typeInst = mExpectingType->ToTypeInstance();
  14214. if (typeInst != NULL)
  14215. {
  14216. String filter;
  14217. if ((memberRefExpression->mMemberName != NULL) && (autoComplete->IsAutocompleteNode(memberRefExpression->mMemberName)))
  14218. filter = autoComplete->GetFilter(memberRefExpression->mMemberName);
  14219. bool allowPrivate = typeInst == mModule->mCurTypeInstance;
  14220. autoComplete->AddEnumTypeMembers(typeInst, filter, false, allowPrivate);
  14221. autoComplete->AddSelfResultTypeMembers(typeInst, typeInst, filter, allowPrivate);
  14222. }
  14223. }
  14224. }
  14225. }
  14226. if ((memberRefExpression->mTarget == NULL) && (memberRefExpression->mMemberName == NULL))
  14227. {
  14228. auto expectingType = mExpectingType;
  14229. if ((expectingType != NULL) && (expectingType->IsNullable()))
  14230. {
  14231. auto underlyingType = expectingType->GetUnderlyingType();
  14232. expectingType = underlyingType;
  14233. }
  14234. if (expectingType != NULL)
  14235. {
  14236. if (expectingType->IsSizedArray())
  14237. {
  14238. if (mModule->mParentNodeEntry != NULL)
  14239. {
  14240. if (auto invocationExpr = BfNodeDynCast<BfInvocationExpression>(mModule->mParentNodeEntry->mNode))
  14241. {
  14242. InitializedSizedArray((BfSizedArrayType*)expectingType, invocationExpr->mOpenParen, invocationExpr->mArguments, invocationExpr->mCommas, invocationExpr->mCloseParen);
  14243. return;
  14244. }
  14245. }
  14246. }
  14247. else if (expectingType->IsStruct())
  14248. {
  14249. if ((wasCapturingMethodInfo) && (autoComplete->mMethodMatchInfo != NULL))
  14250. {
  14251. autoComplete->mIsCapturingMethodMatchInfo = true;
  14252. BF_ASSERT(autoComplete->mMethodMatchInfo != NULL);
  14253. }
  14254. if (mModule->mParentNodeEntry != NULL)
  14255. {
  14256. if (auto invocationExpr = BfNodeDynCast<BfInvocationExpression>(mModule->mParentNodeEntry->mNode))
  14257. {
  14258. BfResolvedArgs argValues(invocationExpr->mOpenParen, &invocationExpr->mArguments, &invocationExpr->mCommas, invocationExpr->mCloseParen);
  14259. BfResolveArgsFlags resolveArgsFlags = BfResolveArgsFlag_DeferParamEval;
  14260. ResolveArgValues(argValues, resolveArgsFlags);
  14261. if ((mReceivingValue != NULL) && (mReceivingValue->mType == expectingType) && (mReceivingValue->IsAddr()))
  14262. {
  14263. mResult = *mReceivingValue;
  14264. mReceivingValue = NULL;
  14265. }
  14266. else
  14267. mResult = BfTypedValue(mModule->CreateAlloca(expectingType), expectingType, BfTypedValueKind_TempAddr);
  14268. auto ctorResult = MatchConstructor(target, methodBoundExpr, mResult, expectingType->ToTypeInstance(), argValues, false, false);
  14269. if ((ctorResult) && (!ctorResult.mType->IsVoid()))
  14270. mResult = ctorResult;
  14271. mModule->ValidateAllocation(expectingType, invocationExpr->mTarget);
  14272. return;
  14273. }
  14274. }
  14275. }
  14276. else if (expectingType->IsGenericParam())
  14277. {
  14278. if (mModule->mParentNodeEntry != NULL)
  14279. {
  14280. if (auto invocationExpr = BfNodeDynCast<BfInvocationExpression>(mModule->mParentNodeEntry->mNode))
  14281. {
  14282. BfResolvedArgs argValues(invocationExpr->mOpenParen, &invocationExpr->mArguments, &invocationExpr->mCommas, invocationExpr->mCloseParen);
  14283. BfResolveArgsFlags resolveArgsFlags = BfResolveArgsFlag_None;
  14284. ResolveArgValues(argValues, resolveArgsFlags);
  14285. CheckGenericCtor((BfGenericParamType*)expectingType, argValues, invocationExpr->mTarget);
  14286. mResult = mModule->GetDefaultTypedValue(expectingType);
  14287. return;
  14288. }
  14289. }
  14290. }
  14291. else if (expectingType->IsVar())
  14292. {
  14293. // Silently allow
  14294. gaveUnqualifiedDotError = true;
  14295. }
  14296. else if (expectingType->IsPrimitiveType())
  14297. {
  14298. // Allow
  14299. }
  14300. else
  14301. {
  14302. gaveUnqualifiedDotError = true;
  14303. if (mModule->PreFail())
  14304. mModule->Fail(StrFormat("Cannot use inferred constructor on type '%s'", mModule->TypeToString(expectingType).c_str()), memberRefExpression->mDotToken);
  14305. }
  14306. }
  14307. }
  14308. if (memberRefExpression->IsA<BfBaseExpression>())
  14309. bypassVirtual = true;
  14310. if (memberRefExpression->mMemberName != NULL)
  14311. methodNodeSrc = memberRefExpression->mMemberName;
  14312. if (auto attrIdentifier = BfNodeDynCast<BfAttributedIdentifierNode>(memberRefExpression->mMemberName))
  14313. {
  14314. if (attrIdentifier->mIdentifier != NULL)
  14315. methodNodeSrc = attrIdentifier->mIdentifier;
  14316. attributeState.mSrc = attrIdentifier->mAttributes;
  14317. attributeState.mCustomAttributes = mModule->GetCustomAttributes(attrIdentifier->mAttributes, attributeState.mTarget);
  14318. if (attrIdentifier->mIdentifier != NULL)
  14319. targetFunctionName = attrIdentifier->mIdentifier->ToString();
  14320. }
  14321. else if (memberRefExpression->mMemberName != NULL)
  14322. targetFunctionName = memberRefExpression->mMemberName->ToString();
  14323. if (memberRefExpression->mTarget == NULL)
  14324. {
  14325. if (mExpectingType)
  14326. {
  14327. if (mExpectingType->IsVar())
  14328. {
  14329. }
  14330. mResult = BfTypedValue(mExpectingType);
  14331. }
  14332. else if (!gaveUnqualifiedDotError)
  14333. mModule->Fail("Unqualified dot syntax can only be used when the result type can be inferred", memberRefExpression->mDotToken);
  14334. }
  14335. else if (auto typeRef = BfNodeDynCast<BfTypeReference>(memberRefExpression->mTarget))
  14336. {
  14337. // Static method
  14338. mResult = BfTypedValue(ResolveTypeRef(typeRef));
  14339. }
  14340. if (auto leftIdentifier = BfNodeDynCast<BfIdentifierNode>(memberRefExpression->mTarget))
  14341. {
  14342. bool hadError = false;
  14343. thisValue = LookupIdentifier(leftIdentifier, true, &hadError);
  14344. CheckResultForReading(thisValue);
  14345. if (mPropDef != NULL)
  14346. thisValue = GetResult(true);
  14347. if (hadError)
  14348. {
  14349. mModule->AssertErrorState();
  14350. thisValue = mModule->GetDefaultTypedValue(mModule->mContext->mBfObjectType);
  14351. }
  14352. if ((!thisValue) && (mPropDef == NULL))
  14353. {
  14354. // Identifier not found. Static method? Just check speculatively don't throw error
  14355. BfType* type;
  14356. {
  14357. SetAndRestoreValue<bool> prevIgnoreErrors(mModule->mIgnoreErrors, true);
  14358. type = mModule->ResolveTypeRef(leftIdentifier, NULL, BfPopulateType_DataAndMethods, BfResolveTypeRefFlag_NoResolveGenericParam);
  14359. }
  14360. if (type != NULL)
  14361. thisValue = BfTypedValue(type);
  14362. else if (auto qualifiedLeft = BfNodeDynCast<BfQualifiedNameNode>(leftIdentifier))
  14363. {
  14364. LookupQualifiedStaticField(qualifiedLeft, true);
  14365. thisValue = mResult;
  14366. mResult = BfTypedValue();
  14367. }
  14368. }
  14369. if (mPropDef != NULL)
  14370. thisValue = GetResult(true);
  14371. if (!thisValue.mType)
  14372. {
  14373. mModule->Fail("Identifier not found", leftIdentifier);
  14374. mModule->CheckTypeRefFixit(leftIdentifier);
  14375. thisValue = mModule->GetDefaultTypedValue(mModule->mContext->mBfObjectType);
  14376. }
  14377. if (mResult)
  14378. CheckResultForReading(mResult);
  14379. mResult = thisValue;
  14380. }
  14381. else if (auto expr = BfNodeDynCast<BfExpression>(memberRefExpression->mTarget))
  14382. {
  14383. BfType* expectingTargetType = NULL;
  14384. if (memberRefExpression->mDotToken->mToken == BfToken_DotDot)
  14385. expectingTargetType = mExpectingType;
  14386. bool handled = false;
  14387. if (auto subMemberRefExpr = BfNodeDynCast<BfMemberReferenceExpression>(expr))
  14388. {
  14389. String findName;
  14390. if (subMemberRefExpr->mMemberName != NULL)
  14391. findName = subMemberRefExpr->mMemberName->ToString();
  14392. if (findName == "base") // Generic IFace<T>.base
  14393. {
  14394. thisValue = mModule->GetThis();
  14395. if (thisValue)
  14396. {
  14397. VisitChild(subMemberRefExpr->mTarget);
  14398. if (mResult.HasType())
  14399. {
  14400. if (mResult.mValue)
  14401. {
  14402. mModule->Fail("Type name expected", subMemberRefExpr->mTarget);
  14403. }
  14404. else
  14405. {
  14406. auto type = mResult.mType;
  14407. if (type != NULL)
  14408. {
  14409. if ((thisValue.mType == type) || (!mModule->TypeIsSubTypeOf(thisValue.mType->ToTypeInstance(), type->ToTypeInstance())))
  14410. {
  14411. mModule->Fail(StrFormat("Type '%s' is not a base type of '%s'",
  14412. mModule->TypeToString(type).c_str(),
  14413. mModule->TypeToString(thisValue.mType).c_str()), subMemberRefExpr->mTarget);
  14414. }
  14415. else
  14416. {
  14417. if (type->IsInterface())
  14418. {
  14419. thisValue.mType = type;
  14420. }
  14421. else
  14422. {
  14423. auto castedThis = mModule->Cast(subMemberRefExpr->mMemberName, thisValue, type, BfCastFlags_Explicit);
  14424. if (castedThis)
  14425. thisValue = castedThis;
  14426. //mModule->Fail("Explicit base types can only be used for specifying default interface members", qualifiedLeft->mLeft);
  14427. }
  14428. }
  14429. handled = true;
  14430. }
  14431. bypassVirtual = true;
  14432. }
  14433. }
  14434. }
  14435. }
  14436. }
  14437. if (!handled)
  14438. {
  14439. SetAndRestoreValue<BfAttributeState*> prevAttributeState(mModule->mAttributeState, &attributeState);
  14440. auto flags = (BfEvalExprFlags)(BfEvalExprFlags_PropogateNullConditional | BfEvalExprFlags_NoCast);
  14441. if (mFunctionBindResult != NULL)
  14442. {
  14443. if (auto paranExpr = BfNodeDynCast<BfParenthesizedExpression>(expr))
  14444. {
  14445. // Allow 'ref' on binding, to indicate we want to capture 'this' by reference
  14446. flags = (BfEvalExprFlags)(flags | BfEvalExprFlags_AllowRefExpr);
  14447. expr = paranExpr->mExpression;
  14448. }
  14449. }
  14450. if (expr != NULL)
  14451. mResult = mModule->CreateValueFromExpression(expr, expectingTargetType, flags);
  14452. }
  14453. }
  14454. isCascade = (memberRefExpression->mDotToken != NULL) && (memberRefExpression->mDotToken->GetToken() == BfToken_DotDot);
  14455. if (isCascade)
  14456. cascadeOperatorToken = memberRefExpression->mDotToken;
  14457. bool isNullCondLookup = (memberRefExpression->mDotToken != NULL) && (memberRefExpression->mDotToken->GetToken() == BfToken_QuestionDot);
  14458. if (isNullCondLookup)
  14459. mResult = SetupNullConditional(mResult, memberRefExpression->mDotToken);
  14460. if ((mResult.mType == NULL) && (memberRefExpression->mTarget != NULL))
  14461. {
  14462. mModule->AssertErrorState();
  14463. mResult = mModule->GetDefaultTypedValue(mModule->mContext->mBfObjectType);
  14464. }
  14465. thisValue = mResult;
  14466. mResult = BfTypedValue();
  14467. }
  14468. else if (auto qualifiedName = BfNodeDynCast<BfQualifiedNameNode>(target))
  14469. {
  14470. if (GetAutoComplete() != NULL)
  14471. GetAutoComplete()->CheckMemberReference(qualifiedName->mLeft, qualifiedName->mDot, qualifiedName->mRight);
  14472. if (qualifiedName->mLeft->GetSrcLength() == 4)
  14473. {
  14474. if (CheckIsBase(qualifiedName->mLeft))
  14475. bypassVirtual = true;
  14476. }
  14477. if (qualifiedName->mRight != NULL)
  14478. methodNodeSrc = qualifiedName->mRight;
  14479. if (auto attrIdentifier = BfNodeDynCast<BfAttributedIdentifierNode>(qualifiedName->mRight))
  14480. {
  14481. if (attrIdentifier->mIdentifier != NULL)
  14482. methodNodeSrc = attrIdentifier->mIdentifier;
  14483. attributeState.mSrc = attrIdentifier->mAttributes;
  14484. attributeState.mCustomAttributes = mModule->GetCustomAttributes(attrIdentifier->mAttributes, attributeState.mTarget);
  14485. targetFunctionName = attrIdentifier->mIdentifier->ToString();
  14486. }
  14487. else
  14488. targetFunctionName = qualifiedName->mRight->ToString();
  14489. bool hadError = false;
  14490. thisValue = LookupIdentifier(qualifiedName->mLeft, true, &hadError);
  14491. CheckResultForReading(thisValue);
  14492. if (mPropDef != NULL)
  14493. thisValue = GetResult(true);
  14494. if (hadError)
  14495. {
  14496. mModule->AssertErrorState();
  14497. thisValue = mModule->GetDefaultTypedValue(mModule->mContext->mBfObjectType);
  14498. }
  14499. if ((!thisValue) && (mPropDef == NULL))
  14500. {
  14501. // Identifier not found. Static method? Just check speculatively don't throw error
  14502. BfType* type;
  14503. {
  14504. //SetAndRestoreValue<bool> prevIgnoreErrors(mModule->mIgnoreErrors, true);
  14505. type = mModule->ResolveTypeRef(qualifiedName->mLeft, NULL, BfPopulateType_DataAndMethods, (BfResolveTypeRefFlags)(BfResolveTypeRefFlag_NoResolveGenericParam | BfResolveTypeRefFlag_AllowGlobalContainer | BfResolveTypeRefFlag_IgnoreLookupError));
  14506. }
  14507. if (type == NULL)
  14508. {
  14509. //SetAndRestoreValue<bool> prevIgnoreErrors(mModule->mIgnoreErrors, true);
  14510. type = mModule->ResolveTypeRef(qualifiedName, methodGenericArguments, BfPopulateType_DataAndMethods, (BfResolveTypeRefFlags)(BfResolveTypeRefFlag_NoResolveGenericParam | BfResolveTypeRefFlag_AllowGlobalContainer | BfResolveTypeRefFlag_IgnoreLookupError));
  14511. if (type != NULL)
  14512. {
  14513. // This is a CTOR call, treat it as such
  14514. targetFunctionName.clear();
  14515. }
  14516. }
  14517. if (type != NULL)
  14518. thisValue = BfTypedValue(type);
  14519. else if (auto qualifiedLeft = BfNodeDynCast<BfQualifiedNameNode>(qualifiedName->mLeft))
  14520. {
  14521. String findName = qualifiedLeft->mRight->ToString();
  14522. bool handled = false;
  14523. if (findName == "base")
  14524. {
  14525. auto type = mModule->ResolveTypeRef(qualifiedLeft->mLeft, NULL, BfPopulateType_Data, BfResolveTypeRefFlag_AllowRef);
  14526. mModule->CheckTypeRefFixit(qualifiedLeft->mLeft);
  14527. thisValue = mModule->GetThis();
  14528. if (type != NULL)
  14529. {
  14530. if ((thisValue.mType == type) || (!mModule->TypeIsSubTypeOf(thisValue.mType->ToTypeInstance(), type->ToTypeInstance())))
  14531. {
  14532. mModule->Fail(StrFormat("Type '%s' is not a base type of '%s'",
  14533. mModule->TypeToString(type).c_str(),
  14534. mModule->TypeToString(thisValue.mType).c_str()), qualifiedLeft->mLeft);
  14535. }
  14536. else
  14537. {
  14538. if (type->IsInterface())
  14539. {
  14540. thisValue.mType = type;
  14541. }
  14542. else
  14543. {
  14544. auto castedThis = mModule->Cast(qualifiedLeft->mRight, thisValue, type, BfCastFlags_Explicit);
  14545. if (castedThis)
  14546. thisValue = castedThis;
  14547. //mModule->Fail("Explicit base types can only be used for specifying default interface members", qualifiedLeft->mLeft);
  14548. }
  14549. }
  14550. handled = true;
  14551. }
  14552. bypassVirtual = true;
  14553. }
  14554. if (!handled)
  14555. {
  14556. LookupQualifiedStaticField(qualifiedLeft, true);
  14557. thisValue = mResult;
  14558. mResult = BfTypedValue();
  14559. }
  14560. }
  14561. }
  14562. if (mPropDef != NULL)
  14563. thisValue = GetResult(true);
  14564. if (!thisValue.mType)
  14565. {
  14566. mModule->Fail("Identifier not found", qualifiedName->mLeft);
  14567. mModule->CheckTypeRefFixit(qualifiedName->mLeft);
  14568. mModule->CheckIdentifierFixit(qualifiedName->mLeft);
  14569. thisValue = mModule->GetDefaultTypedValue(mModule->GetPrimitiveType(BfTypeCode_Var));
  14570. }
  14571. if (mResult)
  14572. CheckResultForReading(mResult);
  14573. mResult = BfTypedValue();
  14574. }
  14575. else if (auto identiferExpr = BfNodeDynCast<BfIdentifierNode>(target))
  14576. {
  14577. if (auto attrIdentifier = BfNodeDynCast<BfAttributedIdentifierNode>(target))
  14578. {
  14579. if (attrIdentifier->mIdentifier != NULL)
  14580. methodNodeSrc = attrIdentifier->mIdentifier;
  14581. attributeState.mSrc = attrIdentifier->mAttributes;
  14582. attributeState.mCustomAttributes = mModule->GetCustomAttributes(attrIdentifier->mAttributes, attributeState.mTarget);
  14583. }
  14584. allowImplicitThis = true;
  14585. if (autoComplete != NULL)
  14586. autoComplete->CheckIdentifier(identiferExpr);
  14587. targetFunctionName = target->ToString();
  14588. if (targetFunctionName == "PrintF") // Just directly call that one
  14589. {
  14590. BfType* charType = mModule->GetPrimitiveType(BfTypeCode_Char8);
  14591. BfType* charPtrType = mModule->CreatePointerType(charType);
  14592. auto func = mModule->GetBuiltInFunc(BfBuiltInFuncType_PrintF);
  14593. SizedArray<BfIRValue, 4> irArgs;
  14594. for (BfExpression* arg : args)
  14595. {
  14596. BfTypedValue value;
  14597. if (arg != NULL)
  14598. value = mModule->CreateValueFromExpression(arg);
  14599. if (!value)
  14600. return;
  14601. auto typeInst = value.mType->ToTypeInstance();
  14602. if ((typeInst != NULL) && (typeInst->IsInstanceOf(mModule->mCompiler->mStringTypeDef)))
  14603. value = mModule->Cast(arg, value, charPtrType);
  14604. if ((value.mType->IsFloat()) && (value.mType->mSize != 8)) // Always cast float to double
  14605. value = mModule->Cast(arg, value, mModule->GetPrimitiveType(BfTypeCode_Double));
  14606. irArgs.push_back(value.mValue);
  14607. }
  14608. if ((targetFunctionName != "PrintF") || (irArgs.size() > 0))
  14609. {
  14610. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateCall(func, irArgs/*, targetFunctionName*/),
  14611. mModule->ResolveTypeDef(mModule->mSystem->mTypeInt32));
  14612. }
  14613. return;
  14614. }
  14615. }
  14616. else if (auto expr = BfNodeDynCast<BfExpression>(target))
  14617. {
  14618. auto innerInvocationResult = mModule->CreateValueFromExpression(expr);
  14619. if (!innerInvocationResult)
  14620. {
  14621. mModule->AssertErrorState();
  14622. innerInvocationResult = mModule->GetDefaultTypedValue(mModule->mContext->mBfObjectType);
  14623. }
  14624. if (innerInvocationResult.mType->IsVar())
  14625. {
  14626. mResult = innerInvocationResult;
  14627. return;
  14628. }
  14629. targetFunctionName = "Invoke";
  14630. if (innerInvocationResult.mType->IsTypeInstance())
  14631. {
  14632. auto invocationTypeInst = innerInvocationResult.mType->ToTypeInstance();
  14633. if (invocationTypeInst->mTypeDef->mIsDelegate)
  14634. {
  14635. thisValue = innerInvocationResult;
  14636. }
  14637. }
  14638. if (!thisValue)
  14639. {
  14640. mModule->Fail(StrFormat("Cannot perform invocation on type '%s'", mModule->TypeToString(innerInvocationResult.mType).c_str()), expr);
  14641. thisValue = mModule->GetDefaultTypedValue(mModule->mContext->mBfObjectType);
  14642. }
  14643. }
  14644. else
  14645. {
  14646. mModule->Fail("Invalid invocation target", target);
  14647. thisValue = mModule->GetDefaultTypedValue(mModule->mContext->mBfObjectType);
  14648. }
  14649. if ((wasCapturingMethodInfo) && (autoComplete->mMethodMatchInfo != NULL))
  14650. {
  14651. autoComplete->mIsCapturingMethodMatchInfo = true;
  14652. BF_ASSERT(autoComplete->mMethodMatchInfo != NULL);
  14653. }
  14654. SetAndRestoreValue<BfAttributeState*> prevAttributeState;
  14655. if (attributeState.mCustomAttributes != NULL)
  14656. prevAttributeState.Init(mModule->mAttributeState, &attributeState);
  14657. if ((targetFunctionName != "") && (targetFunctionName[targetFunctionName.length() - 1] == '!'))
  14658. {
  14659. targetFunctionName = targetFunctionName.Substring(0, targetFunctionName.length() - 1);
  14660. InjectMixin(methodNodeSrc, thisValue, allowImplicitThis, targetFunctionName, args, methodGenericArguments);
  14661. return;
  14662. }
  14663. //TODO: We removed this... Messed up with PrimStruct 'this' non-mut errors
  14664. // 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
  14665. /*if (thisValue)
  14666. {
  14667. if ((!thisValue.mType->IsGenericParam()) && (!thisValue.IsSplat()) && (!thisValue.mType->IsVar()))
  14668. thisValue = MakeCallableTarget(target, thisValue);
  14669. }*/
  14670. int methodCount = 0;
  14671. bool mayBeSkipCall = false;
  14672. bool mayBeComptimeCall = false;
  14673. if (thisValue.mType != NULL)
  14674. {
  14675. if (thisValue.mType->IsAllocType())
  14676. thisValue.mType = thisValue.mType->GetUnderlyingType();
  14677. auto checkTypeInst = thisValue.mType->ToTypeInstance();
  14678. while (checkTypeInst != NULL)
  14679. {
  14680. checkTypeInst->mTypeDef->PopulateMemberSets();
  14681. BfMemberSetEntry* memberSetEntry;
  14682. if (checkTypeInst->mTypeDef->mMethodSet.TryGetWith(targetFunctionName, &memberSetEntry))
  14683. {
  14684. BfMethodDef* methodDef = (BfMethodDef*)memberSetEntry->mMemberDef;
  14685. while (methodDef != NULL)
  14686. {
  14687. if (methodDef->mIsSkipCall)
  14688. mayBeSkipCall = true;
  14689. if (methodDef->mHasComptime)
  14690. mayBeComptimeCall = true;
  14691. methodDef = methodDef->mNextWithSameName;
  14692. }
  14693. }
  14694. checkTypeInst = checkTypeInst->mBaseType;
  14695. }
  14696. }
  14697. SizedArray<BfExpression*, 8> copiedArgs;
  14698. for (BfExpression* arg : args)
  14699. copiedArgs.push_back(arg);
  14700. BfSizedArray<BfExpression*> sizedCopiedArgs(copiedArgs);
  14701. BfResolvedArgs argValues(&sizedCopiedArgs);
  14702. if (mModule->mParentNodeEntry != NULL)
  14703. {
  14704. if (auto invocationExpr = BfNodeDynCast<BfInvocationExpression>(mModule->mParentNodeEntry->mNode))
  14705. {
  14706. argValues.mOpenToken = invocationExpr->mOpenParen;
  14707. argValues.mCommas = &invocationExpr->mCommas;
  14708. argValues.mCloseToken = invocationExpr->mCloseParen;
  14709. }
  14710. }
  14711. BfResolveArgsFlags resolveArgsFlags = (BfResolveArgsFlags)(BfResolveArgsFlag_DeferFixits | BfResolveArgsFlag_AllowUnresolvedTypes);
  14712. resolveArgsFlags = (BfResolveArgsFlags)(resolveArgsFlags | BfResolveArgsFlag_DeferParamEval);
  14713. if ((mayBeSkipCall) || (mayBeComptimeCall))
  14714. resolveArgsFlags = (BfResolveArgsFlags)(resolveArgsFlags | BfResolveArgsFlag_DeferParamValues);
  14715. static int sCallIdx = 0;
  14716. sCallIdx++;
  14717. int callIdx = sCallIdx;
  14718. if (callIdx == 1557)
  14719. {
  14720. NOP;
  14721. }
  14722. BfCheckedKind checkedKind = BfCheckedKind_NotSet;
  14723. if ((mModule->mAttributeState != NULL) && (mModule->mAttributeState->mCustomAttributes != NULL))
  14724. {
  14725. if (mModule->mAttributeState->mCustomAttributes->Contains(mModule->mCompiler->mCheckedAttributeTypeDef))
  14726. {
  14727. checkedKind = BfCheckedKind_Checked;
  14728. mModule->mAttributeState->mUsed = true;
  14729. }
  14730. if (mModule->mAttributeState->mCustomAttributes->Contains(mModule->mCompiler->mUncheckedAttributeTypeDef))
  14731. {
  14732. checkedKind = BfCheckedKind_Unchecked;
  14733. mModule->mAttributeState->mUsed = true;
  14734. }
  14735. }
  14736. if ((isCascade) && (cascadeOperatorToken != NULL) && ((mBfEvalExprFlags & BfEvalExprFlags_Comptime) != 0))
  14737. mModule->Fail("Cascade operator cannot be used in const evaluation", cascadeOperatorToken);
  14738. SetAndRestoreValue<bool> prevUsedAsStatement(mUsedAsStatement, mUsedAsStatement || isCascade);
  14739. SetAndRestoreValue<BfEvalExprFlags> prevEvalExprFlags(mBfEvalExprFlags);
  14740. if (isCascade)
  14741. mBfEvalExprFlags = (BfEvalExprFlags)(mBfEvalExprFlags | BfEvalExprFlags_InCascade);
  14742. ResolveArgValues(argValues, resolveArgsFlags);
  14743. mResult = MatchMethod(methodNodeSrc, methodBoundExpr, thisValue, allowImplicitThis, bypassVirtual, targetFunctionName, argValues, methodGenericArguments, checkedKind);
  14744. argValues.HandleFixits(mModule);
  14745. if (mModule->mAttributeState == &attributeState)
  14746. mModule->FinishAttributeState(&attributeState);
  14747. if (isCascade)
  14748. {
  14749. if ((outCascadeValue != NULL) && (thisValue.mValue))
  14750. {
  14751. *outCascadeValue = thisValue;
  14752. }
  14753. else
  14754. {
  14755. mModule->Fail("Invalid use of cascade operator", cascadeOperatorToken);
  14756. }
  14757. }
  14758. }
  14759. void BfExprEvaluator::Visit(BfInvocationExpression* invocationExpr)
  14760. {
  14761. BfAutoParentNodeEntry autoParentNodeEntry(mModule, invocationExpr);
  14762. // We need to check for sized array constructor like "uint8[2](1, 2)"
  14763. if (BfNodeDynCastExact<BfIndexerExpression>(invocationExpr->mTarget) != NULL)
  14764. {
  14765. auto checkTarget = invocationExpr->mTarget;
  14766. while (auto indexerExpr = BfNodeDynCastExact<BfIndexerExpression>(checkTarget))
  14767. {
  14768. checkTarget = indexerExpr->mTarget;
  14769. }
  14770. SetAndRestoreValue<bool> prevIgnoreError(mModule->mIgnoreErrors, true);
  14771. auto resolvedType = mModule->ResolveTypeRef(checkTarget, NULL, BfPopulateType_Identity);
  14772. prevIgnoreError.Restore();
  14773. if (resolvedType != NULL)
  14774. {
  14775. BfType* curType = resolvedType;
  14776. auto checkTarget = invocationExpr->mTarget;
  14777. while (auto indexerExpr = BfNodeDynCastExact<BfIndexerExpression>(checkTarget))
  14778. {
  14779. checkTarget = indexerExpr->mTarget;
  14780. if (indexerExpr->mCommas.size() != 0)
  14781. 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]);
  14782. int arrSize = 0;
  14783. BfTypeState typeState;
  14784. typeState.mArrayInitializerSize = (int)invocationExpr->mArguments.size();
  14785. SetAndRestoreValue<BfTypeState*> prevTypeState(mModule->mContext->mCurTypeState, &typeState);
  14786. if (indexerExpr->mArguments.size() != 0)
  14787. {
  14788. BfConstResolver constResolver(mModule);
  14789. auto arg = indexerExpr->mArguments[0];
  14790. constResolver.mExpectingType = mModule->GetPrimitiveType(BfTypeCode_IntPtr);
  14791. if (arg != NULL)
  14792. constResolver.Resolve(arg, NULL, BfConstResolveFlag_ArrayInitSize);
  14793. if (constResolver.mResult.mValue.IsConst())
  14794. {
  14795. auto constant = mModule->mBfIRBuilder->GetConstant(constResolver.mResult.mValue);
  14796. if ((mModule->mBfIRBuilder->IsInt(constant->mTypeCode)) && (constant->mInt64 >= 0))
  14797. {
  14798. arrSize = constant->mInt32;
  14799. }
  14800. else
  14801. mModule->Fail("Non-negative integer expected", indexerExpr->mArguments[0]);
  14802. }
  14803. }
  14804. else
  14805. arrSize = invocationExpr->mArguments.size();
  14806. curType = mModule->CreateSizedArrayType(curType, arrSize);
  14807. }
  14808. InitializedSizedArray((BfSizedArrayType*)curType, invocationExpr->mOpenParen, invocationExpr->mArguments, invocationExpr->mCommas, invocationExpr->mCloseParen, NULL);
  14809. return;
  14810. }
  14811. }
  14812. auto autoComplete = GetAutoComplete();
  14813. auto wasCapturingMethodInfo = (autoComplete != NULL) && (autoComplete->mIsCapturingMethodMatchInfo);
  14814. if (autoComplete != NULL)
  14815. autoComplete->CheckInvocation(invocationExpr, invocationExpr->mOpenParen, invocationExpr->mCloseParen, invocationExpr->mCommas);
  14816. mModule->UpdateExprSrcPos(invocationExpr);
  14817. BfSizedArray<ASTREF(BfTypeReference*)>* methodGenericArguments = NULL;
  14818. if (invocationExpr->mGenericArgs != NULL)
  14819. methodGenericArguments = &invocationExpr->mGenericArgs->mGenericArgs;
  14820. SizedArray<BfExpression*, 8> copiedArgs;
  14821. for (BfExpression* arg : invocationExpr->mArguments)
  14822. copiedArgs.push_back(arg);
  14823. BfTypedValue cascadeValue;
  14824. DoInvocation(invocationExpr->mTarget, invocationExpr, copiedArgs, methodGenericArguments, &cascadeValue);
  14825. if (autoComplete != NULL)
  14826. {
  14827. if ((wasCapturingMethodInfo) && (!autoComplete->mIsCapturingMethodMatchInfo))
  14828. {
  14829. if (autoComplete->mMethodMatchInfo != NULL)
  14830. autoComplete->mIsCapturingMethodMatchInfo = true;
  14831. else
  14832. autoComplete->mIsCapturingMethodMatchInfo = false;
  14833. //BF_ASSERT(autoComplete->mMethodMatchInfo != NULL);
  14834. }
  14835. else
  14836. autoComplete->mIsCapturingMethodMatchInfo = false;
  14837. }
  14838. /// Previous check for discard
  14839. if (cascadeValue)
  14840. mResult = cascadeValue;
  14841. }
  14842. BfMethodDef* BfExprEvaluator::GetPropertyMethodDef(BfPropertyDef* propDef, BfMethodType methodType, BfCheckedKind checkedKind, BfTypedValue propTarget)
  14843. {
  14844. bool allowMut = true;
  14845. if ((propTarget) && (propTarget.mType->IsValueType()))
  14846. {
  14847. if (propTarget.IsReadOnly())
  14848. {
  14849. allowMut = false;
  14850. }
  14851. else if (!propTarget.IsAddr())
  14852. {
  14853. mModule->PopulateType(propTarget.mType);
  14854. if (!propTarget.IsValuelessType())
  14855. allowMut = false;
  14856. }
  14857. }
  14858. int bestPri = -1000;
  14859. BfMethodDef* matchedMethod = NULL;
  14860. for (auto methodDef : propDef->mMethods)
  14861. {
  14862. if (methodDef->mMethodType != methodType)
  14863. continue;
  14864. int curPri = 0;
  14865. if (methodDef->mCheckedKind == checkedKind)
  14866. {
  14867. curPri = 5;
  14868. }
  14869. else if ((checkedKind == BfCheckedKind_NotSet) && (methodDef->mCheckedKind == mModule->GetDefaultCheckedKind()))
  14870. curPri = 3;
  14871. else
  14872. curPri = 1;
  14873. if (methodDef->mIsMutating)
  14874. {
  14875. if (allowMut)
  14876. curPri++;
  14877. else
  14878. curPri -= 10;
  14879. }
  14880. if (curPri > bestPri)
  14881. {
  14882. bestPri = curPri;
  14883. matchedMethod = methodDef;
  14884. }
  14885. }
  14886. return matchedMethod;
  14887. /*BfMethodDef* matchedMethod = NULL;
  14888. BfMethodDef* backupMethod = NULL;
  14889. for (auto methodDef : propDef->mMethods)
  14890. {
  14891. if (methodDef->mMethodType != methodType)
  14892. continue;
  14893. if (methodDef->mCheckedKind == checkedKind)
  14894. {
  14895. matchedMethod = methodDef;
  14896. break;
  14897. }
  14898. if ((checkedKind == BfCheckedKind_NotSet) && (methodDef->mCheckedKind == mModule->GetDefaultCheckedKind()))
  14899. matchedMethod = methodDef;
  14900. else
  14901. backupMethod = methodDef;
  14902. }
  14903. if (matchedMethod == NULL)
  14904. matchedMethod = backupMethod;
  14905. return matchedMethod;*/
  14906. }
  14907. BfModuleMethodInstance BfExprEvaluator::GetPropertyMethodInstance(BfMethodDef* methodDef)
  14908. {
  14909. if (mPropDefBypassVirtual)
  14910. {
  14911. if (mPropTarget.mType->IsInterface())
  14912. {
  14913. auto curTypeInst = mPropTarget.mType->ToTypeInstance();
  14914. if (mModule->TypeIsSubTypeOf(mModule->mCurTypeInstance, curTypeInst))
  14915. {
  14916. if (methodDef->mBody != NULL)
  14917. {
  14918. // This is an explicit call to a default static interface method. We pull the methodDef into our own concrete type.
  14919. mPropTarget = mModule->GetThis();
  14920. return mModule->GetMethodInstance(mModule->mCurTypeInstance, methodDef, BfTypeVector(), BfGetMethodInstanceFlag_ForeignMethodDef, curTypeInst);
  14921. }
  14922. }
  14923. else
  14924. {
  14925. mModule->Fail("Property is not implemented by this type", mPropSrc);
  14926. return BfModuleMethodInstance();
  14927. }
  14928. }
  14929. else
  14930. {
  14931. auto propTypeInst = mPropTarget.mType->ToTypeInstance();
  14932. mModule->PopulateType(propTypeInst, BfPopulateType_DataAndMethods);
  14933. auto rawMethodInstance = mModule->GetRawMethodInstance(propTypeInst, methodDef);
  14934. if (rawMethodInstance->mVirtualTableIdx == -1)
  14935. {
  14936. if (!mModule->mCompiler->mIsResolveOnly)
  14937. {
  14938. // ResolveOnly does not force methods to slot
  14939. BF_ASSERT(rawMethodInstance->mVirtualTableIdx != -1);
  14940. mModule->Fail(StrFormat("Failed to devirtualize %s", mModule->MethodToString(rawMethodInstance).c_str()));
  14941. }
  14942. }
  14943. else
  14944. {
  14945. auto useTypeInst = mOrigPropTarget.mType->ToTypeInstance();
  14946. auto virtualMethod = (BfMethodInstance*)useTypeInst->mVirtualMethodTable[rawMethodInstance->mVirtualTableIdx].mImplementingMethod;
  14947. return mModule->ReferenceExternalMethodInstance(virtualMethod);
  14948. }
  14949. }
  14950. }
  14951. if ((mOrigPropTarget) && (mOrigPropTarget.mType != mPropTarget.mType) &&
  14952. ((!mOrigPropTarget.mType->IsGenericParam()) && (mPropTarget.mType->IsInterface())))
  14953. {
  14954. auto checkType = mOrigPropTarget.mType;
  14955. if (checkType->IsPointer())
  14956. checkType = ((BfPointerType*)checkType)->mElementType;
  14957. if (checkType->IsWrappableType())
  14958. checkType = mModule->GetWrappedStructType(checkType);
  14959. if ((checkType != NULL) && (checkType->IsTypeInstance()))
  14960. {
  14961. auto activeTypeDef = mModule->GetActiveTypeDef();
  14962. BfTypeInterfaceEntry* bestIFaceEntry = NULL;
  14963. bool checkedUnderlying = false;
  14964. auto checkTypeInst = checkType->ToTypeInstance();
  14965. while (checkTypeInst != NULL)
  14966. {
  14967. mModule->PopulateType(checkTypeInst, BfPopulateType_DataAndMethods);
  14968. BF_ASSERT((checkTypeInst->mDefineState >= BfTypeDefineState_DefinedAndMethodsSlotted) || (mModule->mCompiler->IsAutocomplete()));
  14969. if (checkTypeInst->mDefineState != BfTypeDefineState_DefinedAndMethodsSlotted)
  14970. break;
  14971. for (auto& iface : checkTypeInst->mInterfaces)
  14972. {
  14973. if (!mModule->IsInSpecializedSection())
  14974. {
  14975. if (!checkTypeInst->IsTypeMemberAccessible(iface.mDeclaringType, activeTypeDef))
  14976. continue;
  14977. }
  14978. if (iface.mInterfaceType == mPropTarget.mType)
  14979. {
  14980. if (bestIFaceEntry == NULL)
  14981. {
  14982. bestIFaceEntry = &iface;
  14983. continue;
  14984. }
  14985. bool isBetter;
  14986. bool isWorse;
  14987. mModule->CompareDeclTypes(iface.mDeclaringType, bestIFaceEntry->mDeclaringType, isBetter, isWorse);
  14988. if (isBetter == isWorse)
  14989. {
  14990. // Failed
  14991. }
  14992. else
  14993. {
  14994. if (isBetter)
  14995. bestIFaceEntry = &iface;
  14996. }
  14997. }
  14998. }
  14999. if (bestIFaceEntry != NULL)
  15000. break;
  15001. checkTypeInst = checkTypeInst->mBaseType;
  15002. if (checkTypeInst == NULL)
  15003. {
  15004. if (!checkedUnderlying)
  15005. {
  15006. checkedUnderlying = true;
  15007. if (checkType->HasWrappedRepresentation())
  15008. {
  15009. auto underlyingType = checkType->GetUnderlyingType();
  15010. if (underlyingType != NULL)
  15011. checkTypeInst = mModule->GetWrappedStructType(underlyingType);
  15012. }
  15013. }
  15014. }
  15015. }
  15016. if (bestIFaceEntry != NULL)
  15017. {
  15018. auto ifaceMethodEntry = checkTypeInst->mInterfaceMethodTable[bestIFaceEntry->mStartInterfaceTableIdx + methodDef->mIdx];
  15019. BfMethodInstance* bestMethodInstance = ifaceMethodEntry.mMethodRef;
  15020. if (bestMethodInstance != NULL)
  15021. {
  15022. mPropTarget = mOrigPropTarget;
  15023. //mPropTarget.mType = checkTypeInst;
  15024. //mPropTarget = mModule->Cast( mOrigPropTarget, checkTypeInst);
  15025. return mModule->GetMethodInstanceAtIdx(ifaceMethodEntry.mMethodRef.mTypeInstance, ifaceMethodEntry.mMethodRef.mMethodNum);
  15026. }
  15027. }
  15028. }
  15029. mModule->AssertErrorState();
  15030. return BfModuleMethodInstance();
  15031. }
  15032. auto propTypeInst = mPropTarget.mType->ToTypeInstance();
  15033. if (propTypeInst == NULL)
  15034. {
  15035. propTypeInst = mModule->GetWrappedStructType(mPropTarget.mType);
  15036. }
  15037. if (propTypeInst == NULL)
  15038. {
  15039. mModule->Fail("INTERNAL ERROR: Invalid property target", mPropSrc);
  15040. return BfModuleMethodInstance();
  15041. }
  15042. return mModule->GetMethodInstance(propTypeInst, methodDef, BfTypeVector(), mPropGetMethodFlags);
  15043. }
  15044. void BfExprEvaluator::CheckPropFail(BfMethodDef* propMethodDef, BfMethodInstance* methodInstance, bool checkProt)
  15045. {
  15046. auto propTypeInst = mPropTarget.mType->ToTypeInstance();
  15047. // If mExplicitInterface is null then we are implicitly calling through an interface
  15048. if ((checkProt) && (propTypeInst != NULL) && (methodInstance->GetExplicitInterface() == NULL) &&
  15049. (!mModule->CheckAccessMemberProtection(propMethodDef->mProtection, propTypeInst)))
  15050. mModule->Fail(StrFormat("'%s' is inaccessible due to its protection level", mModule->MethodToString(methodInstance).c_str()), mPropSrc);
  15051. else if (mPropCheckedKind != methodInstance->mMethodDef->mCheckedKind)
  15052. {
  15053. bool passes = true;
  15054. if (mPropCheckedKind != BfCheckedKind_NotSet)
  15055. {
  15056. passes = false;
  15057. }
  15058. else
  15059. {
  15060. auto defaultCheckedKind = mModule->GetDefaultCheckedKind();
  15061. if (defaultCheckedKind != methodInstance->mMethodDef->mCheckedKind)
  15062. passes = false;
  15063. }
  15064. if (!passes)
  15065. {
  15066. 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);
  15067. if (error != NULL)
  15068. {
  15069. if ((error != NULL) && (methodInstance->mMethodDef->mMethodDeclaration != NULL))
  15070. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("See method declaration"), methodInstance->mMethodDef->GetRefNode());
  15071. }
  15072. }
  15073. }
  15074. }
  15075. bool BfExprEvaluator::HasResult()
  15076. {
  15077. return (mResult) || (mPropDef != NULL);
  15078. }
  15079. BfTypedValue BfExprEvaluator::GetResult(bool clearResult, bool resolveGenericType)
  15080. {
  15081. if ((!mResult) && (mPropDef != NULL))
  15082. {
  15083. bool handled = false;
  15084. if (mPropTarget.mType->IsGenericTypeInstance())
  15085. {
  15086. auto genericTypeInst = (BfTypeInstance*)mPropTarget.mType;
  15087. if (genericTypeInst->IsInstanceOf(mModule->mCompiler->mSizedArrayTypeDef))
  15088. {
  15089. if (mPropDef->mName == "Count")
  15090. {
  15091. auto sizedType = genericTypeInst->mGenericTypeInfo->mTypeGenericArguments[1];
  15092. if (sizedType->IsConstExprValue())
  15093. {
  15094. auto constExprType = (BfConstExprValueType*)sizedType;
  15095. mResult = BfTypedValue(mModule->GetConstValue(constExprType->mValue.mInt64), mModule->GetPrimitiveType(BfTypeCode_IntPtr));
  15096. handled = true;
  15097. }
  15098. else
  15099. {
  15100. BF_ASSERT(mModule->mCurMethodInstance->mIsUnspecialized);
  15101. mResult = BfTypedValue(mModule->mBfIRBuilder->GetUndefConstValue(mModule->mBfIRBuilder->GetPrimitiveType(BfTypeCode_IntPtr)), mModule->GetPrimitiveType(BfTypeCode_IntPtr));
  15102. handled = true;
  15103. }
  15104. }
  15105. }
  15106. }
  15107. if (!handled)
  15108. {
  15109. SetAndRestoreValue<BfFunctionBindResult*> prevFunctionBindResult(mFunctionBindResult, NULL);
  15110. SetAndRestoreValue<BfAstNode*> prevDeferCallRef(mDeferCallRef, NULL);
  15111. BfMethodDef* matchedMethod = GetPropertyMethodDef(mPropDef, BfMethodType_PropertyGetter, mPropCheckedKind, mPropTarget);
  15112. if (matchedMethod == NULL)
  15113. {
  15114. mModule->Fail("Property has no getter", mPropSrc);
  15115. return mResult;
  15116. }
  15117. auto methodInstance = GetPropertyMethodInstance(matchedMethod);
  15118. if (methodInstance.mMethodInstance == NULL)
  15119. return mResult;
  15120. BF_ASSERT(methodInstance.mMethodInstance->mMethodDef->mName == matchedMethod->mName);
  15121. if (!mModule->mBfIRBuilder->mIgnoreWrites)
  15122. {
  15123. BF_ASSERT(!methodInstance.mFunc.IsFake());
  15124. }
  15125. if (mPropSrc != NULL)
  15126. mModule->UpdateExprSrcPos(mPropSrc);
  15127. auto autoComplete = GetAutoComplete();
  15128. if ((autoComplete != NULL) && (autoComplete->IsAutocompleteNode(mPropSrc)) && (autoComplete->mResolveType == BfResolveType_GetResultString))
  15129. {
  15130. autoComplete->mResultString = ":";
  15131. autoComplete->mResultString += mModule->TypeToString(methodInstance.mMethodInstance->mReturnType);
  15132. autoComplete->mResultString += " ";
  15133. autoComplete->mResultString += mModule->TypeToString(methodInstance.mMethodInstance->GetOwner());
  15134. autoComplete->mResultString += ".";
  15135. autoComplete->mResultString += mPropDef->mName;
  15136. }
  15137. CheckPropFail(matchedMethod, methodInstance.mMethodInstance, (mPropGetMethodFlags & BfGetMethodInstanceFlag_Friend) == 0);
  15138. PerformCallChecks(methodInstance.mMethodInstance, mPropSrc);
  15139. if (methodInstance.mMethodInstance->IsSkipCall())
  15140. {
  15141. mResult = mModule->GetDefaultTypedValue(methodInstance.mMethodInstance->mReturnType);
  15142. }
  15143. else
  15144. {
  15145. SizedArray<BfIRValue, 4> args;
  15146. if (!matchedMethod->mIsStatic)
  15147. {
  15148. auto owner = methodInstance.mMethodInstance->GetOwner();
  15149. bool isTypeMatch = mPropTarget.mType == owner;
  15150. if (owner->IsTypedPrimitive())
  15151. isTypeMatch |= mPropTarget.mType == owner->GetUnderlyingType();
  15152. if ((!isTypeMatch) ||
  15153. ((mPropTarget.mValue.IsFake()) && (!mOrigPropTarget.mValue.IsFake())))
  15154. {
  15155. auto prevPropTarget = mPropTarget;
  15156. mPropTarget = mModule->Cast(mPropSrc, mOrigPropTarget, owner);
  15157. if (!mPropTarget)
  15158. {
  15159. mModule->Fail("Internal property error", mPropSrc);
  15160. return BfTypedValue();
  15161. }
  15162. }
  15163. if ((mPropGetMethodFlags & BfGetMethodInstanceFlag_DisableObjectAccessChecks) == 0)
  15164. mModule->EmitObjectAccessCheck(mPropTarget);
  15165. }
  15166. auto callFlags = mPropDefBypassVirtual ? BfCreateCallFlags_BypassVirtual : BfCreateCallFlags_None;
  15167. mResult = CreateCall(mPropSrc, mPropTarget, mOrigPropTarget, matchedMethod, methodInstance, callFlags, mIndexerValues, NULL);
  15168. }
  15169. }
  15170. mPropDef = NULL;
  15171. mPropDefBypassVirtual = false;
  15172. mIndexerValues.clear();
  15173. mResultLocalVar = NULL;
  15174. mResultFieldInstance = NULL;
  15175. }
  15176. if (resolveGenericType)
  15177. ResolveGenericType();
  15178. BfTypedValue result = mResult;
  15179. if (clearResult)
  15180. mResult = BfTypedValue();
  15181. return result;
  15182. }
  15183. void BfExprEvaluator::CheckResultForReading(BfTypedValue& typedValue)
  15184. {
  15185. if (mModule->mCurMethodState == NULL)
  15186. return;
  15187. if ((mModule->mCurMethodState->mTempKind != BfMethodState::TempKind_None) || (mModule->mCurMethodState->mAllowUinitReads))
  15188. return;
  15189. if ((mModule->mCurTypeInstance->mResolvingVarField) || (mModule->mCurTypeInstance->mResolvingConstField))
  15190. return;
  15191. if ((typedValue) && (typedValue.IsAddr()))
  15192. {
  15193. if ((mResultLocalVar != NULL) && (mResultLocalVarRefNode != NULL))
  15194. {
  15195. SetAndRestoreValue<bool> prevIgnoreError(mModule->mIgnoreErrors);
  15196. if ((mModule->mCurMethodState->mClosureState != NULL) && (mModule->mCurMethodState->mClosureState->mCapturing))
  15197. {
  15198. // These errors can only be detected during capture time, so we don't ignore them on this pass
  15199. mModule->mIgnoreErrors = false;
  15200. }
  15201. int fieldIdx = mResultLocalVarField - 1;
  15202. auto localVar = mResultLocalVar;
  15203. if (localVar->mCompositeCount > 0)
  15204. {
  15205. mModule->Fail(StrFormat("Cannot read from composite '%s', it can only be used in an argument list", localVar->mName.c_str()), mResultLocalVarRefNode);
  15206. typedValue = BfTypedValue();
  15207. return;
  15208. }
  15209. if (localVar->mAssignedKind == BfLocalVarAssignKind_None)
  15210. {
  15211. mModule->TryLocalVariableInit(localVar);
  15212. }
  15213. if (localVar->mAssignedKind == BfLocalVarAssignKind_None)
  15214. {
  15215. auto methodStateForLocal = mModule->mCurMethodState->GetMethodStateForLocal(localVar);
  15216. bool isAssigned = false;
  15217. int64 undefinedFieldFlags = localVar->mUnassignedFieldFlags;
  15218. auto deferredLocalAssignData = methodStateForLocal->mDeferredLocalAssignData;
  15219. while ((deferredLocalAssignData != NULL) && (deferredLocalAssignData->mIsChained))
  15220. deferredLocalAssignData = deferredLocalAssignData->mChainedAssignData;
  15221. if (deferredLocalAssignData != NULL)
  15222. {
  15223. for (auto& assignedVar : deferredLocalAssignData->mAssignedLocals)
  15224. {
  15225. auto assignedLocal = assignedVar.mLocalVar;
  15226. if (assignedLocal == localVar)
  15227. {
  15228. int assignedFieldIdx = assignedVar.mLocalVarField;
  15229. if (assignedFieldIdx >= 0)
  15230. undefinedFieldFlags &= ~((int64)1 << assignedFieldIdx);
  15231. else
  15232. undefinedFieldFlags = 0;
  15233. }
  15234. }
  15235. }
  15236. if (fieldIdx == -1)
  15237. {
  15238. if (undefinedFieldFlags == 0)
  15239. isAssigned = true;
  15240. }
  15241. else
  15242. {
  15243. isAssigned = true;
  15244. for (int i = 0; i < mResultLocalVarFieldCount; i++)
  15245. if ((undefinedFieldFlags & (1LL << (fieldIdx + i))) != 0)
  15246. isAssigned = false;
  15247. }
  15248. if (!isAssigned)
  15249. {
  15250. if ((localVar->mIsThis) && (fieldIdx != -1))
  15251. {
  15252. // When we have initializers for fields, they won't all be processed in the autocomplte case
  15253. if (!mModule->mCompiler->IsAutocomplete())
  15254. {
  15255. auto bfError = mModule->Fail(StrFormat("Use of possibly unassigned field '%s'", mResultLocalVarRefNode->ToString().c_str()), mResultLocalVarRefNode, true);
  15256. }
  15257. }
  15258. else
  15259. {
  15260. mModule->Fail(StrFormat("Use of unassigned local variable '%s'", localVar->mName.c_str()), mResultLocalVarRefNode);
  15261. }
  15262. }
  15263. }
  15264. localVar->mReadFromId = mModule->mCurMethodState->GetRootMethodState()->mCurAccessId++;
  15265. }
  15266. }
  15267. }
  15268. void BfExprEvaluator::FinishExpressionResult()
  15269. {
  15270. CheckResultForReading(mResult);
  15271. mResultLocalVar = NULL;
  15272. mResultFieldInstance = NULL;
  15273. }
  15274. bool BfExprEvaluator::CheckAllowValue(const BfTypedValue& typedValue, BfAstNode* refNode)
  15275. {
  15276. return true;
  15277. }
  15278. void BfExprEvaluator::MarkResultUsed()
  15279. {
  15280. if (mResultLocalVar != NULL)
  15281. {
  15282. mResultLocalVar->mReadFromId = mModule->mCurMethodState->GetRootMethodState()->mCurAccessId++;
  15283. }
  15284. }
  15285. void BfExprEvaluator::MarkResultAssigned()
  15286. {
  15287. if (mResultLocalVar != NULL)
  15288. {
  15289. //int localIdx = mResultLocalVarIdx;
  15290. //if (localIdx == 0x7FFF)
  15291. //return;
  15292. auto localVar = mResultLocalVar;
  15293. int fieldIdx = mResultLocalVarField - 1;
  15294. int count = mResultLocalVarFieldCount;
  15295. if (fieldIdx == -1)
  15296. count = 1;
  15297. for (int i = 0; i < count; i++)
  15298. mModule->mCurMethodState->GetMethodStateForLocal(localVar)->LocalDefined(localVar, fieldIdx + i);
  15299. //if (localIdx != 0x7FFF)
  15300. {
  15301. if (localVar->mCompositeCount > 0)
  15302. {
  15303. mModule->Fail(StrFormat("Cannot write to composite '%s', it can only be used in an argument list", localVar->mName.c_str()), mResultLocalVarRefNode);
  15304. }
  15305. }
  15306. }
  15307. }
  15308. void BfExprEvaluator::MakeResultAsValue()
  15309. {
  15310. // Expressions like parens will turn a variable reference into a simple value
  15311. mResultLocalVar = NULL;
  15312. mResultFieldInstance = NULL;
  15313. }
  15314. bool BfExprEvaluator::CheckIsBase(BfAstNode* checkNode)
  15315. {
  15316. if (checkNode == NULL)
  15317. return false;
  15318. if (!checkNode->Equals("base"))
  15319. return false;
  15320. auto autoComplete = GetAutoComplete();
  15321. if ((autoComplete != NULL) && (autoComplete->IsAutocompleteNode(checkNode)))
  15322. {
  15323. if ((mModule->mCurTypeInstance != NULL) && (mModule->mCurTypeInstance->mBaseType != NULL))
  15324. autoComplete->SetDefinitionLocation(mModule->mCurTypeInstance->mBaseType->mTypeDef->GetRefNode());
  15325. }
  15326. return true;
  15327. }
  15328. bool BfExprEvaluator::CheckModifyResult(BfTypedValue typedVal, BfAstNode* refNode, const char* modifyType, bool onlyNeedsMut, bool emitWarning, bool skipCopyOnMutate)
  15329. {
  15330. if ((!skipCopyOnMutate) && (typedVal.IsCopyOnMutate()))
  15331. typedVal = mModule->CopyValue(typedVal);
  15332. BfLocalVariable* localVar = NULL;
  15333. bool isCapturedLocal = false;
  15334. if (mResultLocalVar != NULL)
  15335. {
  15336. localVar = mResultLocalVar;
  15337. localVar->mWrittenToId = mModule->mCurMethodState->GetRootMethodState()->mCurAccessId++;
  15338. }
  15339. else if (typedVal.IsThis())
  15340. {
  15341. localVar = mModule->GetThisVariable();
  15342. }
  15343. else if (typedVal.IsSplat())
  15344. {
  15345. for (auto checkLocal : mModule->mCurMethodState->mLocals)
  15346. {
  15347. if (checkLocal->mAddr == typedVal.mValue)
  15348. {
  15349. localVar = checkLocal;
  15350. break;
  15351. }
  15352. }
  15353. }
  15354. else if (typedVal.mValue.IsArg())
  15355. {
  15356. auto methodState = mModule->mCurMethodState->GetNonCaptureState();
  15357. localVar = methodState->mLocals[typedVal.mValue.mId];
  15358. }
  15359. if ((typedVal.mKind == BfTypedValueKind_MutableValue) && (onlyNeedsMut))
  15360. {
  15361. return true;
  15362. }
  15363. bool canModify = typedVal.CanModify();
  15364. auto _Fail = [&](const StringImpl& error, BfAstNode* refNode)
  15365. {
  15366. if (emitWarning)
  15367. return mModule->Warn(BfWarning_BF4204_AddressOfReadOnly, error, refNode);
  15368. else
  15369. return mModule->Fail(error, refNode);
  15370. };
  15371. if (localVar != NULL)
  15372. {
  15373. if (!canModify)
  15374. {
  15375. BfError* error = NULL;
  15376. if (localVar->mIsThis)
  15377. {
  15378. bool isClosure = false;
  15379. BfTypeInstance* checkTypeInst = localVar->mResolvedType->ToTypeInstance();
  15380. int fieldIdx = mResultLocalVarField - 1;
  15381. if ((!isCapturedLocal) && (mModule->mCurMethodState != NULL) && (mModule->mCurMethodState->mClosureState != NULL) && (mModule->mCurMethodState->mClosureState->mClosureType != NULL))
  15382. {
  15383. isClosure = true;
  15384. auto closureThis = mModule->mCurMethodState->mClosureState->mClosureType;
  15385. closureThis = checkTypeInst->mFieldInstances[0].mResolvedType->ToTypeInstance();
  15386. if (fieldIdx >= -1)
  15387. {
  15388. checkTypeInst = closureThis;
  15389. }
  15390. else
  15391. {
  15392. fieldIdx = -fieldIdx - 2;
  15393. isCapturedLocal = true;
  15394. }
  15395. }
  15396. if (fieldIdx < 0)
  15397. {
  15398. if (isClosure)
  15399. {
  15400. if (!mModule->mCurMethodState->mClosureState->mDeclaringMethodIsMutating)
  15401. error = _Fail(StrFormat("Cannot %s 'this' within struct lambda. Consider adding 'mut' specifier to this method.", modifyType), refNode);
  15402. else
  15403. error = _Fail(StrFormat("Cannot %s 'this' within struct lambda. Consider adding by-reference capture specifier [&] to lambda.", modifyType), refNode);
  15404. }
  15405. else if (localVar->mResolvedType->IsValueType())
  15406. {
  15407. error = _Fail(StrFormat("Cannot %s 'this' within struct method '%s'. Consider adding 'mut' specifier to this method.", modifyType,
  15408. mModule->MethodToString(mModule->mCurMethodInstance).c_str()), refNode);
  15409. }
  15410. else
  15411. {
  15412. error = _Fail(StrFormat("Cannot %s 'this' because '%s' is a reference type.", modifyType,
  15413. mModule->TypeToString(localVar->mResolvedType).c_str()), refNode);
  15414. }
  15415. return false;
  15416. }
  15417. else if (mResultFieldInstance != NULL)
  15418. {
  15419. if (isCapturedLocal)
  15420. {
  15421. 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,
  15422. mResultFieldInstance->GetFieldDef()->mName.c_str()), refNode);
  15423. }
  15424. else if (isClosure)
  15425. {
  15426. if (!mModule->mCurMethodState->mClosureState->mDeclaringMethodIsMutating)
  15427. error = _Fail(StrFormat("Cannot %s field '%s.%s' within struct lambda. Consider adding 'mut' specifier to this method.", modifyType,
  15428. mModule->TypeToString(mResultFieldInstance->mOwner).c_str(), mResultFieldInstance->GetFieldDef()->mName.c_str()), refNode);
  15429. else
  15430. error = _Fail(StrFormat("Cannot %s field '%s.%s' within struct lambda. Consider adding by-reference capture specifier [&] to lambda.", modifyType,
  15431. mModule->TypeToString(mResultFieldInstance->mOwner).c_str(), mResultFieldInstance->GetFieldDef()->mName.c_str()), refNode);
  15432. }
  15433. else if (mResultFieldInstance->GetFieldDef()->mIsReadOnly)
  15434. {
  15435. error = _Fail(StrFormat("Cannot %s readonly field '%s.%s' within method '%s'", modifyType,
  15436. mModule->TypeToString(mResultFieldInstance->mOwner).c_str(), mResultFieldInstance->GetFieldDef()->mName.c_str(),
  15437. mModule->MethodToString(mModule->mCurMethodInstance).c_str()), refNode);
  15438. }
  15439. else if (auto propertyDeclaration = BfNodeDynCast<BfPropertyDeclaration>(mResultFieldInstance->GetFieldDef()->mFieldDeclaration))
  15440. {
  15441. String propNam;
  15442. if (propertyDeclaration->mNameNode != NULL)
  15443. propertyDeclaration->mNameNode->ToString(propNam);
  15444. error = _Fail(StrFormat("Cannot %s auto-implemented property '%s.%s' without set accessor", modifyType,
  15445. mModule->TypeToString(mResultFieldInstance->mOwner).c_str(), propNam.c_str()), refNode);
  15446. }
  15447. else
  15448. {
  15449. error = _Fail(StrFormat("Cannot %s field '%s.%s' within struct method '%s'. Consider adding 'mut' specifier to this method.", modifyType,
  15450. mModule->TypeToString(mResultFieldInstance->mOwner).c_str(), mResultFieldInstance->GetFieldDef()->mName.c_str(),
  15451. mModule->MethodToString(mModule->mCurMethodInstance).c_str()), refNode);
  15452. }
  15453. return false;
  15454. }
  15455. }
  15456. else if (localVar->IsParam())
  15457. {
  15458. if (!mModule->mCurMethodInstance->IsMixin())
  15459. {
  15460. if (mModule->mCurMethodState->mMixinState != NULL)
  15461. error = _Fail(StrFormat("Cannot %s mixin parameter '%s'", modifyType,
  15462. localVar->mName.c_str()), refNode);
  15463. else if ((localVar->mResolvedType->IsGenericParam()) && (onlyNeedsMut))
  15464. error = _Fail(StrFormat("Cannot %s parameter '%s'. Consider adding 'mut' or 'ref' specifier to parameter or declaring 'var %s;' to create a mutable copy.", modifyType,
  15465. localVar->mName.c_str(), localVar->mName.c_str()), refNode);
  15466. else
  15467. error = _Fail(StrFormat("Cannot %s parameter '%s'. Consider adding 'ref' specifier to parameter or declaring 'var %s;' to create a mutable copy.", modifyType,
  15468. localVar->mName.c_str(), localVar->mName.c_str()), refNode);
  15469. return false;
  15470. }
  15471. }
  15472. else
  15473. {
  15474. if ((mResultLocalVarField != 0) && (!localVar->mIsReadOnly))
  15475. {
  15476. auto typeInst = localVar->mResolvedType->ToTypeInstance();
  15477. int dataIdx = mResultLocalVarField - 1;
  15478. if (typeInst != NULL)
  15479. {
  15480. for (auto& field : typeInst->mFieldInstances)
  15481. {
  15482. if (field.mDataIdx == dataIdx)
  15483. {
  15484. error = _Fail(StrFormat("Cannot %s readonly field '%s.%s'.", modifyType,
  15485. mModule->TypeToString(typeInst).c_str(),
  15486. field.GetFieldDef()->mName.c_str()), refNode);
  15487. break;
  15488. }
  15489. }
  15490. }
  15491. }
  15492. if (error == NULL)
  15493. {
  15494. error = _Fail(StrFormat("Cannot %s read-only local variable '%s'.", modifyType,
  15495. localVar->mName.c_str()), refNode);
  15496. }
  15497. return false;
  15498. }
  15499. }
  15500. else
  15501. {
  15502. // When we are capturing, we need to note that we require capturing by reference here
  15503. localVar->mWrittenToId = mModule->mCurMethodState->GetRootMethodState()->mCurAccessId++;
  15504. }
  15505. }
  15506. if ((mResultFieldInstance != NULL) && (mResultFieldInstance->GetFieldDef()->mIsReadOnly) && (!canModify))
  15507. {
  15508. auto error = _Fail(StrFormat("Cannot %s static readonly field '%s.%s' within method '%s'", modifyType,
  15509. mModule->TypeToString(mResultFieldInstance->mOwner).c_str(), mResultFieldInstance->GetFieldDef()->mName.c_str(),
  15510. mModule->MethodToString(mModule->mCurMethodInstance).c_str()), refNode);
  15511. return false;
  15512. }
  15513. return mModule->CheckModifyValue(typedVal, refNode, modifyType);
  15514. }
  15515. void BfExprEvaluator::Visit(BfConditionalExpression* condExpr)
  15516. {
  15517. static int sCallCount = 0;
  15518. sCallCount++;
  15519. auto condResult = mModule->CreateValueFromExpression(condExpr->mConditionExpression, mModule->GetPrimitiveType(BfTypeCode_Boolean), (BfEvalExprFlags)(mBfEvalExprFlags & BfEvalExprFlags_InheritFlags));
  15520. if (!condResult)
  15521. return;
  15522. if (condExpr->mTrueExpression == NULL)
  15523. {
  15524. mModule->AssertErrorState();
  15525. return;
  15526. }
  15527. if (condExpr->mFalseExpression == NULL)
  15528. {
  15529. mModule->CreateValueFromExpression(condExpr->mTrueExpression, mExpectingType, BfEvalExprFlags_NoCast);
  15530. mModule->AssertErrorState();
  15531. return;
  15532. }
  15533. bool isConstBranch = false;
  15534. bool constResult = false;
  15535. bool constResultUndef = false;
  15536. if (condResult.mValue.IsConst())
  15537. {
  15538. auto constValue = mModule->mBfIRBuilder->GetConstant(condResult.mValue);
  15539. if (constValue->mTypeCode == BfTypeCode_Boolean)
  15540. {
  15541. isConstBranch = true;
  15542. constResult = constValue->mBool;
  15543. }
  15544. else if (constValue->mConstType == BfConstType_Undef)
  15545. {
  15546. isConstBranch = true;
  15547. constResultUndef = true;
  15548. }
  15549. }
  15550. if (isConstBranch)
  15551. {
  15552. BfExpression* actualExpr = (constResult) ? condExpr->mTrueExpression : condExpr->mFalseExpression;
  15553. BfExpression* ignoredExpr = (constResult) ? condExpr->mFalseExpression : condExpr->mTrueExpression;
  15554. BfTypedValue actualValue = mModule->CreateValueFromExpression(actualExpr, mExpectingType, (BfEvalExprFlags)((mBfEvalExprFlags & BfEvalExprFlags_InheritFlags) | BfEvalExprFlags_NoCast));
  15555. BfTypedValue ignoredValue;
  15556. //
  15557. {
  15558. auto curBlock = mModule->mBfIRBuilder->GetInsertBlock();
  15559. SetAndRestoreValue<bool> ignoreWrites(mModule->mBfIRBuilder->mIgnoreWrites, true);
  15560. ignoredValue = mModule->CreateValueFromExpression(ignoredExpr, mExpectingType, (BfEvalExprFlags)((mBfEvalExprFlags & BfEvalExprFlags_InheritFlags) | BfEvalExprFlags_NoCast));
  15561. mModule->mBfIRBuilder->SetInsertPoint(curBlock);
  15562. }
  15563. if (!actualValue)
  15564. return;
  15565. if ((ignoredValue) && (ignoredValue.mType != actualValue.mType))
  15566. {
  15567. // Cast to more specific 'ignored' type if applicable
  15568. if (mModule->CanCast(actualValue, ignoredValue.mType))
  15569. {
  15570. actualValue = mModule->Cast(actualExpr, actualValue, ignoredValue.mType);
  15571. }
  15572. else if (!mModule->CanCast(ignoredValue, actualValue.mType))
  15573. {
  15574. mModule->Fail(StrFormat("Type of conditional expression cannot be determined because there is no implicit conversion between '%s' and '%s'",
  15575. mModule->TypeToString(actualValue.mType).c_str(), mModule->TypeToString(ignoredValue.mType).c_str()), condExpr);
  15576. }
  15577. }
  15578. mResult = actualValue;
  15579. if (constResultUndef)
  15580. mResult = mModule->GetDefaultTypedValue(mResult.mType, false, BfDefaultValueKind_Undef);
  15581. return;
  15582. }
  15583. auto trueBB = mModule->mBfIRBuilder->CreateBlock("cond.then");
  15584. auto falseBB = mModule->mBfIRBuilder->CreateBlock("cond.else");
  15585. auto endBB = mModule->mBfIRBuilder->CreateBlock("cond.end");
  15586. auto contBB = mModule->mBfIRBuilder->CreateBlock("cond.cont");
  15587. mModule->mBfIRBuilder->CreateCondBr(condResult.mValue, trueBB, falseBB);
  15588. SetAndRestoreValue<bool> prevInCondBlock(mModule->mCurMethodState->mCurScope->mInnerIsConditional, true);
  15589. bool wantExpectingCast = (mExpectingType != NULL) && ((mBfEvalExprFlags & BfEvalExprFlags_NoCast) == 0);
  15590. mModule->AddBasicBlock(trueBB);
  15591. auto trueValue = mModule->CreateValueFromExpression(condExpr->mTrueExpression, mExpectingType, (BfEvalExprFlags)((mBfEvalExprFlags & BfEvalExprFlags_InheritFlags) | BfEvalExprFlags_NoCast | BfEvalExprFlags_CreateConditionalScope));
  15592. if ((wantExpectingCast) && (trueValue) && (trueValue.mType != mExpectingType))
  15593. {
  15594. // In some cases like typed primitives - we CAN individually cast each value which it's a constant still, but not after the merging
  15595. // IE: Color c = isOver ? 0xFF000000 : 0xFFFFFFFF;
  15596. // Otherwise the resulting value would just be 'int' which cannot implicitly convert to Color, but each of those ints can be
  15597. // a uint32 if converted separately
  15598. auto checkTrueValue = mModule->Cast(condExpr->mTrueExpression, trueValue, mExpectingType, BfCastFlags_SilentFail);
  15599. if (checkTrueValue)
  15600. trueValue = checkTrueValue;
  15601. mModule->FixIntUnknown(trueValue);
  15602. }
  15603. auto trueBlockPos = mModule->mBfIRBuilder->GetInsertBlock();
  15604. mModule->AddBasicBlock(falseBB);
  15605. auto falseValue = mModule->CreateValueFromExpression(condExpr->mFalseExpression, mExpectingType, (BfEvalExprFlags)((mBfEvalExprFlags & BfEvalExprFlags_InheritFlags) | BfEvalExprFlags_NoCast | BfEvalExprFlags_CreateConditionalScope));
  15606. auto falseBlockPos = mModule->mBfIRBuilder->GetInsertBlock();
  15607. if ((wantExpectingCast) && (falseValue) && (falseValue.mType != mExpectingType))
  15608. {
  15609. auto checkFalseValue = mModule->Cast(condExpr->mFalseExpression, falseValue, mExpectingType, BfCastFlags_SilentFail);
  15610. if (checkFalseValue)
  15611. falseValue = checkFalseValue;
  15612. mModule->FixIntUnknown(falseValue);
  15613. }
  15614. prevInCondBlock.Restore();
  15615. bool isValid = trueValue && falseValue;
  15616. if (isValid)
  15617. {
  15618. BfTypedValue falseToTrue;
  15619. {
  15620. SetAndRestoreValue<bool> prevIgnoreError(mModule->mIgnoreErrors, true);
  15621. mModule->mBfIRBuilder->SetInsertPoint(falseBlockPos);
  15622. falseToTrue = mModule->Cast(condExpr->mFalseExpression, falseValue, trueValue.mType);
  15623. }
  15624. if (falseToTrue)
  15625. {
  15626. falseValue = falseToTrue;
  15627. }
  15628. else
  15629. {
  15630. BfTypedValue trueToFalse;
  15631. {
  15632. SetAndRestoreValue<bool> prevIgnoreError(mModule->mIgnoreErrors, true);
  15633. mModule->mBfIRBuilder->SetInsertPoint(trueBlockPos);
  15634. trueToFalse = mModule->Cast(condExpr->mTrueExpression, trueValue, falseValue.mType);
  15635. }
  15636. if (!trueToFalse)
  15637. {
  15638. mModule->Fail(StrFormat("Type of conditional expression cannot be determined because there is no implicit conversion between '%s' and '%s'",
  15639. mModule->TypeToString(trueValue.mType).c_str(), mModule->TypeToString(falseValue.mType).c_str()), condExpr);
  15640. //return;
  15641. isValid = false;
  15642. }
  15643. else
  15644. trueValue = trueToFalse;
  15645. }
  15646. }
  15647. mModule->mBfIRBuilder->SetInsertPoint(trueBlockPos);
  15648. if (isValid)
  15649. trueValue = mModule->LoadValue(trueValue);
  15650. mModule->mBfIRBuilder->CreateBr(endBB);
  15651. mModule->mBfIRBuilder->SetInsertPoint(falseBlockPos);
  15652. if (isValid)
  15653. falseValue = mModule->LoadValue(falseValue);
  15654. mModule->mBfIRBuilder->CreateBr(endBB);
  15655. mModule->AddBasicBlock(endBB, false);
  15656. if (!isValid)
  15657. return;
  15658. mModule->mBfIRBuilder->SetInsertPoint(endBB);
  15659. BfIRValue phi;
  15660. if (!trueValue.mType->IsValuelessType())
  15661. {
  15662. if (trueValue.mType->IsVar())
  15663. {
  15664. phi = mModule->mBfIRBuilder->GetFakeVal();
  15665. }
  15666. else
  15667. {
  15668. phi = mModule->mBfIRBuilder->CreatePhi(mModule->mBfIRBuilder->MapType(trueValue.mType), 2);
  15669. mModule->mBfIRBuilder->AddPhiIncoming(phi, trueValue.mValue, trueBlockPos);
  15670. mModule->mBfIRBuilder->AddPhiIncoming(phi, falseValue.mValue, falseBlockPos);
  15671. }
  15672. }
  15673. mModule->mBfIRBuilder->CreateBr(contBB);
  15674. mModule->AddBasicBlock(contBB);
  15675. mResult = BfTypedValue(phi, trueValue.mType);
  15676. }
  15677. void BfExprEvaluator::PopulateDeferrredTupleAssignData(BfTupleExpression* tupleExpr, DeferredTupleAssignData& deferredTupleAssignData)
  15678. {
  15679. BfTypeVector fieldTypes;
  15680. Array<String> fieldNames;
  15681. // We need to evaluate each LHS tuple component in a separate BfExprEvaluator because each one
  15682. // could be a property and the 'mPropDef' target info is tied to a single evaluator
  15683. for (int valueIdx = 0; valueIdx < (int)tupleExpr->mValues.size(); valueIdx++)
  15684. {
  15685. DeferredTupleAssignData::Entry entry;
  15686. entry.mExprEvaluator = NULL;
  15687. entry.mInnerTuple = NULL;
  15688. BfExpression* valueExpr = tupleExpr->mValues[valueIdx];
  15689. entry.mExpr = valueExpr;
  15690. BfType* fieldType = NULL;
  15691. BfType* resultType = NULL;
  15692. if (auto innerTupleExpr = BfNodeDynCast<BfTupleExpression>(valueExpr))
  15693. {
  15694. entry.mInnerTuple = new DeferredTupleAssignData();
  15695. PopulateDeferrredTupleAssignData(innerTupleExpr, *entry.mInnerTuple);
  15696. resultType = entry.mInnerTuple->mTupleType;
  15697. }
  15698. else
  15699. {
  15700. BfExprEvaluator* exprEvaluator = new BfExprEvaluator(mModule);
  15701. entry.mExprEvaluator = exprEvaluator;
  15702. if (valueExpr->IsA<BfUninitializedExpression>())
  15703. {
  15704. resultType = mModule->GetPrimitiveType(BfTypeCode_None);
  15705. }
  15706. if (auto varDecl = BfNodeDynCast<BfVariableDeclaration>(valueExpr))
  15707. {
  15708. if ((varDecl->mTypeRef->IsA<BfLetTypeReference>()) || (varDecl->mTypeRef->IsA<BfVarTypeReference>()))
  15709. {
  15710. resultType = mModule->GetPrimitiveType(BfTypeCode_Var);
  15711. }
  15712. else
  15713. {
  15714. resultType = ResolveTypeRef(varDecl->mTypeRef);
  15715. if (resultType == NULL)
  15716. resultType = mModule->GetPrimitiveType(BfTypeCode_Var);
  15717. }
  15718. }
  15719. if (resultType == NULL)
  15720. {
  15721. exprEvaluator->VisitChild(valueExpr);
  15722. if ((!exprEvaluator->mResult) && (exprEvaluator->mPropDef == NULL))
  15723. exprEvaluator->mResult = mModule->GetDefaultTypedValue(mModule->GetPrimitiveType(BfTypeCode_None));
  15724. resultType = exprEvaluator->mResult.mType;
  15725. }
  15726. if ((resultType == NULL) && (exprEvaluator->mPropDef != NULL) && (exprEvaluator->mPropTarget.mType != NULL))
  15727. {
  15728. auto propTypeInst = exprEvaluator->mPropTarget.mType->ToTypeInstance();
  15729. if ((propTypeInst == NULL) && (exprEvaluator->mPropTarget.mType->IsPointer()))
  15730. {
  15731. BfPointerType* pointerType = (BfPointerType*)exprEvaluator->mPropTarget.mType;
  15732. propTypeInst = pointerType->mElementType->ToTypeInstance();
  15733. }
  15734. auto setMethod = GetPropertyMethodDef(exprEvaluator->mPropDef, BfMethodType_PropertySetter, mPropCheckedKind, mPropTarget);
  15735. if (setMethod != NULL)
  15736. {
  15737. auto methodInstance = mModule->GetMethodInstance(propTypeInst, setMethod, BfTypeVector());
  15738. resultType = methodInstance.mMethodInstance->GetParamType(0);
  15739. }
  15740. else
  15741. {
  15742. auto getMethod = GetPropertyMethodDef(exprEvaluator->mPropDef, BfMethodType_PropertyGetter, mPropCheckedKind, mPropTarget);
  15743. if (getMethod != NULL)
  15744. {
  15745. auto methodInstance = mModule->GetMethodInstance(propTypeInst, getMethod, BfTypeVector());
  15746. auto retType = methodInstance.mMethodInstance->mReturnType;
  15747. if (retType->IsRef())
  15748. resultType = retType->GetUnderlyingType();
  15749. }
  15750. }
  15751. }
  15752. }
  15753. if (resultType == NULL)
  15754. resultType = mModule->GetPrimitiveType(BfTypeCode_None);
  15755. deferredTupleAssignData.mChildren.push_back(entry);
  15756. fieldTypes.push_back(resultType);
  15757. }
  15758. for (BfTupleNameNode* requestedName : tupleExpr->mNames)
  15759. {
  15760. if (requestedName == NULL)
  15761. fieldNames.push_back("");
  15762. else
  15763. fieldNames.push_back(requestedName->mNameNode->ToString());
  15764. }
  15765. BfTypeInstance* tupleType = mModule->CreateTupleType(fieldTypes, fieldNames, true);
  15766. deferredTupleAssignData.mTupleType = tupleType;
  15767. }
  15768. void BfExprEvaluator::AssignDeferrredTupleAssignData(BfAssignmentExpression* assignExpr, DeferredTupleAssignData& deferredTupleAssignData, BfTypedValue rightValue)
  15769. {
  15770. BF_ASSERT(rightValue.mType->IsTuple());
  15771. auto tupleType = (BfTypeInstance*)rightValue.mType;
  15772. for (int valueIdx = 0; valueIdx < (int)deferredTupleAssignData.mChildren.size(); valueIdx++)
  15773. {
  15774. auto& child = deferredTupleAssignData.mChildren[valueIdx];
  15775. BfFieldInstance* fieldInstance = &tupleType->mFieldInstances[valueIdx];
  15776. BfTypedValue elementValue;
  15777. if (fieldInstance->mDataIdx >= 0)
  15778. {
  15779. rightValue = mModule->LoadOrAggregateValue(rightValue);
  15780. auto extractedValue = mModule->mBfIRBuilder->CreateExtractValue(rightValue.mValue, fieldInstance->mDataIdx);
  15781. elementValue = BfTypedValue(extractedValue, fieldInstance->GetResolvedType());
  15782. if (child.mInnerTuple != NULL)
  15783. {
  15784. AssignDeferrredTupleAssignData(assignExpr, *child.mInnerTuple, elementValue);
  15785. delete child.mInnerTuple;
  15786. child.mInnerTuple = NULL;
  15787. }
  15788. else
  15789. {
  15790. if (child.mExprEvaluator->HasResult())
  15791. {
  15792. child.mExprEvaluator->mBfEvalExprFlags = (BfEvalExprFlags)(child.mExprEvaluator->mBfEvalExprFlags | BfEvalExprFlags_NoAutoComplete);
  15793. child.mExprEvaluator->PerformAssignment(assignExpr, true, elementValue);
  15794. }
  15795. }
  15796. }
  15797. if (auto varDecl = BfNodeDynCast<BfVariableDeclaration>(child.mExpr))
  15798. {
  15799. if (!elementValue)
  15800. elementValue = mModule->GetDefaultTypedValue(fieldInstance->GetResolvedType());
  15801. mModule->HandleVariableDeclaration(varDecl, elementValue);
  15802. }
  15803. }
  15804. }
  15805. void BfExprEvaluator::DoTupleAssignment(BfAssignmentExpression* assignExpr)
  15806. {
  15807. auto tupleExpr = BfNodeDynCast<BfTupleExpression>(assignExpr->mLeft);
  15808. DeferredTupleAssignData deferredTupleAssignData;
  15809. PopulateDeferrredTupleAssignData(tupleExpr, deferredTupleAssignData);
  15810. BfTypeInstance* tupleType = deferredTupleAssignData.mTupleType;
  15811. BfTypedValue rightValue;
  15812. if (assignExpr->mRight != NULL)
  15813. {
  15814. rightValue = mModule->CreateValueFromExpression(assignExpr->mRight, tupleType);
  15815. }
  15816. if (!rightValue)
  15817. {
  15818. tupleType = mModule->SantizeTupleType(tupleType);
  15819. rightValue = mModule->GetDefaultTypedValue(tupleType);
  15820. }
  15821. rightValue = mModule->LoadValue(rightValue);
  15822. AssignDeferrredTupleAssignData(assignExpr, deferredTupleAssignData, rightValue);
  15823. mResult = rightValue;
  15824. }
  15825. void BfExprEvaluator::PerformAssignment(BfAssignmentExpression* assignExpr, bool evaluatedLeft, BfTypedValue rightValue, BfTypedValue* outCascadeValue)
  15826. {
  15827. auto binaryOp = BfAssignOpToBinaryOp(assignExpr->mOp);
  15828. BfExpression* targetNode = assignExpr->mLeft;
  15829. if ((BfNodeIsA<BfMixinExpression>(targetNode)) && (!mModule->mCurMethodInstance->mIsUnspecialized))
  15830. {
  15831. // If we have a "mixin = <X>" but there's no mixin target then ignore the assignment
  15832. int mixinVar = GetMixinVariable();
  15833. if (mixinVar == -1)
  15834. {
  15835. mResult = mModule->GetDefaultTypedValue(mModule->GetPrimitiveType(BfTypeCode_None));
  15836. return;
  15837. }
  15838. }
  15839. BfAutoComplete* autoComplete = GetAutoComplete();
  15840. bool deferredFixits = false;
  15841. if ((autoComplete != NULL) && (autoComplete->mResolveType == BfResolveType_GetFixits))
  15842. {
  15843. SetAndRestoreValue<bool> ignoreFixits(autoComplete->mIgnoreFixits, true);
  15844. VisitChild(targetNode);
  15845. deferredFixits = true;
  15846. }
  15847. else if (!evaluatedLeft)
  15848. {
  15849. if (auto memberReferenceExpr = BfNodeDynCast<BfMemberReferenceExpression>(targetNode))
  15850. {
  15851. DoMemberReference(memberReferenceExpr, outCascadeValue);
  15852. }
  15853. else
  15854. VisitChild(targetNode);
  15855. }
  15856. if ((!mResult) && (mPropDef == NULL))
  15857. {
  15858. if (assignExpr->mRight != NULL)
  15859. {
  15860. auto result = mModule->CreateValueFromExpression(assignExpr->mRight);
  15861. if (deferredFixits)
  15862. {
  15863. SetAndRestoreValue<bool> ignoreErrors(mModule->mIgnoreErrors, true);
  15864. mExpectingType = result.mType;
  15865. VisitChild(targetNode);
  15866. mResult = BfTypedValue();
  15867. }
  15868. }
  15869. return;
  15870. }
  15871. ResolveGenericType();
  15872. auto ptr = mResult;
  15873. mResult = BfTypedValue();
  15874. if (mPropDef == NULL)
  15875. {
  15876. if (!CheckModifyResult(ptr, assignExpr->mOpToken, "assign to", false, false, true))
  15877. {
  15878. if (assignExpr->mRight != NULL)
  15879. mModule->CreateValueFromExpression(assignExpr->mRight, ptr.mType, BfEvalExprFlags_NoCast);
  15880. return;
  15881. }
  15882. }
  15883. if (mPropDef != NULL)
  15884. {
  15885. bool hasLeftVal = false;
  15886. auto propDef = mPropDef;
  15887. auto propTarget = mPropTarget;
  15888. auto setMethod = GetPropertyMethodDef(mPropDef, BfMethodType_PropertySetter, mPropCheckedKind, mPropTarget);
  15889. if (setMethod == NULL)
  15890. {
  15891. // Allow for a ref return on the getter to be used if a setter is not available
  15892. GetResult();
  15893. if ((mResult) && (mResult.mKind == BfTypedValueKind_Addr))
  15894. {
  15895. ptr = mResult;
  15896. mResult = BfTypedValue();
  15897. hasLeftVal = true;
  15898. }
  15899. else
  15900. {
  15901. mModule->Fail("Property has no setter", mPropSrc);
  15902. if (assignExpr->mRight != NULL)
  15903. mModule->CreateValueFromExpression(assignExpr->mRight, ptr.mType, BfEvalExprFlags_NoCast);
  15904. return;
  15905. }
  15906. }
  15907. if (!hasLeftVal)
  15908. {
  15909. auto methodInstance = GetPropertyMethodInstance(setMethod);
  15910. if (methodInstance.mMethodInstance == NULL)
  15911. return;
  15912. //BF_ASSERT(methodInstance.mMethodInstance->mMethodDef == setMethod);
  15913. CheckPropFail(setMethod, methodInstance.mMethodInstance, (mPropGetMethodFlags & BfGetMethodInstanceFlag_Friend) == 0);
  15914. auto autoComplete = GetAutoComplete();
  15915. if ((autoComplete != NULL) && (autoComplete->IsAutocompleteNode(mPropSrc)) && (autoComplete->mResolveType == BfResolveType_GetResultString))
  15916. {
  15917. autoComplete->mResultString = ":";
  15918. autoComplete->mResultString += mModule->TypeToString(methodInstance.mMethodInstance->GetParamType(0));
  15919. autoComplete->mResultString += " ";
  15920. autoComplete->mResultString += mModule->TypeToString(methodInstance.mMethodInstance->GetOwner());
  15921. autoComplete->mResultString += ".";
  15922. autoComplete->mResultString += mPropDef->mName;
  15923. }
  15924. BfTypedValue convVal;
  15925. if (binaryOp != BfBinaryOp_None)
  15926. {
  15927. PerformBinaryOperation(assignExpr->mLeft, assignExpr->mRight, binaryOp, assignExpr->mOpToken, BfBinOpFlag_ForceLeftType);
  15928. if (!mResult)
  15929. return;
  15930. convVal = mResult;
  15931. mResult = BfTypedValue();
  15932. if (!convVal)
  15933. return;
  15934. }
  15935. else
  15936. {
  15937. auto wantType = methodInstance.mMethodInstance->GetParamType(0);
  15938. if (rightValue)
  15939. {
  15940. convVal = mModule->Cast(assignExpr->mRight, rightValue, wantType);
  15941. }
  15942. else
  15943. {
  15944. if (assignExpr->mRight == NULL)
  15945. {
  15946. mModule->AssertErrorState();
  15947. return;
  15948. }
  15949. BfEvalExprFlags exprFlags = (BfEvalExprFlags)(BfEvalExprFlags_AllowSplat | BfEvalExprFlags_PendingPropSet);
  15950. if (wantType->IsRef())
  15951. exprFlags = (BfEvalExprFlags)(exprFlags | BfEvalExprFlags_AllowRefExpr);
  15952. convVal = mModule->CreateValueFromExpression(assignExpr->mRight, wantType, exprFlags);
  15953. }
  15954. if (!convVal)
  15955. {
  15956. mPropDef = NULL;
  15957. return;
  15958. }
  15959. }
  15960. if (mPropSrc != NULL)
  15961. mModule->UpdateExprSrcPos(mPropSrc);
  15962. BfResolvedArg valueArg;
  15963. valueArg.mTypedValue = convVal;
  15964. mIndexerValues.Insert(0, valueArg);
  15965. if (!setMethod->mIsStatic)
  15966. {
  15967. auto owner = methodInstance.mMethodInstance->GetOwner();
  15968. if ((mPropTarget.mType != owner) ||
  15969. ((mPropTarget.mValue.IsFake()) && (!mOrigPropTarget.mValue.IsFake())))
  15970. {
  15971. if ((mPropDefBypassVirtual) || (!mPropTarget.mType->IsInterface()))
  15972. {
  15973. mPropTarget = mModule->Cast(mPropSrc, mOrigPropTarget, owner);
  15974. if (!mPropTarget)
  15975. {
  15976. mModule->Fail("Internal property error", mPropSrc);
  15977. return;
  15978. }
  15979. }
  15980. }
  15981. }
  15982. auto callFlags = mPropDefBypassVirtual ? BfCreateCallFlags_BypassVirtual : BfCreateCallFlags_None;
  15983. mResult = CreateCall(mPropSrc, mPropTarget, mOrigPropTarget, setMethod, methodInstance, callFlags, mIndexerValues, NULL);
  15984. mPropDef = NULL;
  15985. mResult = convVal;
  15986. mIndexerValues.Clear();
  15987. return;
  15988. }
  15989. }
  15990. auto toType = ptr.mType;
  15991. if (toType->IsRef())
  15992. {
  15993. auto refType = (BfRefType*)toType;
  15994. toType = refType->mElementType;
  15995. }
  15996. if ((autoComplete != NULL) && (assignExpr->mOpToken != NULL) && (toType != NULL))
  15997. autoComplete->CheckEmptyStart(assignExpr->mOpToken, toType);
  15998. BfExpression* rightExpr = assignExpr->mRight;
  15999. if (rightExpr == NULL)
  16000. {
  16001. mModule->AssertErrorState();
  16002. return;
  16003. }
  16004. bool alreadyWritten = false;
  16005. BfTypedValue convVal;
  16006. if (binaryOp != BfBinaryOp_None)
  16007. {
  16008. CheckResultForReading(ptr);
  16009. BfTypedValue leftValue = ptr;
  16010. bool deferBinop = false;
  16011. BfDeferEvalChecker deferEvalChecker;
  16012. deferEvalChecker.mDeferLiterals = false;
  16013. assignExpr->mRight->Accept(&deferEvalChecker);
  16014. if (deferEvalChecker.mNeedsDeferEval)
  16015. deferBinop = true;
  16016. if (binaryOp == BfBinaryOp_NullCoalesce)
  16017. {
  16018. deferBinop = true;
  16019. }
  16020. if (!deferBinop)
  16021. {
  16022. auto expectedType = ptr.mType;
  16023. if ((binaryOp == BfBinaryOp_LeftShift) || (binaryOp == BfBinaryOp_RightShift))
  16024. expectedType = mModule->GetPrimitiveType(BfTypeCode_IntPtr);
  16025. if ((!rightValue) && (assignExpr->mRight != NULL))
  16026. {
  16027. rightValue = mModule->CreateValueFromExpression(assignExpr->mRight, expectedType, (BfEvalExprFlags)(BfEvalExprFlags_AllowSplat | BfEvalExprFlags_NoCast));
  16028. }
  16029. }
  16030. bool handled = false;
  16031. BfResolvedArgs argValues;
  16032. if ((rightValue) || (deferBinop))
  16033. {
  16034. auto checkTypeInst = leftValue.mType->ToTypeInstance();
  16035. while (checkTypeInst != NULL)
  16036. {
  16037. for (auto operatorDef : checkTypeInst->mTypeDef->mOperators)
  16038. {
  16039. if (operatorDef->mOperatorDeclaration->mAssignOp != assignExpr->mOp)
  16040. continue;
  16041. auto methodInst = mModule->GetRawMethodInstanceAtIdx(checkTypeInst, operatorDef->mIdx);
  16042. if (methodInst->GetParamCount() != 1)
  16043. continue;
  16044. auto paramType = methodInst->GetParamType(0);
  16045. if (deferBinop)
  16046. {
  16047. if (argValues.mArguments == NULL)
  16048. {
  16049. SizedArray<BfExpression*, 2> argExprs;
  16050. argExprs.push_back(assignExpr->mRight);
  16051. BfSizedArray<BfExpression*> sizedArgExprs(argExprs);
  16052. argValues.Init(&sizedArgExprs);
  16053. ResolveArgValues(argValues, BfResolveArgsFlag_DeferParamEval);
  16054. }
  16055. rightValue = ResolveArgValue(argValues.mResolvedArgs[0], paramType);
  16056. if (!rightValue)
  16057. continue;
  16058. }
  16059. else
  16060. {
  16061. if (!mModule->CanCast(rightValue, paramType))
  16062. continue;
  16063. }
  16064. mModule->SetElementType(assignExpr->mOpToken, BfSourceElementType_Method);
  16065. if ((autoComplete != NULL) && (autoComplete->IsAutocompleteNode(assignExpr->mOpToken)))
  16066. {
  16067. if (operatorDef->mOperatorDeclaration != NULL)
  16068. autoComplete->SetDefinitionLocation(operatorDef->mOperatorDeclaration->mOpTypeToken);
  16069. }
  16070. auto moduleMethodInstance = mModule->GetMethodInstance(checkTypeInst, operatorDef, BfTypeVector());
  16071. BfExprEvaluator exprEvaluator(mModule);
  16072. SizedArray<BfIRValue, 1> args;
  16073. exprEvaluator.PushThis(assignExpr->mLeft, leftValue, moduleMethodInstance.mMethodInstance, args);
  16074. exprEvaluator.PushArg(rightValue, args);
  16075. exprEvaluator.CreateCall(assignExpr, moduleMethodInstance.mMethodInstance, moduleMethodInstance.mFunc, false, args);
  16076. convVal = leftValue;
  16077. handled = true;
  16078. break;
  16079. }
  16080. if (handled)
  16081. break;
  16082. checkTypeInst = mModule->GetBaseType(checkTypeInst);
  16083. }
  16084. if (!handled)
  16085. {
  16086. auto flags = BfBinOpFlag_ForceLeftType;
  16087. if (deferBinop)
  16088. flags = (BfBinOpFlags)(flags | BfBinOpFlag_DeferRight);
  16089. leftValue = mModule->LoadValue(leftValue);
  16090. if ((binaryOp == BfBinaryOp_NullCoalesce) && (PerformBinaryOperation_NullCoalesce(assignExpr->mOpToken, assignExpr->mLeft, assignExpr->mRight, leftValue, leftValue.mType, &ptr)))
  16091. {
  16092. return;
  16093. }
  16094. PerformBinaryOperation(assignExpr->mLeft, assignExpr->mRight, binaryOp, assignExpr->mOpToken, flags, leftValue, rightValue);
  16095. }
  16096. }
  16097. if (!handled)
  16098. {
  16099. convVal = mResult;
  16100. mResult = BfTypedValue();
  16101. }
  16102. if (!convVal)
  16103. return;
  16104. }
  16105. else
  16106. {
  16107. convVal = rightValue;
  16108. if (!convVal)
  16109. {
  16110. if (auto uninitExpr = BfNodeDynCast<BfUninitializedExpression>(rightExpr))
  16111. {
  16112. if (mResultLocalVar != NULL)
  16113. {
  16114. MarkResultAssigned();
  16115. return;
  16116. }
  16117. }
  16118. // In the cases like "structVal = GetVal()", the allowDirectStructRetWrite optimization allows us to pass the
  16119. // address of structVal into the sret. We only allow that if structVal is a local, because if it's globally
  16120. // visible then we could see the results of a partially-modified structVal
  16121. //bool allowDirectStructRetWrite = mResultLocalVarIdx != -1;
  16122. // ALTHOUGH- we can only allow this optimization if we can be sure the local value is not aliased- we could
  16123. // have the backend ensure that this local value never gets its address taken.
  16124. bool allowDirectStructWrite = false;
  16125. BfExprEvaluator exprEvaluator(mModule);
  16126. exprEvaluator.mExpectingType = toType;
  16127. if (allowDirectStructWrite)
  16128. exprEvaluator.mReceivingValue = &ptr;
  16129. exprEvaluator.Evaluate(rightExpr, false, false, true);
  16130. exprEvaluator.CheckResultForReading(exprEvaluator.mResult);
  16131. convVal = exprEvaluator.GetResult();
  16132. mModule->FixIntUnknown(convVal);
  16133. alreadyWritten = (allowDirectStructWrite) && (exprEvaluator.mReceivingValue == NULL);
  16134. if (!convVal)
  16135. convVal = mModule->GetDefaultTypedValue(toType);
  16136. // Did we use mReceivingValue as a mixin result?
  16137. if ((convVal.mValue) && (convVal.mValue == ptr.mValue))
  16138. {
  16139. mResult = convVal;
  16140. return;
  16141. }
  16142. }
  16143. }
  16144. BF_ASSERT(convVal);
  16145. if ((convVal) && (convVal.mType->IsNull()) && (ptr.mType->IsNullable()))
  16146. {
  16147. // Allow this to pass through so we can catch it in the memset later in this function
  16148. }
  16149. else
  16150. {
  16151. if (!convVal.mType->IsComposite())
  16152. convVal = mModule->LoadValue(convVal);
  16153. convVal = mModule->Cast(rightExpr, convVal, toType);
  16154. if (!convVal)
  16155. return;
  16156. convVal = mModule->LoadValue(convVal);
  16157. }
  16158. if (ptr.mType->IsVar())
  16159. {
  16160. mResult = ptr;
  16161. MarkResultAssigned();
  16162. return;
  16163. }
  16164. if (convVal.mValue)
  16165. {
  16166. if ((ptr.mType->IsStruct()) && (!ptr.mType->IsValuelessType()) && (convVal.mValue.IsConst()))
  16167. {
  16168. auto constant = mModule->mBfIRBuilder->GetConstant(convVal.mValue);
  16169. if ((constant->mTypeCode == BfTypeCode_NullPtr) || (constant->mConstType == BfConstType_AggZero))
  16170. {
  16171. auto type = ptr.mType;
  16172. mModule->mBfIRBuilder->CreateMemSet(ptr.mValue, mModule->GetConstValue(0, mModule->GetPrimitiveType(BfTypeCode_Int8)),
  16173. mModule->GetConstValue(type->mSize), type->mAlign);
  16174. mResult = ptr;
  16175. MarkResultAssigned();
  16176. return;
  16177. }
  16178. }
  16179. // if (ptr.mType->IsMethodRef())
  16180. // {
  16181. // auto methodRefType = (BfMethodRefType*)ptr.mType;
  16182. // auto methodInstance = methodRefType->mMethodInstance;
  16183. // int implicitParamCount = methodInstance->GetImplicitParamCount();
  16184. // for (int implicitParamIdx = methodInstance->HasThis() ? - 1 : 0; implicitParamIdx < implicitParamCount; implicitParamIdx++)
  16185. // {
  16186. // bool failed = false;
  16187. // auto destPtr = DoImplicitArgCapture(assignExpr, methodRefType->mMethodInstance, implicitParamIdx, failed, BfImplicitParamKind_GenericTypeMember_Addr);
  16188. // auto srcVal = DoImplicitArgCapture(assignExpr, methodRefType->mMethodInstance, implicitParamIdx, failed, BfImplicitParamKind_GenericMethodMember);
  16189. // if ((destPtr) && (srcVal))
  16190. // {
  16191. // srcVal = mModule->AggregateSplat(srcVal);
  16192. // mModule->mBfIRBuilder->CreateStore(srcVal.mValue, destPtr.mValue);
  16193. // }
  16194. // }
  16195. // }
  16196. // else
  16197. {
  16198. mModule->mBfIRBuilder->PopulateType(ptr.mType);
  16199. if (convVal.IsSplat())
  16200. {
  16201. //convVal = mModule->AggregateSplat(convVal);
  16202. mModule->AggregateSplatIntoAddr(convVal, ptr.mValue);
  16203. }
  16204. else
  16205. {
  16206. if (ptr.mType->IsValuelessType())
  16207. {
  16208. mModule->EmitEnsureInstructionAt();
  16209. }
  16210. else if (!alreadyWritten)
  16211. {
  16212. //ptr = mModule->LoadValue(ptr);
  16213. BF_ASSERT(ptr.IsAddr());
  16214. convVal = mModule->LoadValue(convVal);
  16215. auto storeInst = mModule->mBfIRBuilder->CreateAlignedStore(convVal.mValue, ptr.mValue, ptr.mType->mAlign, mIsVolatileReference);
  16216. }
  16217. }
  16218. }
  16219. }
  16220. else
  16221. {
  16222. BF_ASSERT(convVal.mType->IsValuelessType());
  16223. }
  16224. mResult = convVal;
  16225. MarkResultAssigned();
  16226. }
  16227. void BfExprEvaluator::Visit(BfAssignmentExpression* assignExpr)
  16228. {
  16229. if (assignExpr->mLeft->IsA<BfTupleExpression>())
  16230. {
  16231. DoTupleAssignment(assignExpr);
  16232. return;
  16233. }
  16234. BfAutoParentNodeEntry autoParentNodeEntry(mModule, assignExpr);
  16235. BfTypedValue cascadeValue;
  16236. PerformAssignment(assignExpr, false, BfTypedValue(), &cascadeValue);
  16237. if (cascadeValue)
  16238. mResult = cascadeValue;
  16239. }
  16240. void BfExprEvaluator::Visit(BfParenthesizedExpression* parenExpr)
  16241. {
  16242. VisitChild(parenExpr->mExpression);
  16243. MakeResultAsValue();
  16244. }
  16245. void BfExprEvaluator::InitializedSizedArray(BfSizedArrayType* arrayType, BfTokenNode* openToken, const BfSizedArray<BfExpression*>& valueExprs, const BfSizedArray<BfTokenNode*>& commas, BfTokenNode* closeToken, BfTypedValue* receivingValue)
  16246. {
  16247. struct InitValue
  16248. {
  16249. BfTypedValue mValue;
  16250. bool mIsUninitialized;
  16251. bool mIsDefaultInitializer;
  16252. bool mIsDeferred;
  16253. InitValue()
  16254. {
  16255. mIsUninitialized = false;
  16256. mIsDefaultInitializer = false;
  16257. mIsDeferred = false;
  16258. }
  16259. };
  16260. SizedArray<InitValue, 8> values;
  16261. {
  16262. //bool hasFailed = false;
  16263. HashSet<int> failedAt;
  16264. bool isAllConst = true;
  16265. //bool endUninitialzied = false;
  16266. int depth = 0;
  16267. std::function<void(BfSizedArrayType*, BfTokenNode* openToken, const BfSizedArray<BfExpression*>&, const BfSizedArray<BfTokenNode*>&, BfTokenNode*, bool)>
  16268. _GetValues = [&](BfSizedArrayType* checkArrayType, BfTokenNode* openToken, const BfSizedArray<BfExpression*>& valueExprs, const BfSizedArray<BfTokenNode*>& commas, BfTokenNode* closeToken, bool ignore)
  16269. {
  16270. int64 initCountDiff = (int)valueExprs.size() - checkArrayType->mElementCount;
  16271. if ((initCountDiff != 0) && (!valueExprs.IsEmpty()) && (!failedAt.Contains(depth)))
  16272. {
  16273. if (checkArrayType->mElementCount == -1)
  16274. {
  16275. // mModule->Fail("Initializers not supported for unknown-sized arrays", valueExprs[0]);
  16276. // failedAt.Add(depth);
  16277. }
  16278. else if (initCountDiff > 0)
  16279. {
  16280. mModule->Fail(StrFormat("Too many initializers, expected %d fewer", initCountDiff), valueExprs[BF_MAX((int)checkArrayType->mElementCount, 0)]);
  16281. failedAt.Add(depth);
  16282. }
  16283. else
  16284. {
  16285. // If it ends with ", ?) or ",)" then allow unsized
  16286. if (((valueExprs.size() == 0) || (BfNodeDynCast<BfUninitializedExpression>(valueExprs.back()) == NULL)) &&
  16287. ((commas.size() < valueExprs.size()) || (valueExprs.size() == 0)))
  16288. {
  16289. BfAstNode* refNode = closeToken;
  16290. if ((refNode == NULL) && (mModule->mParentNodeEntry != NULL))
  16291. refNode = mModule->mParentNodeEntry->mNode;
  16292. BF_ASSERT(refNode != NULL);
  16293. mModule->Fail(StrFormat("Too few initializer, expected %d more", -initCountDiff), refNode);
  16294. failedAt.Add(depth);
  16295. }
  16296. }
  16297. }
  16298. for (int idx = 0; idx < BF_MAX(checkArrayType->mElementCount, valueExprs.size()); idx++)
  16299. {
  16300. BfTypedValue elementValue;
  16301. bool deferredValue = false;
  16302. BfExpression* expr = NULL;
  16303. if (idx < (int)valueExprs.size())
  16304. {
  16305. expr = valueExprs[idx];
  16306. if (expr == NULL)
  16307. {
  16308. if (idx == 0)
  16309. mModule->FailAfter("Expression expected", openToken);
  16310. else
  16311. mModule->FailAfter("Expression expected", commas[idx - 1]);
  16312. }
  16313. if ((BfNodeDynCastExact<BfUninitializedExpression>(expr) != NULL) && (idx == (int)commas.size()))
  16314. {
  16315. isAllConst = false;
  16316. break;
  16317. }
  16318. if (checkArrayType->mElementType->IsSizedArray())
  16319. {
  16320. if (auto arrayInitExpr = BfNodeDynCast<BfTupleExpression>(expr))
  16321. {
  16322. depth++;
  16323. _GetValues((BfSizedArrayType*)checkArrayType->mElementType, arrayInitExpr->mOpenParen, arrayInitExpr->mValues, arrayInitExpr->mCommas, arrayInitExpr->mCloseParen, ignore);
  16324. depth--;
  16325. continue;
  16326. }
  16327. else if (auto arrayInitExpr = BfNodeDynCast<BfCollectionInitializerExpression>(expr))
  16328. {
  16329. depth++;
  16330. _GetValues((BfSizedArrayType*)checkArrayType->mElementType, arrayInitExpr->mOpenBrace, arrayInitExpr->mValues, arrayInitExpr->mCommas, arrayInitExpr->mCloseBrace, ignore);
  16331. depth--;
  16332. continue;
  16333. }
  16334. else if (auto parenExpr = BfNodeDynCast<BfParenthesizedExpression>(expr))
  16335. {
  16336. depth++;
  16337. SizedArray<BfExpression*, 1> values;
  16338. values.Add(parenExpr->mExpression);
  16339. SizedArray<BfTokenNode*, 1> commas;
  16340. _GetValues((BfSizedArrayType*)checkArrayType->mElementType, parenExpr->mOpenParen, values, commas, parenExpr->mCloseParen, ignore);
  16341. depth--;
  16342. continue;
  16343. }
  16344. }
  16345. if (expr != NULL)
  16346. {
  16347. auto evalFlags = (BfEvalExprFlags)(mBfEvalExprFlags & BfEvalExprFlags_InheritFlags);
  16348. bool tryDefer = false;
  16349. if ((checkArrayType->IsComposite()) &&
  16350. ((expr->IsA<BfInvocationExpression>()) || (expr->IsExact<BfTupleExpression>())))
  16351. {
  16352. // We evaluate with a new scope because this expression may create variables that we don't want to be visible to other
  16353. // non-deferred evaluations (since the value may actually be a FakeVal)
  16354. SetAndRestoreValue<bool> prevIgnoreWrites(mModule->mBfIRBuilder->mIgnoreWrites, true);
  16355. elementValue = mModule->CreateValueFromExpression(expr, checkArrayType->mElementType, (BfEvalExprFlags)(evalFlags | BfEvalExprFlags_CreateConditionalScope));
  16356. deferredValue = !prevIgnoreWrites.mPrevVal && elementValue.mValue.IsFake();
  16357. }
  16358. else
  16359. {
  16360. elementValue = mModule->CreateValueFromExpression(expr, checkArrayType->mElementType, evalFlags);
  16361. }
  16362. if (!elementValue)
  16363. elementValue = mModule->GetDefaultTypedValue(checkArrayType->mElementType);
  16364. if ((!elementValue) || (!CheckAllowValue(elementValue, expr)))
  16365. elementValue = mModule->GetDefaultTypedValue(checkArrayType->mElementType);
  16366. // For now, we can't properly create const-valued non-size-aligned composites
  16367. // if (checkArrayType->mElementType->NeedsExplicitAlignment())
  16368. // isAllConst = false;
  16369. if (!elementValue.mValue.IsConst())
  16370. isAllConst = false;
  16371. if (elementValue.IsAddr())
  16372. isAllConst = false;
  16373. InitValue initValue;
  16374. initValue.mValue = elementValue;
  16375. initValue.mIsDeferred = deferredValue;
  16376. values.push_back(initValue);
  16377. }
  16378. }
  16379. }
  16380. };
  16381. int valueIdx = 0;
  16382. std::function<void(BfTypedValue, BfTokenNode* openToken, const BfSizedArray<BfExpression*>&, const BfSizedArray<BfTokenNode*>&, BfTokenNode*)>
  16383. _CreateMemArray = [&](BfTypedValue arrayValue, BfTokenNode* openToken, const BfSizedArray<BfExpression*>& valueExprs, const BfSizedArray<BfTokenNode*>& commas, BfTokenNode* closeToken)
  16384. {
  16385. BF_ASSERT(arrayValue.mType->IsSizedArray());
  16386. auto checkArrayType = (BfSizedArrayType*)arrayValue.mType;
  16387. int valIdx = 0;
  16388. bool hasUninit = false;
  16389. for (int idx = 0; idx < checkArrayType->mElementCount; idx++)
  16390. {
  16391. BfExpression* expr = NULL;
  16392. BfTypedValue elementValue;
  16393. if (idx >= (int)valueExprs.size())
  16394. break;
  16395. expr = valueExprs[idx];
  16396. if ((BfNodeDynCastExact<BfUninitializedExpression>(expr) != NULL) && (idx == (int)commas.size()))
  16397. {
  16398. hasUninit = true;
  16399. break;
  16400. }
  16401. BfIRValue elemPtrValue = mModule->CreateIndexedValue(checkArrayType->mElementType, arrayValue.mValue, valIdx, true);
  16402. valIdx++;
  16403. if (checkArrayType->mElementType->IsSizedArray())
  16404. {
  16405. if (auto arrayInitExpr = BfNodeDynCast<BfTupleExpression>(expr))
  16406. {
  16407. _CreateMemArray(BfTypedValue(elemPtrValue, checkArrayType->mElementType, true), arrayInitExpr->mOpenParen, arrayInitExpr->mValues, arrayInitExpr->mCommas, arrayInitExpr->mCloseParen);
  16408. continue;
  16409. }
  16410. else if (auto arrayInitExpr = BfNodeDynCast<BfCollectionInitializerExpression>(expr))
  16411. {
  16412. _CreateMemArray(BfTypedValue(elemPtrValue, checkArrayType->mElementType, true), arrayInitExpr->mOpenBrace, arrayInitExpr->mValues, arrayInitExpr->mCommas, arrayInitExpr->mCloseBrace);
  16413. continue;
  16414. }
  16415. else if (auto parenExpr = BfNodeDynCast<BfParenthesizedExpression>(expr))
  16416. {
  16417. depth++;
  16418. SizedArray<BfExpression*, 1> values;
  16419. values.Add(parenExpr->mExpression);
  16420. SizedArray<BfTokenNode*, 1> commas;
  16421. _CreateMemArray(BfTypedValue(elemPtrValue, checkArrayType->mElementType, true), parenExpr->mOpenParen, values, commas, parenExpr->mCloseParen);
  16422. depth--;
  16423. continue;
  16424. }
  16425. }
  16426. if (expr != NULL)
  16427. {
  16428. InitValue initValue = values[valueIdx++];
  16429. elementValue = initValue.mValue;
  16430. if (initValue.mIsDeferred)
  16431. {
  16432. BfTypedValue elemePtrTypedVal = BfTypedValue(elemPtrValue, checkArrayType->mElementType, BfTypedValueKind_Addr);
  16433. BfExprEvaluator exprEvaluator(mModule);
  16434. exprEvaluator.mExpectingType = checkArrayType->mElementType;
  16435. exprEvaluator.mReceivingValue = &elemePtrTypedVal;
  16436. exprEvaluator.Evaluate(expr);
  16437. exprEvaluator.GetResult();
  16438. if (exprEvaluator.mReceivingValue == NULL)
  16439. {
  16440. // We wrote directly to the array in-place, we're done with this element
  16441. continue;
  16442. }
  16443. elementValue = exprEvaluator.mResult;
  16444. elementValue = mModule->Cast(expr, elementValue, checkArrayType->mElementType);
  16445. if (!elementValue)
  16446. {
  16447. mModule->AssertErrorState();
  16448. continue;
  16449. }
  16450. }
  16451. elementValue = mModule->LoadValue(elementValue);
  16452. mModule->mBfIRBuilder->CreateAlignedStore(elementValue.mValue, elemPtrValue, checkArrayType->mElementType->mAlign);
  16453. }
  16454. }
  16455. int fillCount = (int)(checkArrayType->mElementCount - valIdx);
  16456. if (fillCount > 0)
  16457. {
  16458. BfIRValue elemPtrValue = mModule->CreateIndexedValue(checkArrayType->mElementType, arrayValue.mValue, valIdx, true);
  16459. if (hasUninit)
  16460. {
  16461. if (!mModule->IsOptimized())
  16462. {
  16463. int setSize = std::min(checkArrayType->mElementType->mSize, 128); // Keep it to a reasonable number of bytes to trash
  16464. mModule->mBfIRBuilder->CreateMemSet(elemPtrValue, mModule->mBfIRBuilder->CreateConst(BfTypeCode_Int8, 0xCC),
  16465. mModule->GetConstValue(setSize), checkArrayType->mElementType->mAlign);
  16466. }
  16467. }
  16468. else
  16469. {
  16470. int setSize = (int)((checkArrayType->mElementType->GetStride() * (fillCount - 1)) + checkArrayType->mElementType->mSize);
  16471. if (setSize >= 0)
  16472. {
  16473. mModule->mBfIRBuilder->CreateMemSet(elemPtrValue, mModule->mBfIRBuilder->CreateConst(BfTypeCode_Int8, 0),
  16474. mModule->GetConstValue(setSize), checkArrayType->mElementType->mAlign);
  16475. }
  16476. }
  16477. }
  16478. };
  16479. std::function<BfIRValue(BfTypedValue, BfTokenNode*, const BfSizedArray<BfExpression*>&, const BfSizedArray<BfTokenNode*>&, BfTokenNode*)>
  16480. _CreateConstArray = [&](BfTypedValue arrayValue, BfTokenNode* openToken, const BfSizedArray<BfExpression*>& valueExprs, const BfSizedArray<BfTokenNode*>& commas, BfTokenNode* closeToken)
  16481. {
  16482. SizedArray<BfIRValue, 8> members;
  16483. BF_ASSERT(arrayValue.mType->IsSizedArray());
  16484. auto checkArrayType = (BfSizedArrayType*)arrayValue.mType;
  16485. int valIdx = 0;
  16486. for (int idx = 0; idx < checkArrayType->mElementCount; idx++)
  16487. {
  16488. BfTypedValue elementValue;
  16489. if (idx >= (int)valueExprs.size())
  16490. break;
  16491. auto expr = valueExprs[idx];
  16492. if (expr == NULL)
  16493. continue;
  16494. valIdx++;
  16495. if (checkArrayType->mElementType->IsSizedArray())
  16496. {
  16497. if (auto arrayInitExpr = BfNodeDynCast<BfTupleExpression>(expr))
  16498. {
  16499. members.push_back(_CreateConstArray(checkArrayType->mElementType, arrayInitExpr->mOpenParen, arrayInitExpr->mValues, arrayInitExpr->mCommas, arrayInitExpr->mCloseParen));
  16500. continue;
  16501. }
  16502. else if (auto arrayInitExpr = BfNodeDynCast<BfCollectionInitializerExpression>(expr))
  16503. {
  16504. members.push_back(_CreateConstArray(checkArrayType->mElementType, arrayInitExpr->mOpenBrace, arrayInitExpr->mValues, arrayInitExpr->mCommas, arrayInitExpr->mCloseBrace));
  16505. continue;
  16506. }
  16507. else if (auto parenExpr = BfNodeDynCast<BfParenthesizedExpression>(expr))
  16508. {
  16509. depth++;
  16510. SizedArray<BfExpression*, 1> values;
  16511. values.Add(parenExpr->mExpression);
  16512. SizedArray<BfTokenNode*, 1> commas;
  16513. members.push_back(_CreateConstArray(checkArrayType->mElementType, parenExpr->mOpenParen, values, commas, parenExpr->mCloseParen));
  16514. depth--;
  16515. continue;
  16516. }
  16517. }
  16518. InitValue initValue = values[valueIdx++];
  16519. BF_ASSERT(!initValue.mIsUninitialized);
  16520. elementValue = initValue.mValue;
  16521. members.push_back(elementValue.mValue);
  16522. }
  16523. int fillCount = (int)(checkArrayType->mElementCount - valIdx);
  16524. if (fillCount > 0)
  16525. {
  16526. // We just need to insert one default value, it will be duplicated as needed into the backend
  16527. auto defaultVal = mModule->GetDefaultTypedValue(checkArrayType->GetUnderlyingType());
  16528. BF_ASSERT(defaultVal.mValue.IsConst());
  16529. members.push_back(defaultVal.mValue);
  16530. }
  16531. auto allocArrayType = checkArrayType;
  16532. if (checkArrayType->IsUndefSizedArray())
  16533. allocArrayType = mModule->CreateSizedArrayType(checkArrayType->GetUnderlyingType(), (int)members.size());
  16534. return mModule->mBfIRBuilder->CreateConstAgg(mModule->mBfIRBuilder->MapType(checkArrayType), members);
  16535. };
  16536. _GetValues(arrayType, openToken, valueExprs, commas, closeToken, false);
  16537. if (!failedAt.IsEmpty())
  16538. {
  16539. mResult = mModule->GetDefaultTypedValue(arrayType, false, BfDefaultValueKind_Addr);
  16540. return;
  16541. }
  16542. if (receivingValue != NULL)
  16543. {
  16544. BF_ASSERT(receivingValue->mType == arrayType);
  16545. BF_ASSERT(receivingValue->IsAddr());
  16546. mResult = *receivingValue;
  16547. _CreateMemArray(mResult, openToken, valueExprs, commas, closeToken);
  16548. }
  16549. else if (isAllConst)
  16550. {
  16551. mResult = BfTypedValue(_CreateConstArray(arrayType, openToken, valueExprs, commas, closeToken), arrayType, BfTypedValueKind_Value);
  16552. }
  16553. else
  16554. {
  16555. if ((mReceivingValue != NULL) && (mReceivingValue->mType == arrayType) && (mReceivingValue->IsAddr()))
  16556. {
  16557. mResult = *mReceivingValue;
  16558. mReceivingValue = NULL;
  16559. }
  16560. else
  16561. {
  16562. auto arrayValue = mModule->CreateAlloca(arrayType);
  16563. mResult = BfTypedValue(arrayValue, arrayType, BfTypedValueKind_TempAddr);
  16564. }
  16565. if (!arrayType->IsValuelessType())
  16566. _CreateMemArray(mResult, openToken, valueExprs, commas, closeToken);
  16567. }
  16568. }
  16569. }
  16570. void BfExprEvaluator::Visit(BfTupleExpression* tupleExpr)
  16571. {
  16572. BfTypeInstance* tupleType = NULL;
  16573. bool hadFullMatch = false;
  16574. if ((mExpectingType != NULL) && (mExpectingType->IsTuple()))
  16575. {
  16576. tupleType = (BfTypeInstance*)mExpectingType;
  16577. hadFullMatch = tupleType->mFieldInstances.size() == tupleExpr->mValues.size();
  16578. }
  16579. struct InitValue
  16580. {
  16581. BfTypedValue mValue;
  16582. bool mIsUninitialized;
  16583. bool mIsDefaultInitializer;
  16584. bool mIsDeferred;
  16585. InitValue()
  16586. {
  16587. mIsUninitialized = false;
  16588. mIsDefaultInitializer = false;
  16589. mIsDeferred = false;
  16590. }
  16591. };
  16592. SizedArray<BfTypedValue, 2> typedValues;
  16593. if ((tupleExpr->mCommas.size() != 0) && (tupleExpr->mCommas.size() >= tupleExpr->mValues.size()))
  16594. {
  16595. // We would normally give this error during syntax parsing, but a TupleExpression can be an array initializer
  16596. mModule->FailAfter("Expression expected", tupleExpr->mCommas.back());
  16597. }
  16598. for (int valueIdx = 0; valueIdx < (int)tupleExpr->mValues.size(); valueIdx++)
  16599. {
  16600. BfExpression* valueExpr = tupleExpr->mValues[valueIdx];
  16601. BfType* fieldType = NULL;
  16602. BfFieldInstance* fieldInstance = NULL;
  16603. if (tupleType != NULL)
  16604. {
  16605. if (valueIdx < (int)tupleType->mFieldInstances.size())
  16606. {
  16607. fieldInstance = (BfFieldInstance*)&tupleType->mFieldInstances[valueIdx];
  16608. fieldType = fieldInstance->GetResolvedType();
  16609. if (fieldType->IsVoid())
  16610. {
  16611. typedValues.push_back(BfTypedValue());
  16612. continue;
  16613. }
  16614. if (fieldType->IsVar())
  16615. {
  16616. hadFullMatch = false;
  16617. fieldType = NULL;
  16618. }
  16619. }
  16620. }
  16621. bool tryDefer = false;
  16622. if (((fieldType == NULL) || (fieldType->IsComposite())) &&
  16623. ((valueExpr->IsA<BfInvocationExpression>()) || (valueExpr->IsExact<BfTupleExpression>())))
  16624. {
  16625. tryDefer = true;
  16626. }
  16627. SetAndRestoreValue<bool> prevIgnoreWrites(mModule->mBfIRBuilder->mIgnoreWrites, mModule->mBfIRBuilder->mIgnoreWrites || tryDefer);
  16628. BfTypedValue value = mModule->CreateValueFromExpression(valueExpr, fieldType);
  16629. if (!value)
  16630. {
  16631. if (fieldType != NULL)
  16632. value = mModule->GetDefaultTypedValue(fieldType);
  16633. else
  16634. value = mModule->GetDefaultTypedValue(mModule->mContext->mBfObjectType);
  16635. }
  16636. if ((fieldInstance != NULL) && (!fieldInstance->GetFieldDef()->IsUnnamedTupleField()) && (valueIdx < (int)tupleExpr->mNames.size()))
  16637. {
  16638. auto checkName = tupleExpr->mNames[valueIdx];
  16639. if (checkName != NULL)
  16640. {
  16641. if (checkName->ToString() != fieldInstance->GetFieldDef()->mName)
  16642. hadFullMatch = false;
  16643. }
  16644. }
  16645. value = mModule->LoadValue(value);
  16646. typedValues.push_back(value);
  16647. }
  16648. if (!hadFullMatch)
  16649. {
  16650. BfTypeVector fieldTypes;
  16651. Array<String> fieldNames;
  16652. HashSet<String> fieldNameSet;
  16653. for (auto typedVal : typedValues)
  16654. {
  16655. auto type = typedVal.mType;
  16656. if (type != NULL)
  16657. fieldTypes.push_back(type);
  16658. else
  16659. fieldTypes.push_back(mModule->mContext->mBfObjectType);
  16660. }
  16661. for (BfTupleNameNode* requestedName : tupleExpr->mNames)
  16662. {
  16663. if (requestedName == NULL)
  16664. fieldNames.push_back("");
  16665. else
  16666. {
  16667. auto fieldName = requestedName->mNameNode->ToString();
  16668. if (!fieldNameSet.TryAdd(fieldName, NULL))
  16669. {
  16670. mModule->Fail(StrFormat("A field named '%s' has already been declared", fieldName.c_str()), requestedName->mNameNode);
  16671. }
  16672. fieldNames.push_back(fieldName);
  16673. }
  16674. }
  16675. tupleType = mModule->CreateTupleType(fieldTypes, fieldNames);
  16676. }
  16677. mModule->mBfIRBuilder->PopulateType(tupleType);
  16678. BfIRValue curTupleValue;
  16679. if ((mReceivingValue != NULL) && (mReceivingValue->mType == tupleType) && (mReceivingValue->IsAddr()))
  16680. {
  16681. mResult = *mReceivingValue;
  16682. mReceivingValue = NULL;
  16683. curTupleValue = mResult.mValue;
  16684. }
  16685. else
  16686. {
  16687. int valueIdx = -1;
  16688. bool isExactConst = true;
  16689. for (int fieldIdx = 0; fieldIdx < (int)tupleType->mFieldInstances.size(); fieldIdx++)
  16690. {
  16691. BfFieldInstance* fieldInstance = &tupleType->mFieldInstances[fieldIdx];
  16692. if (fieldInstance->mDataIdx < 0)
  16693. continue;
  16694. ++valueIdx;
  16695. auto typedValue = typedValues[valueIdx];
  16696. if (typedValue.mType != fieldInstance->mResolvedType)
  16697. {
  16698. isExactConst = false;
  16699. break;
  16700. }
  16701. if (!typedValue.mValue.IsConst())
  16702. {
  16703. isExactConst = false;
  16704. break;
  16705. }
  16706. }
  16707. if (isExactConst)
  16708. {
  16709. mModule->PopulateType(tupleType);
  16710. Array<BfIRValue> irValues;
  16711. irValues.Resize(typedValues.mSize + 1);
  16712. irValues[0] = mModule->mBfIRBuilder->CreateConstAggZero(mModule->mBfIRBuilder->MapType(tupleType->mBaseType));
  16713. for (int fieldIdx = 0; fieldIdx < (int)tupleType->mFieldInstances.size(); fieldIdx++)
  16714. {
  16715. BfFieldInstance* fieldInstance = &tupleType->mFieldInstances[fieldIdx];
  16716. if (fieldInstance->mDataIdx < 0)
  16717. continue;
  16718. irValues[fieldInstance->mDataIdx] = typedValues[fieldIdx].mValue;
  16719. }
  16720. for (auto& val : irValues)
  16721. {
  16722. if (!val)
  16723. val = mModule->mBfIRBuilder->CreateConstArrayZero(0);
  16724. }
  16725. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConstAgg(mModule->mBfIRBuilder->MapType(tupleType), irValues), tupleType);
  16726. return;
  16727. }
  16728. curTupleValue = mModule->CreateAlloca(tupleType);
  16729. mResultIsTempComposite = true;
  16730. mResult = BfTypedValue(curTupleValue, tupleType, BfTypedValueKind_TempAddr);
  16731. }
  16732. int valueIdx = -1;
  16733. for (int fieldIdx = 0; fieldIdx < (int)tupleType->mFieldInstances.size(); fieldIdx++)
  16734. {
  16735. BfFieldInstance* fieldInstance = &tupleType->mFieldInstances[fieldIdx];
  16736. ++valueIdx;
  16737. if (fieldInstance->mResolvedType->IsValuelessType())
  16738. continue;
  16739. auto typedVal = typedValues[valueIdx];
  16740. if (!typedVal)
  16741. {
  16742. mModule->AssertErrorState();
  16743. continue;
  16744. }
  16745. if (fieldInstance->mDataIdx >= 0)
  16746. {
  16747. auto memberVal = mModule->mBfIRBuilder->CreateInBoundsGEP(curTupleValue, 0, fieldInstance->mDataIdx);
  16748. if ((!mModule->mBfIRBuilder->mIgnoreWrites) && (typedVal.mValue.IsFake()))
  16749. {
  16750. // Value was deferred. Allow us to try to init in place
  16751. BfExpression* valueExpr = tupleExpr->mValues[valueIdx];
  16752. BfTypedValue memberPtrTypedVal = BfTypedValue(memberVal, fieldInstance->mResolvedType, BfTypedValueKind_Addr);
  16753. BfExprEvaluator exprEvaluator(mModule);
  16754. exprEvaluator.mExpectingType = fieldInstance->mResolvedType;
  16755. exprEvaluator.mReceivingValue = &memberPtrTypedVal;
  16756. exprEvaluator.Evaluate(valueExpr);
  16757. exprEvaluator.GetResult();
  16758. if (exprEvaluator.mReceivingValue == NULL)
  16759. {
  16760. // We wrote directly to the array in-place, we're done with this element
  16761. continue;
  16762. }
  16763. typedVal = exprEvaluator.mResult;
  16764. typedVal = mModule->Cast(valueExpr, typedVal, fieldInstance->mResolvedType);
  16765. if (!typedVal)
  16766. {
  16767. mModule->AssertErrorState();
  16768. continue;
  16769. }
  16770. typedVal = mModule->LoadValue(typedVal);
  16771. }
  16772. if (typedVal.mType->IsVar())
  16773. {
  16774. // Do nothing
  16775. }
  16776. else if (typedVal.IsSplat())
  16777. mModule->AggregateSplatIntoAddr(typedVal, memberVal);
  16778. else
  16779. mModule->mBfIRBuilder->CreateStore(typedVal.mValue, memberVal);
  16780. }
  16781. }
  16782. }
  16783. BfTypedValue BfExprEvaluator::SetupNullConditional(BfTypedValue thisValue, BfTokenNode* dotToken)
  16784. {
  16785. bool isStaticLookup = (!thisValue) ||
  16786. ((!thisValue.mType->IsValuelessType()) && (!thisValue.mValue));
  16787. if (isStaticLookup)
  16788. {
  16789. mModule->Fail("Null conditional reference not valid for static field references", dotToken);
  16790. return thisValue;
  16791. }
  16792. auto opResult = PerformUnaryOperation_TryOperator(thisValue, NULL, BfUnaryOp_NullConditional, dotToken, BfUnaryOpFlag_None);
  16793. if (opResult)
  16794. thisValue = opResult;
  16795. if (thisValue.mType->IsGenericParam())
  16796. {
  16797. bool isValid = false;
  16798. auto genericParams = mModule->GetGenericParamInstance((BfGenericParamType*)thisValue.mType);
  16799. if (genericParams->mTypeConstraint != NULL)
  16800. {
  16801. if ((genericParams->mTypeConstraint->IsNullable()) ||
  16802. (genericParams->mTypeConstraint->IsPointer()) ||
  16803. (genericParams->mTypeConstraint->IsObjectOrInterface()))
  16804. isValid = true;
  16805. }
  16806. if ((genericParams->mGenericParamFlags & (BfGenericParamFlag_Var | BfGenericParamFlag_StructPtr | BfGenericParamFlag_Class)) != 0)
  16807. isValid = true;
  16808. if (isValid)
  16809. return thisValue;
  16810. }
  16811. if (thisValue.mType->IsNullable())
  16812. {
  16813. // Success
  16814. }
  16815. else if ((thisValue.mType->IsPointer()) || (thisValue.mType->IsObjectOrInterface()))
  16816. {
  16817. // Also good
  16818. }
  16819. else
  16820. {
  16821. mModule->Warn(0, StrFormat("Null conditional reference is unnecessary since value type '%s' can never be null", mModule->TypeToString(thisValue.mType).c_str()), dotToken);
  16822. return thisValue;
  16823. }
  16824. thisValue = mModule->LoadValue(thisValue);
  16825. BfPendingNullConditional* pendingNullCond = mModule->mCurMethodState->mPendingNullConditional;
  16826. if (pendingNullCond == NULL)
  16827. {
  16828. pendingNullCond = new BfPendingNullConditional();
  16829. mModule->mCurMethodState->mPendingNullConditional = pendingNullCond;
  16830. }
  16831. if (!pendingNullCond->mPrevBB)
  16832. pendingNullCond->mPrevBB = mModule->mBfIRBuilder->GetInsertBlock();
  16833. if (!pendingNullCond->mDoneBB)
  16834. pendingNullCond->mDoneBB = mModule->mBfIRBuilder->CreateBlock("nullCond.done");
  16835. // We will in the br to checkBB later
  16836. if (!pendingNullCond->mCheckBB)
  16837. {
  16838. pendingNullCond->mCheckBB = mModule->mBfIRBuilder->CreateBlock("nullCond.check");
  16839. mModule->AddBasicBlock(pendingNullCond->mCheckBB);
  16840. }
  16841. BfIRValue isNotNull;
  16842. if (thisValue.mType->IsNullable())
  16843. {
  16844. BfTypeInstance* nullableType = (BfTypeInstance*)thisValue.mType->ToTypeInstance();
  16845. auto elementType = nullableType->GetUnderlyingType();
  16846. if (elementType->IsValuelessType())
  16847. {
  16848. thisValue = mModule->MakeAddressable(thisValue);
  16849. BfIRValue hasValuePtr = mModule->mBfIRBuilder->CreateInBoundsGEP(thisValue.mValue, 0, 1); // mHasValue
  16850. isNotNull = mModule->mBfIRBuilder->CreateLoad(hasValuePtr);
  16851. thisValue = BfTypedValue(mModule->mBfIRBuilder->GetFakeVal(), elementType, true);
  16852. }
  16853. else
  16854. {
  16855. thisValue = mModule->MakeAddressable(thisValue);
  16856. BfIRValue hasValuePtr = mModule->mBfIRBuilder->CreateInBoundsGEP(thisValue.mValue, 0, 2); // mHasValue
  16857. isNotNull = mModule->mBfIRBuilder->CreateLoad(hasValuePtr);
  16858. BfIRValue valuePtr = mModule->mBfIRBuilder->CreateInBoundsGEP(thisValue.mValue, 0, 1); // mValue
  16859. thisValue = BfTypedValue(valuePtr, elementType, true);
  16860. }
  16861. }
  16862. else
  16863. isNotNull = mModule->mBfIRBuilder->CreateIsNotNull(thisValue.mValue);
  16864. BfIRBlock notNullBB = mModule->mBfIRBuilder->CreateBlock("nullCond.notNull");
  16865. pendingNullCond->mNotNullBBs.Add(notNullBB);
  16866. mModule->mBfIRBuilder->CreateCondBr(isNotNull, notNullBB, pendingNullCond->mDoneBB);
  16867. mModule->AddBasicBlock(notNullBB);
  16868. return thisValue;
  16869. }
  16870. void BfExprEvaluator::CheckDotToken(BfTokenNode* tokenNode)
  16871. {
  16872. if ((tokenNode != NULL) && (tokenNode->mToken == BfToken_DotDot))
  16873. mModule->Fail("Unexpected cascade operation. Chaining can only be used for method invocations", tokenNode);
  16874. }
  16875. void BfExprEvaluator::DoMemberReference(BfMemberReferenceExpression* memberRefExpr, BfTypedValue* outCascadeValue)
  16876. {
  16877. CheckDotToken(memberRefExpr->mDotToken);
  16878. BfAttributeState attributeState;
  16879. attributeState.mTarget = (BfAttributeTargets)(BfAttributeTargets_MemberAccess);
  16880. String findName;
  16881. BfAstNode* nameRefNode = memberRefExpr->mMemberName;
  16882. if (auto attrIdentifierExpr = BfNodeDynCast<BfAttributedIdentifierNode>(memberRefExpr->mMemberName))
  16883. {
  16884. nameRefNode = attrIdentifierExpr->mIdentifier;
  16885. // Don't validate
  16886. attributeState.mCustomAttributes = mModule->GetCustomAttributes(attrIdentifierExpr->mAttributes, BfAttributeTargets_SkipValidate);
  16887. if (nameRefNode != NULL)
  16888. findName = attrIdentifierExpr->mIdentifier->ToString();
  16889. }
  16890. else if (memberRefExpr->mMemberName != NULL)
  16891. findName = memberRefExpr->mMemberName->ToString();
  16892. else if (memberRefExpr->mDotToken != NULL)
  16893. mModule->FailAfter("Member name expected", memberRefExpr->mDotToken);
  16894. defer
  16895. (
  16896. if (attributeState.mCustomAttributes != NULL)
  16897. {
  16898. if (mPropDef != NULL)
  16899. attributeState.mTarget = (BfAttributeTargets)(attributeState.mTarget | BfAttributeTargets_Invocation);
  16900. mModule->ValidateCustomAttributes(attributeState.mCustomAttributes, attributeState.mTarget);
  16901. }
  16902. );
  16903. SetAndRestoreValue<BfAttributeState*> prevAttributeState(mModule->mAttributeState, &attributeState);
  16904. BfTypeInstance* expectingTypeInst = NULL;
  16905. if (mExpectingType != NULL)
  16906. {
  16907. expectingTypeInst = mExpectingType->ToTypeInstance();
  16908. if (mExpectingType->IsPointer())
  16909. expectingTypeInst = mExpectingType->GetUnderlyingType()->ToTypeInstance();
  16910. else if (mExpectingType->IsNullable())
  16911. expectingTypeInst = mExpectingType->GetUnderlyingType()->ToTypeInstance();
  16912. else if (mExpectingType->IsConstExprValue())
  16913. expectingTypeInst = mExpectingType->GetUnderlyingType()->ToTypeInstance();
  16914. else if (mExpectingType->IsGenericParam())
  16915. {
  16916. auto genericParam = mModule->GetGenericParamInstance((BfGenericParamType*)mExpectingType);
  16917. if (genericParam->mTypeConstraint != NULL)
  16918. expectingTypeInst = genericParam->mTypeConstraint->ToTypeInstance();
  16919. }
  16920. }
  16921. BfAutoComplete* autoComplete = GetAutoComplete();
  16922. if (autoComplete != NULL)
  16923. {
  16924. SetAndRestoreValue<bool> prevFriendSet(autoComplete->mHasFriendSet, (attributeState.mCustomAttributes != NULL) && (attributeState.mCustomAttributes->Contains(mModule->mCompiler->mFriendAttributeTypeDef)));
  16925. if (memberRefExpr->mTarget == NULL)
  16926. {
  16927. String filter;
  16928. if ((mExpectingType != NULL) &&
  16929. (autoComplete->InitAutocomplete(memberRefExpr->mDotToken, memberRefExpr->mMemberName, filter)))
  16930. {
  16931. if (expectingTypeInst != NULL)
  16932. {
  16933. bool allowPrivate = expectingTypeInst == mModule->mCurTypeInstance;
  16934. if (expectingTypeInst->IsEnum())
  16935. autoComplete->AddEnumTypeMembers(expectingTypeInst, filter, false, allowPrivate);
  16936. autoComplete->AddSelfResultTypeMembers(expectingTypeInst, expectingTypeInst, filter, allowPrivate);
  16937. }
  16938. }
  16939. }
  16940. else
  16941. {
  16942. autoComplete->CheckMemberReference(memberRefExpr->mTarget, memberRefExpr->mDotToken, memberRefExpr->mMemberName, false, mExpectingType);
  16943. if (auto objCreateExpr = BfNodeDynCast<BfObjectCreateExpression>(memberRefExpr->mTarget))
  16944. {
  16945. // This handles a weird case where we have "obj a = new\nWhatever().Thing = 123;".
  16946. // That gets parsed as "Whatever()" being the type we want to create, and then referencing
  16947. // the "Thing" member of that new object.
  16948. //if (objCreateExpr->mArraySizeSpecifier == NULL)
  16949. CheckObjectCreateTypeRef(mExpectingType, objCreateExpr->mNewNode);
  16950. }
  16951. }
  16952. }
  16953. if (memberRefExpr->mTarget == NULL)
  16954. {
  16955. if (mExpectingType == NULL)
  16956. {
  16957. if (mModule->PreFail())
  16958. mModule->Fail("Unqualified dot syntax can only be used when the result type can be inferred", nameRefNode);
  16959. return;
  16960. }
  16961. if (expectingTypeInst == NULL)
  16962. {
  16963. if (mModule->PreFail())
  16964. mModule->Fail(StrFormat("Unqualified dot syntax cannot be used with type '%s'", mModule->TypeToString(mExpectingType).c_str()), nameRefNode);
  16965. return;
  16966. }
  16967. if (mExpectingType->IsVar())
  16968. {
  16969. mResult = mModule->GetDefaultTypedValue(mExpectingType);
  16970. return;
  16971. }
  16972. BfTypedValue expectingVal(expectingTypeInst);
  16973. mResult = LookupField(memberRefExpr->mMemberName, expectingVal, findName);
  16974. if ((mResult) || (mPropDef != NULL))
  16975. return;
  16976. }
  16977. bool isNullCondLookup = (memberRefExpr->mDotToken != NULL) && (memberRefExpr->mDotToken->GetToken() == BfToken_QuestionDot);
  16978. bool isCascade = ((memberRefExpr->mDotToken != NULL) && (memberRefExpr->mDotToken->GetToken() == BfToken_DotDot));
  16979. BfIdentifierNode* nameLeft = BfNodeDynCast<BfIdentifierNode>(memberRefExpr->mTarget);
  16980. BfIdentifierNode* nameRight = BfIdentifierCast(memberRefExpr->mMemberName);
  16981. if ((nameLeft != NULL) && (nameRight != NULL) && (!isNullCondLookup) && (!isCascade))
  16982. {
  16983. bool hadError = false;
  16984. LookupQualifiedName(memberRefExpr, nameLeft, nameRight, true, &hadError);
  16985. if ((mResult) || (mPropDef != NULL))
  16986. return;
  16987. if (hadError)
  16988. return;
  16989. LookupQualifiedStaticField(memberRefExpr, nameLeft, nameRight, false);
  16990. return;
  16991. }
  16992. BfTypedValue thisValue;
  16993. if (auto exprTarget = BfNodeDynCast<BfExpression>(memberRefExpr->mTarget))
  16994. {
  16995. if (auto typeOfExpr = BfNodeDynCast<BfTypeOfExpression>(memberRefExpr->mTarget))
  16996. {
  16997. if (auto nameIdentifer = BfNodeDynCast<BfIdentifierNode>(memberRefExpr->mMemberName))
  16998. {
  16999. if (LookupTypeProp(typeOfExpr, nameIdentifer))
  17000. return;
  17001. }
  17002. }
  17003. //Hm, not using VisitChild broke our ability to write to a field for a not-initialized local struct
  17004. VisitChild(memberRefExpr->mTarget);
  17005. GetResult();
  17006. thisValue = mResult;
  17007. if (!thisValue)
  17008. {
  17009. if (auto targetIdentifier = BfNodeDynCast<BfIdentifierNode>(exprTarget))
  17010. {
  17011. thisValue = BfTypedValue(mModule->ResolveTypeRef(targetIdentifier, NULL, BfPopulateType_Declaration));
  17012. }
  17013. }
  17014. if (!thisValue.HasType())
  17015. return;
  17016. //thisValue = mResult;
  17017. }
  17018. else if (auto typeRef = BfNodeDynCast<BfTypeReference>(memberRefExpr->mTarget))
  17019. {
  17020. // Look up static field
  17021. thisValue = BfTypedValue(ResolveTypeRef(typeRef));
  17022. }
  17023. if (nameRefNode == NULL)
  17024. {
  17025. mModule->AssertErrorState();
  17026. return;
  17027. }
  17028. if (isNullCondLookup)
  17029. thisValue = SetupNullConditional(thisValue, memberRefExpr->mDotToken);
  17030. mResult = LookupField(nameRefNode, thisValue, findName);
  17031. if ((!mResult) && (mPropDef == NULL))
  17032. {
  17033. if (thisValue.mType != NULL)
  17034. {
  17035. BfTypeInstance* typeInst = thisValue.mType->ToTypeInstance();
  17036. auto compiler = mModule->mCompiler;
  17037. if ((typeInst != NULL) && (compiler->IsAutocomplete()) && (compiler->mResolvePassData->mAutoComplete->CheckFixit(memberRefExpr->mMemberName)))
  17038. {
  17039. FixitAddMember(typeInst, mExpectingType, findName, !thisValue.mValue);
  17040. }
  17041. }
  17042. if ((!thisValue.mValue) && (thisValue.mType != NULL))
  17043. {
  17044. if (auto targetIdentifier = BfNodeDynCast<BfIdentifierNode>(memberRefExpr->mMemberName))
  17045. {
  17046. mResult.mType = mModule->ResolveInnerType(thisValue.mType, targetIdentifier, BfPopulateType_Declaration);
  17047. }
  17048. }
  17049. if ((memberRefExpr->mTarget == NULL) && (expectingTypeInst != NULL) && (autoComplete != NULL))
  17050. {
  17051. if (autoComplete->CheckFixit(memberRefExpr->mMemberName))
  17052. {
  17053. autoComplete->FixitAddCase(expectingTypeInst, memberRefExpr->mMemberName->ToString(), BfTypeVector());
  17054. }
  17055. }
  17056. if (mResult.mType == NULL)
  17057. {
  17058. if (mModule->PreFail())
  17059. {
  17060. if ((thisValue) && (thisValue.mType->IsPointer()) && (thisValue.mType->GetUnderlyingType()->IsObjectOrInterface()))
  17061. mModule->Fail(StrFormat("Members cannot be referenced on type '%s' because the type is a pointer to a reference type (ie: a double-reference).",
  17062. mModule->TypeToString(thisValue.mType).c_str()), nameRefNode);
  17063. else if (thisValue)
  17064. mModule->Fail(StrFormat("Unable to find member '%s' in '%s'", findName.c_str(), mModule->TypeToString(thisValue.mType).c_str()), nameRefNode);
  17065. else
  17066. mModule->Fail("Unable to find member", nameRefNode);
  17067. }
  17068. }
  17069. }
  17070. if ((isNullCondLookup) && (mPropDef == NULL))
  17071. mResult = GetResult();
  17072. if (isCascade)
  17073. {
  17074. if (outCascadeValue != NULL)
  17075. *outCascadeValue = thisValue;
  17076. else if (mModule->PreFail())
  17077. mModule->Fail("Unexpected cascade operation. Chaining can only be used for method invocations", memberRefExpr->mDotToken);
  17078. }
  17079. }
  17080. void BfExprEvaluator::Visit(BfMemberReferenceExpression* memberRefExpr)
  17081. {
  17082. DoMemberReference(memberRefExpr, NULL);
  17083. }
  17084. void BfExprEvaluator::Visit(BfIndexerExpression* indexerExpr)
  17085. {
  17086. BfTypedValue target;
  17087. bool wantStatic = false;
  17088. // Try first as a non-static indexer, then as a static indexer
  17089. for (int pass = 0; pass < 2; pass++)
  17090. {
  17091. ///
  17092. {
  17093. SetAndRestoreValue<BfEvalExprFlags> prevFlags(mBfEvalExprFlags, (BfEvalExprFlags)(mBfEvalExprFlags | BfEvalExprFlags_NoLookupError | BfEvalExprFlags_AllowBase), pass == 0);
  17094. VisitChild(indexerExpr->mTarget);
  17095. }
  17096. ResolveGenericType();
  17097. target = GetResult(true);
  17098. if (target)
  17099. break;
  17100. if (pass == 0)
  17101. {
  17102. SetAndRestoreValue<bool> prevIgnoreErrors(mModule->mIgnoreErrors, (mModule->mIgnoreErrors) || (pass == 0));
  17103. auto staticType = mModule->ResolveTypeRef(indexerExpr->mTarget, {});
  17104. if (staticType != NULL)
  17105. {
  17106. wantStatic = true;
  17107. target.mType = staticType;
  17108. break;
  17109. }
  17110. }
  17111. }
  17112. if (!target.HasType())
  17113. return;
  17114. BfCheckedKind checkedKind = BfCheckedKind_NotSet;
  17115. bool isInlined = false;
  17116. if ((mModule->mAttributeState != NULL) && (mModule->mAttributeState->mCustomAttributes != NULL))
  17117. {
  17118. if (mModule->mAttributeState->mCustomAttributes->Contains(mModule->mCompiler->mInlineAttributeTypeDef))
  17119. {
  17120. isInlined = true;
  17121. mModule->mAttributeState->mUsed = true;
  17122. }
  17123. if (mModule->mAttributeState->mCustomAttributes->Contains(mModule->mCompiler->mCheckedAttributeTypeDef))
  17124. {
  17125. checkedKind = BfCheckedKind_Checked;
  17126. mModule->mAttributeState->mUsed = true;
  17127. }
  17128. if (mModule->mAttributeState->mCustomAttributes->Contains(mModule->mCompiler->mUncheckedAttributeTypeDef))
  17129. {
  17130. checkedKind = BfCheckedKind_Unchecked;
  17131. mModule->mAttributeState->mUsed = true;
  17132. }
  17133. }
  17134. bool isNullCondLookup = (indexerExpr->mOpenBracket != NULL) && (indexerExpr->mOpenBracket->GetToken() == BfToken_QuestionLBracket);
  17135. if (isNullCondLookup)
  17136. target = SetupNullConditional(target, indexerExpr->mOpenBracket);
  17137. if (target.mType->IsVar())
  17138. {
  17139. mResult = BfTypedValue(mModule->GetDefaultValue(target.mType), target.mType, true);
  17140. return;
  17141. }
  17142. if (target.mType->IsTypeInstance())
  17143. {
  17144. mIndexerValues.clear();
  17145. SizedArray<BfExpression*, 2> argExprs;
  17146. BfSizedArray<BfExpression*> sizedArgExprs(indexerExpr->mArguments);
  17147. BfResolvedArgs argValues(&sizedArgExprs);
  17148. ResolveArgValues(argValues, (BfResolveArgsFlags)(BfResolveArgsFlag_DeferParamEval | BfResolveArgsFlag_FromIndexer));
  17149. //exprEvaluator.MatchMethod(elementExpr, NULL, initValue, false, false, "Add", argValues, NULL);
  17150. mIndexerValues = argValues.mResolvedArgs;
  17151. for (auto& val : mIndexerValues)
  17152. if (!val.mTypedValue)
  17153. val.mTypedValue = mModule->GetDefaultTypedValue(mModule->mContext->mBfObjectType);
  17154. BfMethodMatcher methodMatcher(indexerExpr->mTarget, mModule, "[]", mIndexerValues, NULL);
  17155. methodMatcher.mCheckedKind = checkedKind;
  17156. //methodMatcher.CheckType(target.mType->ToTypeInstance(), target, false);
  17157. BfMethodDef* methodDef = NULL;
  17158. auto startCheckTypeInst = target.mType->ToTypeInstance();
  17159. for (int pass = 0; pass < 2; pass++)
  17160. {
  17161. bool isFailurePass = pass == 1;
  17162. auto curCheckType = startCheckTypeInst;
  17163. while (curCheckType != NULL)
  17164. {
  17165. BfProtectionCheckFlags protectionCheckFlags = BfProtectionCheckFlag_None;
  17166. BfPropertyDef* foundProp = NULL;
  17167. BfTypeInstance* foundPropTypeInst = NULL;
  17168. int matchedIndexCount = 0;
  17169. curCheckType->mTypeDef->PopulateMemberSets();
  17170. BfMemberSetEntry* entry;
  17171. BfPropertyDef* matchedProp = NULL;
  17172. BfPropertyDef* nextProp = NULL;
  17173. if (curCheckType->mTypeDef->mPropertySet.TryGetWith(String("[]"), &entry))
  17174. nextProp = (BfPropertyDef*)entry->mMemberDef;
  17175. while (nextProp != NULL)
  17176. {
  17177. auto prop = nextProp;
  17178. nextProp = nextProp->mNextWithSameName;
  17179. //TODO: Match against setMethod (minus last param) if we have no 'get' method
  17180. for (auto checkMethod : prop->mMethods)
  17181. {
  17182. if (checkMethod->mMethodType != BfMethodType_PropertyGetter)
  17183. continue;
  17184. // For generic params - check interface constraints for an indexer, call that method
  17185. BF_ASSERT(!target.mType->IsGenericParam());
  17186. if (checkMethod->mIsStatic != wantStatic)
  17187. continue;
  17188. if (checkMethod->mExplicitInterface != NULL)
  17189. continue;
  17190. auto autoComplete = GetAutoComplete();
  17191. bool wasCapturingMethodMatchInfo = false;
  17192. if (autoComplete != NULL)
  17193. {
  17194. // Set to false to make sure we don't capture method match info from 'params' array creation
  17195. wasCapturingMethodMatchInfo = autoComplete->mIsCapturingMethodMatchInfo;
  17196. autoComplete->mIsCapturingMethodMatchInfo = false;
  17197. }
  17198. defer
  17199. (
  17200. if (autoComplete != NULL)
  17201. autoComplete->mIsCapturingMethodMatchInfo = wasCapturingMethodMatchInfo;
  17202. );
  17203. if ((!isFailurePass) && (!methodMatcher.WantsCheckMethod(protectionCheckFlags, startCheckTypeInst, curCheckType, checkMethod)))
  17204. continue;
  17205. if (!methodMatcher.IsMemberAccessible(curCheckType, checkMethod->mDeclaringType))
  17206. continue;
  17207. methodMatcher.mCheckedKind = checkedKind;
  17208. methodMatcher.mTarget = target;
  17209. methodMatcher.CheckMethod(startCheckTypeInst, curCheckType, checkMethod, false);
  17210. if ((methodMatcher.mBestMethodDef == checkMethod) ||
  17211. ((foundProp == NULL) && (methodMatcher.mBackupMethodDef == checkMethod)))
  17212. {
  17213. foundPropTypeInst = curCheckType;
  17214. foundProp = prop;
  17215. matchedIndexCount = (int)checkMethod->mParams.size();
  17216. }
  17217. }
  17218. }
  17219. if (foundProp != NULL)
  17220. {
  17221. mPropSrc = indexerExpr->mOpenBracket;
  17222. mPropDef = foundProp;
  17223. if (foundProp->mIsStatic)
  17224. {
  17225. mPropTarget = BfTypedValue(curCheckType);
  17226. }
  17227. else
  17228. {
  17229. if (target.mType != foundPropTypeInst)
  17230. mPropTarget = mModule->Cast(indexerExpr->mTarget, target, foundPropTypeInst);
  17231. else
  17232. mPropTarget = target;
  17233. }
  17234. mOrigPropTarget = mPropTarget;
  17235. if (isInlined)
  17236. mPropGetMethodFlags = (BfGetMethodInstanceFlags)(mPropGetMethodFlags | BfGetMethodInstanceFlag_ForceInline);
  17237. mPropCheckedKind = checkedKind;
  17238. if ((target.IsBase()) && (mPropDef->IsVirtual()))
  17239. mPropDefBypassVirtual = true;
  17240. return;
  17241. }
  17242. curCheckType = curCheckType->mBaseType;
  17243. }
  17244. }
  17245. mModule->Fail("Unable to find indexer property", indexerExpr->mTarget);
  17246. return;
  17247. }
  17248. bool wantsChecks = checkedKind == BfCheckedKind_Checked;
  17249. if (checkedKind == BfCheckedKind_NotSet)
  17250. wantsChecks = mModule->GetDefaultCheckedKind() == BfCheckedKind_Checked;
  17251. //target.mType = mModule->ResolveGenericType(target.mType);
  17252. if (target.mType->IsVar())
  17253. {
  17254. mResult = target;
  17255. return;
  17256. }
  17257. if ((!target.mType->IsPointer()) && (!target.mType->IsSizedArray()))
  17258. {
  17259. mModule->Fail("Expected pointer or array type", indexerExpr->mTarget);
  17260. return;
  17261. }
  17262. auto _GetDefaultResult = [&]()
  17263. {
  17264. return mModule->GetDefaultTypedValue(target.mType->GetUnderlyingType(), false, BfDefaultValueKind_Addr);
  17265. };
  17266. if (indexerExpr->mArguments.size() != 1)
  17267. {
  17268. mModule->Fail("Expected single index", indexerExpr->mOpenBracket);
  17269. mResult = _GetDefaultResult();
  17270. return;
  17271. }
  17272. if (indexerExpr->mArguments[0] == NULL)
  17273. {
  17274. mModule->AssertErrorState();
  17275. mResult = _GetDefaultResult();
  17276. return;
  17277. }
  17278. bool isUndefIndex = false;
  17279. auto indexArgument = mModule->CreateValueFromExpression(indexerExpr->mArguments[0], mModule->GetPrimitiveType(BfTypeCode_IntPtr), BfEvalExprFlags_NoCast);
  17280. if (!indexArgument)
  17281. return;
  17282. if (!indexArgument.mType->IsIntegral())
  17283. {
  17284. if (indexArgument.mType->IsVar())
  17285. {
  17286. isUndefIndex = true;
  17287. indexArgument = mModule->GetDefaultTypedValue(mModule->GetPrimitiveType(BfTypeCode_IntPtr), false, BfDefaultValueKind_Undef);
  17288. }
  17289. else
  17290. {
  17291. indexArgument = mModule->Cast(indexerExpr->mArguments[0], indexArgument, mModule->GetPrimitiveType(BfTypeCode_IntPtr));
  17292. if (!indexArgument)
  17293. indexArgument = mModule->GetDefaultTypedValue(mModule->GetPrimitiveType(BfTypeCode_IntPtr));
  17294. }
  17295. }
  17296. if (indexArgument.mType->IsPrimitiveType())
  17297. {
  17298. auto primType = (BfPrimitiveType*)indexArgument.mType;
  17299. if ((!primType->IsSigned()) && (primType->mSize < 8))
  17300. {
  17301. // GEP will always do a signed upcast so we need to cast manually if we are unsigned
  17302. indexArgument = BfTypedValue(mModule->mBfIRBuilder->CreateNumericCast(indexArgument.mValue, false, BfTypeCode_IntPtr), mModule->GetPrimitiveType(BfTypeCode_IntPtr));
  17303. }
  17304. }
  17305. mModule->PopulateType(target.mType);
  17306. if (target.mType->IsSizedArray())
  17307. {
  17308. BfSizedArrayType* sizedArrayType = (BfSizedArrayType*)target.mType;
  17309. auto underlyingType = sizedArrayType->mElementType;
  17310. if (indexArgument.mValue.IsConst())
  17311. {
  17312. auto indexConst = mModule->mBfIRBuilder->GetConstant(indexArgument.mValue);
  17313. if (indexConst->mUInt64 >= (uint64)sizedArrayType->mElementCount)
  17314. {
  17315. if (!mModule->IsInSpecializedSection())
  17316. {
  17317. mModule->Fail(StrFormat("Index '%d' is out of bounds for type '%s'", indexConst->mInt32, mModule->TypeToString(target.mType).c_str()), indexerExpr->mArguments[0]);
  17318. mResult = _GetDefaultResult();
  17319. return;
  17320. }
  17321. else
  17322. {
  17323. // Is this any good?
  17324. mModule->mBfIRBuilder->CreateUnreachable();
  17325. }
  17326. }
  17327. }
  17328. else if (((mModule->HasExecutedOutput()) || (mModule->mIsComptimeModule)) &&
  17329. (wantsChecks))
  17330. {
  17331. if (checkedKind == BfCheckedKind_NotSet)
  17332. checkedKind = mModule->GetDefaultCheckedKind();
  17333. if (checkedKind == BfCheckedKind_Checked)
  17334. {
  17335. auto oobBlock = mModule->mBfIRBuilder->CreateBlock("oob", true);
  17336. auto contBlock = mModule->mBfIRBuilder->CreateBlock("cont", true);
  17337. auto indexType = (BfPrimitiveType*)indexArgument.mType;
  17338. if (!mModule->mSystem->DoesLiteralFit(indexType->mTypeDef->mTypeCode, (int64)sizedArrayType->mElementCount))
  17339. {
  17340. // We need to upsize the index so we can compare it against the larger elementCount
  17341. indexType = mModule->GetPrimitiveType(BfTypeCode_IntPtr);
  17342. indexArgument = mModule->Cast(indexerExpr->mArguments[0], indexArgument, indexType);
  17343. }
  17344. auto cmpRes = mModule->mBfIRBuilder->CreateCmpGTE(indexArgument.mValue, mModule->mBfIRBuilder->CreateConst(indexType->mTypeDef->mTypeCode, (uint64)sizedArrayType->mElementCount), false);
  17345. mModule->mBfIRBuilder->CreateCondBr(cmpRes, oobBlock, contBlock);
  17346. mModule->mBfIRBuilder->SetInsertPoint(oobBlock);
  17347. auto internalType = mModule->ResolveTypeDef(mModule->mCompiler->mInternalTypeDef);
  17348. auto oobFunc = mModule->GetMethodByName(internalType->ToTypeInstance(), "ThrowIndexOutOfRange");
  17349. if (oobFunc.mFunc)
  17350. {
  17351. /*if (!mModule->mCompiler->mIsResolveOnly)
  17352. {
  17353. OutputDebugStrF("-OOB %d %d\n", oobFunc.mFunc.mId, oobFunc.mFunc.mFlags);
  17354. }*/
  17355. if (mModule->mIsComptimeModule)
  17356. mModule->mCompiler->mCEMachine->QueueMethod(oobFunc.mMethodInstance, oobFunc.mFunc);
  17357. SizedArray<BfIRValue, 1> args;
  17358. args.push_back(mModule->GetConstValue(0));
  17359. mModule->mBfIRBuilder->CreateCall(oobFunc.mFunc, args);
  17360. mModule->mBfIRBuilder->CreateUnreachable();
  17361. mModule->mBfIRBuilder->SetInsertPoint(contBlock);
  17362. }
  17363. else
  17364. {
  17365. mModule->Fail("System.Internal class must contain method 'ThrowIndexOutOfRange'");
  17366. }
  17367. }
  17368. }
  17369. // If this is a 'bag of bytes', we should try hard not to have to make this addressable
  17370. if ((!target.IsAddr()) && (!target.mType->IsSizeAligned()))
  17371. mModule->MakeAddressable(target);
  17372. mModule->PopulateType(underlyingType);
  17373. if ((sizedArrayType->IsUndefSizedArray()) || (isUndefIndex))
  17374. {
  17375. mResult = mModule->GetDefaultTypedValue(underlyingType, false, BfDefaultValueKind_Addr);
  17376. }
  17377. else if (sizedArrayType->IsValuelessType())
  17378. {
  17379. if (underlyingType->IsValuelessType())
  17380. mResult = BfTypedValue(mModule->mBfIRBuilder->GetFakeVal(), underlyingType, true);
  17381. else
  17382. {
  17383. mResult = mModule->GetDefaultTypedValue(underlyingType, false, BfDefaultValueKind_Addr);
  17384. }
  17385. }
  17386. else if (target.IsAddr())
  17387. {
  17388. if (target.mType->IsSizeAligned())
  17389. {
  17390. auto gepResult = mModule->mBfIRBuilder->CreateInBoundsGEP(target.mValue, mModule->GetConstValue(0), indexArgument.mValue);
  17391. mResult = BfTypedValue(gepResult, underlyingType, target.IsReadOnly() ? BfTypedValueKind_ReadOnlyAddr : BfTypedValueKind_Addr);
  17392. }
  17393. else
  17394. {
  17395. auto indexResult = mModule->CreateIndexedValue(underlyingType, target.mValue, indexArgument.mValue);
  17396. mResult = BfTypedValue(indexResult, underlyingType, target.IsReadOnly() ? BfTypedValueKind_ReadOnlyAddr : BfTypedValueKind_Addr);
  17397. }
  17398. }
  17399. else
  17400. {
  17401. if ((!target.mValue.IsConst()) && (!indexArgument.mValue.IsConst()))
  17402. {
  17403. mModule->Fail("Unable to index value", indexerExpr->mTarget);
  17404. return;
  17405. }
  17406. mModule->mBfIRBuilder->PopulateType(target.mType);
  17407. auto gepResult = mModule->mBfIRBuilder->CreateExtractValue(target.mValue, indexArgument.mValue);
  17408. if ((underlyingType->IsString()) || (underlyingType->IsPointer()))
  17409. {
  17410. auto resultConst = mModule->mBfIRBuilder->GetConstant(gepResult);
  17411. if ((resultConst != NULL) && (resultConst->mTypeCode == BfTypeCode_Int32))
  17412. {
  17413. int strId = resultConst->mInt32;
  17414. const StringImpl& str = mModule->mContext->mStringObjectIdMap[strId].mString;
  17415. if (underlyingType->IsString())
  17416. gepResult = mModule->GetStringObjectValue(str, false);
  17417. else
  17418. gepResult = mModule->GetStringCharPtr(strId);
  17419. }
  17420. }
  17421. mResult = BfTypedValue(gepResult, underlyingType, BfTypedValueKind_Value);
  17422. }
  17423. }
  17424. else
  17425. {
  17426. target = mModule->LoadValue(target);
  17427. BfPointerType* pointerType = (BfPointerType*)target.mType;
  17428. auto underlyingType = pointerType->mElementType;
  17429. mModule->mBfIRBuilder->PopulateType(underlyingType);
  17430. if (isUndefIndex)
  17431. {
  17432. mResult = mModule->GetDefaultTypedValue(underlyingType, false, BfDefaultValueKind_Addr);
  17433. }
  17434. else
  17435. {
  17436. BfIRValue result = mModule->CreateIndexedValue(underlyingType, target.mValue, indexArgument.mValue);
  17437. mResult = BfTypedValue(result, underlyingType, true);
  17438. }
  17439. }
  17440. }
  17441. void BfExprEvaluator::Visit(BfUnaryOperatorExpression* unaryOpExpr)
  17442. {
  17443. BfAutoParentNodeEntry autoParentNodeEntry(mModule, unaryOpExpr);
  17444. PerformUnaryOperation(unaryOpExpr->mExpression, unaryOpExpr->mOp, unaryOpExpr->mOpToken, BfUnaryOpFlag_None);
  17445. }
  17446. void BfExprEvaluator::PerformUnaryOperation(BfExpression* unaryOpExpr, BfUnaryOp unaryOp, BfTokenNode* opToken, BfUnaryOpFlags opFlags)
  17447. {
  17448. if ((unaryOpExpr == NULL) && (unaryOp == BfUnaryOp_PartialRangeThrough))
  17449. {
  17450. PerformBinaryOperation(NULL, NULL, BfBinaryOp_ClosedRange, opToken, BfBinOpFlag_None);
  17451. return;
  17452. }
  17453. ///
  17454. {
  17455. // If this is a cast, we don't want the value to be coerced before the unary operator is applied.
  17456. // WAIT: Why not?
  17457. //SetAndRestoreValue<BfType*> prevExpectingType(mExpectingType, NULL);
  17458. BfType* prevExpedcting = mExpectingType;
  17459. switch (unaryOp)
  17460. {
  17461. case BfUnaryOp_Negate:
  17462. case BfUnaryOp_Positive:
  17463. case BfUnaryOp_InvertBits:
  17464. // If we're expecting an int64 or uint64 then just leave the type as unknown
  17465. if ((mExpectingType != NULL) && (mExpectingType->IsInteger()) && (mExpectingType->mSize == 8))
  17466. mExpectingType = NULL;
  17467. // Otherwise keep expecting type
  17468. break;
  17469. default:
  17470. mExpectingType = NULL;
  17471. }
  17472. VisitChild(unaryOpExpr);
  17473. mExpectingType = prevExpedcting;
  17474. }
  17475. BfExprEvaluator::PerformUnaryOperation_OnResult(unaryOpExpr, unaryOp, opToken, opFlags);
  17476. }
  17477. BfTypedValue BfExprEvaluator::PerformUnaryOperation_TryOperator(const BfTypedValue& inValue, BfExpression* unaryOpExpr, BfUnaryOp unaryOp, BfTokenNode* opToken, BfUnaryOpFlags opFlags)
  17478. {
  17479. if ((!inValue.mType->IsTypeInstance()) && (!inValue.mType->IsGenericParam()))
  17480. return BfTypedValue();
  17481. SizedArray<BfResolvedArg, 1> args;
  17482. BfResolvedArg resolvedArg;
  17483. resolvedArg.mTypedValue = inValue;
  17484. args.push_back(resolvedArg);
  17485. BfMethodMatcher methodMatcher(opToken, mModule, "", args, NULL);
  17486. methodMatcher.mBfEvalExprFlags = BfEvalExprFlags_NoAutoComplete;
  17487. methodMatcher.mAllowImplicitRef = true;
  17488. BfBaseClassWalker baseClassWalker(inValue.mType, NULL, mModule);
  17489. BfUnaryOp findOp = unaryOp;
  17490. bool isPostOp = false;
  17491. if (findOp == BfUnaryOp_PostIncrement)
  17492. {
  17493. findOp = BfUnaryOp_Increment;
  17494. isPostOp = true;
  17495. }
  17496. if (findOp == BfUnaryOp_PostDecrement)
  17497. {
  17498. findOp = BfUnaryOp_Decrement;
  17499. isPostOp = true;
  17500. }
  17501. bool isConstraintCheck = ((opFlags & BfUnaryOpFlag_IsConstraintCheck) != 0);
  17502. BfType* operatorConstraintReturnType = NULL;
  17503. BfType* bestSelfType = NULL;
  17504. while (true)
  17505. {
  17506. auto entry = baseClassWalker.Next();
  17507. auto checkType = entry.mTypeInstance;
  17508. if (checkType == NULL)
  17509. break;
  17510. for (auto operatorDef : checkType->mTypeDef->mOperators)
  17511. {
  17512. if (operatorDef->mOperatorDeclaration->mUnaryOp == findOp)
  17513. {
  17514. if (!methodMatcher.IsMemberAccessible(checkType, operatorDef->mDeclaringType))
  17515. continue;
  17516. int prevArgSize = (int)args.mSize;
  17517. if (!operatorDef->mIsStatic)
  17518. {
  17519. // Try without arg
  17520. args.mSize = 0;
  17521. }
  17522. if (isConstraintCheck)
  17523. {
  17524. auto returnType = mModule->CheckOperator(checkType, operatorDef, inValue, BfTypedValue());
  17525. if (returnType != NULL)
  17526. {
  17527. operatorConstraintReturnType = returnType;
  17528. methodMatcher.mBestMethodDef = operatorDef;
  17529. }
  17530. }
  17531. else
  17532. {
  17533. if (methodMatcher.CheckMethod(NULL, checkType, operatorDef, false))
  17534. methodMatcher.mSelfType = entry.mSrcType;
  17535. }
  17536. args.mSize = prevArgSize;
  17537. }
  17538. }
  17539. }
  17540. if (methodMatcher.mBestMethodDef == NULL)
  17541. {
  17542. // Check method generic constraints
  17543. if ((mModule->mCurMethodInstance != NULL) && (mModule->mCurMethodInstance->mIsUnspecialized) && (mModule->mCurMethodInstance->mMethodInfoEx != NULL))
  17544. {
  17545. for (int genericParamIdx = 0; genericParamIdx < mModule->mCurMethodInstance->mMethodInfoEx->mGenericParams.size(); genericParamIdx++)
  17546. {
  17547. auto genericParam = mModule->mCurMethodInstance->mMethodInfoEx->mGenericParams[genericParamIdx];
  17548. for (auto& opConstraint : genericParam->mOperatorConstraints)
  17549. {
  17550. if (opConstraint.mUnaryOp == findOp)
  17551. {
  17552. if (mModule->CanCast(args[0].mTypedValue, opConstraint.mRightType, isConstraintCheck ? BfCastFlags_IsConstraintCheck : BfCastFlags_None))
  17553. {
  17554. return BfTypedValue(mModule->mBfIRBuilder->GetFakeVal(), genericParam->mExternType);
  17555. }
  17556. }
  17557. }
  17558. }
  17559. }
  17560. // Check type generic constraints
  17561. if ((mModule->mCurTypeInstance->IsGenericTypeInstance()) && (mModule->mCurTypeInstance->IsUnspecializedType()))
  17562. {
  17563. auto genericTypeInst = (BfTypeInstance*)mModule->mCurTypeInstance;
  17564. for (int genericParamIdx = 0; genericParamIdx < genericTypeInst->mGenericTypeInfo->mGenericParams.size(); genericParamIdx++)
  17565. {
  17566. auto genericParam = mModule->GetGenericTypeParamInstance(genericParamIdx);
  17567. for (auto& opConstraint : genericParam->mOperatorConstraints)
  17568. {
  17569. if (opConstraint.mUnaryOp == findOp)
  17570. {
  17571. if (mModule->CanCast(args[0].mTypedValue, opConstraint.mRightType, isConstraintCheck ? BfCastFlags_IsConstraintCheck : BfCastFlags_None))
  17572. {
  17573. return BfTypedValue(mModule->mBfIRBuilder->GetFakeVal(), genericParam->mExternType);
  17574. }
  17575. }
  17576. }
  17577. }
  17578. }
  17579. return BfTypedValue();
  17580. }
  17581. if ((!baseClassWalker.mMayBeFromInterface) && (opToken != NULL))
  17582. mModule->SetElementType(opToken, BfSourceElementType_Method);
  17583. auto methodDef = methodMatcher.mBestMethodDef;
  17584. auto autoComplete = GetAutoComplete();
  17585. if ((autoComplete != NULL) && (autoComplete->IsAutocompleteNode(opToken)))
  17586. {
  17587. auto operatorDecl = BfNodeDynCast<BfOperatorDeclaration>(methodDef->mMethodDeclaration);
  17588. if ((operatorDecl != NULL) && (operatorDecl->mOpTypeToken != NULL))
  17589. autoComplete->SetDefinitionLocation(operatorDecl->mOpTypeToken);
  17590. }
  17591. SizedArray<BfExpression*, 2> argSrcs;
  17592. argSrcs.push_back(unaryOpExpr);
  17593. BfTypedValue targetVal = args[0].mTypedValue;
  17594. BfTypedValue postOpVal;
  17595. if (isPostOp)
  17596. postOpVal = mModule->LoadValue(targetVal);
  17597. BfTypedValue callTarget;
  17598. if (!methodMatcher.mBestMethodDef->mIsStatic)
  17599. {
  17600. callTarget = targetVal;
  17601. args.Clear();
  17602. }
  17603. BfTypedValue result;
  17604. if (isConstraintCheck)
  17605. {
  17606. result = BfTypedValue(mModule->mBfIRBuilder->GetFakeVal(), operatorConstraintReturnType);
  17607. }
  17608. else
  17609. {
  17610. SetAndRestoreValue<BfEvalExprFlags> prevFlags(mBfEvalExprFlags, (BfEvalExprFlags)(mBfEvalExprFlags | BfEvalExprFlags_NoAutoComplete));
  17611. result = CreateCall(&methodMatcher, callTarget);
  17612. }
  17613. if (!methodMatcher.mBestMethodDef->mIsStatic)
  17614. {
  17615. if (!isPostOp)
  17616. result = mModule->LoadValue(targetVal);
  17617. }
  17618. else if ((result.mType != NULL) && (methodMatcher.mSelfType != NULL) && (result.mType->IsSelf()))
  17619. {
  17620. BF_ASSERT(mModule->IsInGeneric());
  17621. result = mModule->GetDefaultTypedValue(methodMatcher.mSelfType);
  17622. }
  17623. if ((methodMatcher.mBestMethodInstance) &&
  17624. ((findOp == BfUnaryOp_Increment) || (findOp == BfUnaryOp_Decrement)))
  17625. {
  17626. if (methodMatcher.mBestMethodInstance.mMethodInstance->mIsIntrinsic)
  17627. {
  17628. if (args[0].mTypedValue.IsAddr())
  17629. mModule->mBfIRBuilder->CreateStore(result.mValue, args[0].mTypedValue.mValue);
  17630. else
  17631. {
  17632. mModule->AssertErrorState();
  17633. }
  17634. }
  17635. else
  17636. {
  17637. if (!result.mType->IsValuelessType())
  17638. {
  17639. if (targetVal.IsAddr())
  17640. {
  17641. result = mModule->LoadValue(result);
  17642. mModule->mBfIRBuilder->CreateStore(result.mValue, targetVal.mValue);
  17643. }
  17644. }
  17645. }
  17646. }
  17647. if (postOpVal)
  17648. result = postOpVal;
  17649. return result;
  17650. }
  17651. void BfExprEvaluator::PerformUnaryOperation_OnResult(BfExpression* unaryOpExpr, BfUnaryOp unaryOp, BfTokenNode* opToken, BfUnaryOpFlags opFlags)
  17652. {
  17653. BfAstNode* propSrc = mPropSrc;
  17654. BfTypedValue propTarget = mPropTarget;
  17655. BfPropertyDef* propDef = mPropDef;
  17656. SizedArray<BfResolvedArg, 2> indexerVals = mIndexerValues;
  17657. BfTypedValue writeToProp;
  17658. GetResult();
  17659. if (!mResult)
  17660. return;
  17661. if (mResult.mType->IsRef())
  17662. mResult.mType = mResult.mType->GetUnderlyingType();
  17663. if (mResult.mType->IsVar())
  17664. {
  17665. mResult = BfTypedValue(mModule->GetDefaultValue(mResult.mType), mResult.mType);
  17666. return;
  17667. }
  17668. if (BfCanOverloadOperator(unaryOp))
  17669. {
  17670. auto opResult = PerformUnaryOperation_TryOperator(mResult, unaryOpExpr, unaryOp, opToken, opFlags);
  17671. if (opResult)
  17672. {
  17673. mResult = opResult;
  17674. return;
  17675. }
  17676. }
  17677. bool numericFail = false;
  17678. switch (unaryOp)
  17679. {
  17680. case BfUnaryOp_Not:
  17681. {
  17682. CheckResultForReading(mResult);
  17683. auto boolType = mModule->GetPrimitiveType(BfTypeCode_Boolean);
  17684. auto value = mModule->LoadValue(mResult);
  17685. value = mModule->Cast(unaryOpExpr, value, boolType);
  17686. if (!value)
  17687. {
  17688. mResult = BfTypedValue();
  17689. return;
  17690. }
  17691. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateNot(value.mValue), boolType);
  17692. }
  17693. break;
  17694. case BfUnaryOp_Positive:
  17695. return;
  17696. case BfUnaryOp_Negate:
  17697. {
  17698. CheckResultForReading(mResult);
  17699. auto value = mModule->LoadValue(mResult);
  17700. if (!value)
  17701. {
  17702. mResult = BfTypedValue();
  17703. return;
  17704. }
  17705. BfType* origType = value.mType;
  17706. if (value.mType->IsTypedPrimitive())
  17707. value.mType = value.mType->GetUnderlyingType();
  17708. if (value.mType->IsIntegral())
  17709. {
  17710. auto primType = (BfPrimitiveType*)value.mType;
  17711. auto wantType = primType;
  17712. auto constant = mModule->mBfIRBuilder->GetConstant(value.mValue);
  17713. if ((constant != NULL) && (mModule->mBfIRBuilder->IsInt(constant->mTypeCode)))
  17714. {
  17715. if ((primType->mTypeDef->mTypeCode == BfTypeCode_UInt32) && (constant->mInt64 == 0x80000000LL))
  17716. {
  17717. mResult = BfTypedValue(mModule->GetConstValue32(-0x80000000LL), mModule->GetPrimitiveType(BfTypeCode_Int32));
  17718. return;
  17719. }
  17720. else if ((primType->mTypeDef->mTypeCode == BfTypeCode_UInt64) && (constant->mInt64 == 0x8000000000000000LL))
  17721. {
  17722. mResult = BfTypedValue(mModule->GetConstValue64(-0x8000000000000000LL), mModule->GetPrimitiveType(BfTypeCode_Int64));
  17723. return;
  17724. }
  17725. }
  17726. /*if (auto constantInt = dyn_cast<ConstantInt>((Value*)value.mValue))
  17727. {
  17728. int64 i64Val = constantInt->getSExtValue();
  17729. // This is a special case where the user entered -0x80000000 (maxint) but we thought "0x80000000" was a uint in the parser
  17730. // which would get upcasted to an int64 for this negate. Properly bring back down to an int32
  17731. if ((primType->mTypeDef->mTypeCode == BfTypeCode_UInt32) && (i64Val == -0x80000000LL))
  17732. {
  17733. mResult = BfTypedValue(mModule->GetConstValue((int)i64Val), mModule->GetPrimitiveType(BfTypeCode_Int32));
  17734. return;
  17735. }
  17736. }*/
  17737. if (!primType->IsSigned())
  17738. {
  17739. if (primType->mSize == 1)
  17740. wantType = mModule->GetPrimitiveType(BfTypeCode_Int16);
  17741. else if (primType->mSize == 2)
  17742. wantType = mModule->GetPrimitiveType(BfTypeCode_Int32);
  17743. else if (primType->mSize == 4)
  17744. wantType = mModule->GetPrimitiveType(BfTypeCode_Int64);
  17745. else
  17746. mModule->Fail("Operator '-' cannot be applied to uint64", opToken);
  17747. }
  17748. if (primType != wantType)
  17749. {
  17750. value = mModule->Cast(unaryOpExpr, value, wantType, BfCastFlags_Explicit);
  17751. if (!value)
  17752. {
  17753. mResult = BfTypedValue();
  17754. return;
  17755. }
  17756. }
  17757. if (origType->mSize == wantType->mSize) // Allow negative of primitive typed but not if we had to upsize
  17758. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateNeg(value.mValue), origType);
  17759. else
  17760. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateNeg(value.mValue), wantType);
  17761. }
  17762. else if (value.mType->IsFloat())
  17763. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateNeg(value.mValue), origType);
  17764. else
  17765. numericFail = true;
  17766. }
  17767. break;
  17768. case BfUnaryOp_InvertBits:
  17769. {
  17770. CheckResultForReading(mResult);
  17771. auto value = mModule->LoadValue(mResult);
  17772. if (!value)
  17773. return;
  17774. bool isInteger = value.mType->IsIntegral();
  17775. if (value.mType->IsTypedPrimitive())
  17776. isInteger = value.mType->GetUnderlyingType()->IsIntegral();
  17777. if (!isInteger)
  17778. {
  17779. mResult = BfTypedValue();
  17780. mModule->Fail("Operator can only be used on integer types", opToken);
  17781. return;
  17782. }
  17783. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateNot(value.mValue), value.mType);
  17784. }
  17785. break;
  17786. case BfUnaryOp_AddressOf:
  17787. {
  17788. MarkResultUsed();
  17789. mModule->FixIntUnknown(mResult);
  17790. mModule->PopulateType(mResult.mType);
  17791. auto ptrType = mModule->CreatePointerType(mResult.mType);
  17792. if (mResult.mType->IsValuelessType())
  17793. {
  17794. // Sentinel value
  17795. auto val = mModule->mBfIRBuilder->CreateIntToPtr(mModule->mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, 1), mModule->mBfIRBuilder->MapType(ptrType));
  17796. mResult = BfTypedValue(val, ptrType);
  17797. }
  17798. else if (!CheckModifyResult(mResult, unaryOpExpr, "take address of", false, true))
  17799. {
  17800. if (!mResult.IsAddr())
  17801. mResult = mModule->MakeAddressable(mResult);
  17802. mResult = BfTypedValue(mResult.mValue, ptrType, false);
  17803. }
  17804. else
  17805. mResult = BfTypedValue(mResult.mValue, ptrType, false);
  17806. }
  17807. break;
  17808. case BfUnaryOp_Dereference:
  17809. {
  17810. CheckResultForReading(mResult);
  17811. if (!mResult.mType->IsPointer())
  17812. {
  17813. mResult = BfTypedValue();
  17814. mModule->Fail("Cannot dereference non-pointer type", unaryOpExpr);
  17815. return;
  17816. }
  17817. if (mResult.mValue.IsConst())
  17818. {
  17819. auto constant = mModule->mBfIRBuilder->GetConstant(mResult.mValue);
  17820. bool isNull = constant->mTypeCode == BfTypeCode_NullPtr;
  17821. if (constant->mConstType == BfConstType_ExtractValue)
  17822. {
  17823. auto constExtract = (BfConstantExtractValue*)constant;
  17824. auto targetConst = mModule->mBfIRBuilder->GetConstantById(constExtract->mTarget);
  17825. if (targetConst->mConstType == BfConstType_AggZero)
  17826. isNull = true;
  17827. }
  17828. if (isNull)
  17829. {
  17830. mModule->Warn(0, "Cannot dereference a null pointer", unaryOpExpr);
  17831. mResult = mModule->GetDefaultTypedValue(mResult.mType, false, BfDefaultValueKind_Addr);
  17832. mResult = mModule->LoadValue(mResult);
  17833. }
  17834. }
  17835. auto derefTarget = mModule->LoadValue(mResult);
  17836. BfPointerType* pointerType = (BfPointerType*)derefTarget.mType;
  17837. auto resolvedType = mModule->ResolveType(pointerType->mElementType);
  17838. if (resolvedType == NULL)
  17839. {
  17840. mResult = BfTypedValue();
  17841. return;
  17842. }
  17843. mModule->PopulateType(resolvedType);
  17844. if (resolvedType->IsValuelessType())
  17845. mResult = BfTypedValue(mModule->mBfIRBuilder->GetFakeVal(), resolvedType, true);
  17846. else
  17847. mResult = BfTypedValue(derefTarget.mValue, resolvedType, true);
  17848. }
  17849. break;
  17850. case BfUnaryOp_PostIncrement:
  17851. case BfUnaryOp_Increment:
  17852. {
  17853. CheckResultForReading(mResult);
  17854. auto ptr = mResult;
  17855. //if ((propDef == NULL) && (!mModule->CheckModifyValue(ptr, opToken)))
  17856. if ((propDef == NULL) && (!CheckModifyResult(ptr, opToken, "increment")))
  17857. return;
  17858. BfTypedValue origTypedVal = mModule->LoadValue(ptr, NULL, mIsVolatileReference);
  17859. BfIRValue origVal = origTypedVal.mValue;
  17860. BfIRValue constValue = mModule->GetConstValue(1, ptr.mType);
  17861. BfIRValue resultValue;
  17862. if (ptr.mType->IsPointer())
  17863. {
  17864. BfPointerType* ptrType = (BfPointerType*)ptr.mType;
  17865. BfType* intPtrType = mModule->GetPrimitiveType(BfTypeCode_IntPtr);
  17866. constValue = mModule->GetConstValue(ptrType->mElementType->GetStride(), intPtrType);
  17867. auto i8PtrType = mModule->mBfIRBuilder->GetPointerTo(mModule->mBfIRBuilder->GetPrimitiveType(BfTypeCode_Int8));
  17868. BfIRValue origPtrValue = mModule->mBfIRBuilder->CreateBitCast(origVal, i8PtrType);
  17869. BfIRValue newPtrValue = mModule->mBfIRBuilder->CreateInBoundsGEP(origPtrValue, constValue);
  17870. resultValue = mModule->mBfIRBuilder->CreateBitCast(newPtrValue, mModule->mBfIRBuilder->MapType(ptr.mType));
  17871. }
  17872. else
  17873. {
  17874. constValue = mModule->GetConstValue(1, ptr.mType);
  17875. if (!constValue)
  17876. {
  17877. numericFail = true;
  17878. break;
  17879. }
  17880. if ((ptr.mType->IsIntegral()) || (ptr.mType->IsEnum()) || (ptr.mType->IsFloat()))
  17881. {
  17882. resultValue = mModule->mBfIRBuilder->CreateAdd(origVal, constValue/*, "inc"*/);
  17883. }
  17884. else
  17885. {
  17886. numericFail = true;
  17887. break;
  17888. }
  17889. }
  17890. if ((propDef != NULL) && (!ptr.IsAddr()))
  17891. writeToProp = BfTypedValue(resultValue, ptr.mType);
  17892. else
  17893. mModule->mBfIRBuilder->CreateStore(resultValue, ptr.mValue, mIsVolatileReference);
  17894. if (unaryOp == BfUnaryOp_PostIncrement)
  17895. mResult = BfTypedValue(origVal, ptr.mType, false);
  17896. else
  17897. mResult = BfTypedValue(resultValue, ptr.mType, false);
  17898. }
  17899. break;
  17900. case BfUnaryOp_PostDecrement:
  17901. case BfUnaryOp_Decrement:
  17902. {
  17903. CheckResultForReading(mResult);
  17904. auto ptr = mResult;
  17905. //if ((propDef == NULL) && (!mModule->CheckModifyValue(ptr, opToken)))
  17906. //return;
  17907. if ((propDef == NULL) && (!CheckModifyResult(ptr, opToken, "decrement")))
  17908. return;
  17909. BfTypedValue origTypedVal = mModule->LoadValue(ptr, NULL, mIsVolatileReference);
  17910. BfIRValue origVal = origTypedVal.mValue;
  17911. BfIRValue constValue = mModule->GetConstValue(1, ptr.mType);
  17912. BfIRValue resultValue;
  17913. if (ptr.mType->IsPointer())
  17914. {
  17915. BfPointerType* ptrType = (BfPointerType*)ptr.mType;
  17916. BfType* intPtrType = mModule->GetPrimitiveType(BfTypeCode_IntPtr);
  17917. constValue = mModule->GetConstValue(-ptrType->mElementType->GetStride(), intPtrType);
  17918. auto i8PtrType = mModule->mBfIRBuilder->GetPointerTo(mModule->mBfIRBuilder->GetPrimitiveType(BfTypeCode_Int8));
  17919. BfIRValue origPtrValue = mModule->mBfIRBuilder->CreateBitCast(origVal, i8PtrType);
  17920. BfIRValue newPtrValue = mModule->mBfIRBuilder->CreateInBoundsGEP(origPtrValue, constValue);
  17921. resultValue = mModule->mBfIRBuilder->CreateBitCast(newPtrValue, mModule->mBfIRBuilder->MapType(ptr.mType));
  17922. }
  17923. else
  17924. {
  17925. BfIRValue constValue = mModule->GetConstValue(1, ptr.mType);
  17926. if (!constValue)
  17927. {
  17928. numericFail = true;
  17929. break;
  17930. }
  17931. if ((ptr.mType->IsIntegral()) || (ptr.mType->IsEnum()))
  17932. {
  17933. resultValue = mModule->mBfIRBuilder->CreateSub(origVal, constValue);
  17934. }
  17935. else if (ptr.mType->IsFloat())
  17936. {
  17937. resultValue = mModule->mBfIRBuilder->CreateSub(origVal, constValue);
  17938. }
  17939. else
  17940. {
  17941. numericFail = true;
  17942. break;
  17943. }
  17944. }
  17945. if ((propDef != NULL) && (!ptr.IsAddr()))
  17946. writeToProp = BfTypedValue(resultValue, ptr.mType);
  17947. else
  17948. mModule->mBfIRBuilder->CreateStore(resultValue, ptr.mValue, mIsVolatileReference);
  17949. if (unaryOp == BfUnaryOp_PostDecrement)
  17950. mResult = BfTypedValue(origVal, ptr.mType, false);
  17951. else
  17952. mResult = BfTypedValue(resultValue, ptr.mType, false);
  17953. }
  17954. break;
  17955. case BfUnaryOp_Ref:
  17956. case BfUnaryOp_Mut:
  17957. {
  17958. if (mAllowReadOnlyReference)
  17959. {
  17960. if (mResult.mKind == BfTypedValueKind_ReadOnlyAddr)
  17961. mResult.mKind = BfTypedValueKind_Addr;
  17962. }
  17963. CheckResultForReading(mResult);
  17964. if ((unaryOp == BfUnaryOp_Mut) && (!mResult.mType->IsComposite()) && (!mResult.mType->IsGenericParam()))
  17965. {
  17966. // Non-composite types are already mutable, leave them alone...
  17967. break;
  17968. }
  17969. if ((unaryOp != BfUnaryOp_Mut) || (mResult.mKind != BfTypedValueKind_MutableValue))
  17970. {
  17971. if (!CheckModifyResult(mResult, unaryOpExpr, StrFormat("use '%s' on", BfGetOpName(unaryOp)).c_str()))
  17972. {
  17973. // Just leave the non-ref version in mResult
  17974. return;
  17975. }
  17976. }
  17977. if ((mBfEvalExprFlags & BfEvalExprFlags_AllowRefExpr) == 0)
  17978. {
  17979. mResult = BfTypedValue();
  17980. mModule->Fail(StrFormat("Invalid usage of '%s' expression", BfGetOpName(unaryOp)), opToken);
  17981. return;
  17982. }
  17983. ResolveGenericType();
  17984. if (mResult.mType->IsVar())
  17985. break;
  17986. mResult = BfTypedValue(mResult.mValue, mModule->CreateRefType(mResult.mType, (unaryOp == BfUnaryOp_Ref) ? BfRefType::RefKind_Ref : BfRefType::RefKind_Mut));
  17987. }
  17988. break;
  17989. case BfUnaryOp_Out:
  17990. {
  17991. if (!CheckModifyResult(mResult, unaryOpExpr, "use 'out' on"))
  17992. {
  17993. // Just leave the non-ref version in mResult
  17994. return;
  17995. }
  17996. if ((mBfEvalExprFlags & BfEvalExprFlags_AllowOutExpr) == 0)
  17997. {
  17998. mModule->Fail("Invalid usage of 'out' expression", opToken);
  17999. return;
  18000. }
  18001. if (mInsidePendingNullable)
  18002. {
  18003. // 'out' inside null conditionals never actually causes a definite assignment...
  18004. }
  18005. else
  18006. MarkResultAssigned();
  18007. MarkResultUsed();
  18008. ResolveGenericType();
  18009. if (mResult.mType->IsVar())
  18010. break;
  18011. mResult = BfTypedValue(mResult.mValue, mModule->CreateRefType(mResult.mType, BfRefType::RefKind_Out));
  18012. }
  18013. break;
  18014. case BfUnaryOp_Params:
  18015. {
  18016. bool allowParams = (mBfEvalExprFlags & BfEvalExprFlags_AllowParamsExpr) != 0;
  18017. if (allowParams)
  18018. {
  18019. if ((mResultLocalVar != NULL) && (mResultLocalVar->mCompositeCount >= 0)) // Delegate params
  18020. {
  18021. allowParams = true;
  18022. }
  18023. else
  18024. {
  18025. auto isValid = false;
  18026. auto genericTypeInst = mResult.mType->ToGenericTypeInstance();
  18027. if ((genericTypeInst != NULL) && (genericTypeInst->IsInstanceOf(mModule->mCompiler->mSpanTypeDef)))
  18028. isValid = true;
  18029. else if (mResult.mType->IsArray())
  18030. isValid = true;
  18031. if (!isValid)
  18032. {
  18033. mModule->Fail(StrFormat("A 'params' expression cannot be used on type '%s'", mModule->TypeToString(mResult.mType).c_str()), opToken);
  18034. }
  18035. }
  18036. }
  18037. if (allowParams)
  18038. {
  18039. mResult = mModule->LoadValue(mResult);
  18040. if (mResult.IsSplat())
  18041. mResult.mKind = BfTypedValueKind_ParamsSplat;
  18042. else
  18043. mResult.mKind = BfTypedValueKind_Params;
  18044. }
  18045. else
  18046. {
  18047. mModule->Fail("Illegal use of 'params' expression", opToken);
  18048. }
  18049. }
  18050. break;
  18051. case BfUnaryOp_Cascade:
  18052. {
  18053. mModule->Fail("Illegal use of argument cascade expression", opToken);
  18054. }
  18055. break;
  18056. case BfUnaryOp_FromEnd:
  18057. {
  18058. CheckResultForReading(mResult);
  18059. auto value = mModule->Cast(unaryOpExpr, mResult, mModule->GetPrimitiveType(BfTypeCode_IntPtr));
  18060. value = mModule->LoadValue(value);
  18061. if (value)
  18062. {
  18063. auto indexType = mModule->ResolveTypeDef(mModule->mCompiler->mIndexTypeDef);
  18064. auto alloca = mModule->CreateAlloca(indexType);
  18065. mModule->mBfIRBuilder->CreateStore(value.mValue, mModule->mBfIRBuilder->CreateInBoundsGEP(mModule->mBfIRBuilder->CreateInBoundsGEP(alloca, 0, 1), 0, 1));
  18066. mModule->mBfIRBuilder->CreateStore(mModule->mBfIRBuilder->CreateConst(BfTypeCode_Int8, 1), mModule->mBfIRBuilder->CreateInBoundsGEP(alloca, 0, 2));
  18067. mResult = BfTypedValue(alloca, indexType, BfTypedValueKind_Addr);
  18068. }
  18069. }
  18070. break;
  18071. case BfUnaryOp_PartialRangeUpTo:
  18072. PerformBinaryOperation(NULL, unaryOpExpr, BfBinaryOp_Range, opToken, BfBinOpFlag_None);
  18073. break;
  18074. case BfUnaryOp_PartialRangeThrough:
  18075. PerformBinaryOperation(NULL, unaryOpExpr, BfBinaryOp_ClosedRange, opToken, BfBinOpFlag_None);
  18076. break;
  18077. case BfUnaryOp_PartialRangeFrom:
  18078. PerformBinaryOperation(unaryOpExpr, NULL, BfBinaryOp_ClosedRange, opToken, BfBinOpFlag_None);
  18079. break;
  18080. default:
  18081. mModule->Fail(StrFormat("Illegal use of '%s' unary operator", BfGetOpName(unaryOp)), unaryOpExpr);
  18082. break;
  18083. }
  18084. if (numericFail)
  18085. {
  18086. if (opToken == NULL)
  18087. {
  18088. BF_ASSERT(mModule->mBfIRBuilder->mIgnoreWrites);
  18089. }
  18090. else if ((mResult.mType != NULL) && (mResult.mType->IsInterface()))
  18091. {
  18092. mModule->Fail(
  18093. StrFormat("Operator '%s' cannot be used on interface '%s'. Consider rewriting using generics and use this interface as a generic constraint.",
  18094. BfTokenToString(opToken->mToken), mModule->TypeToString(mResult.mType).c_str()), opToken);
  18095. }
  18096. else
  18097. {
  18098. mModule->Fail(
  18099. StrFormat("Operator '%s' cannot be used because type '%s' is neither a numeric type nor does it define an applicable operator overload",
  18100. BfTokenToString(opToken->mToken), mModule->TypeToString(mResult.mType).c_str()), opToken);
  18101. }
  18102. mResult = BfTypedValue();
  18103. }
  18104. if (writeToProp)
  18105. {
  18106. auto setMethod = GetPropertyMethodDef(propDef, BfMethodType_PropertySetter, mPropCheckedKind, mPropTarget);
  18107. if (setMethod == NULL)
  18108. {
  18109. mModule->Fail("Property has no setter", propSrc);
  18110. return;
  18111. }
  18112. auto methodInstance = GetPropertyMethodInstance(setMethod);
  18113. if (!methodInstance.mFunc)
  18114. return;
  18115. if (propSrc != NULL)
  18116. mModule->UpdateExprSrcPos(propSrc);
  18117. SizedArray<BfIRValue, 4> args;
  18118. if (!setMethod->mIsStatic)
  18119. PushThis(propSrc, propTarget, methodInstance.mMethodInstance, args);
  18120. //args.push_back(propTarget.mValue);
  18121. for (int paramIdx = 0; paramIdx < (int)indexerVals.size(); paramIdx++)
  18122. {
  18123. auto val = mModule->Cast(propSrc, indexerVals[paramIdx].mTypedValue, methodInstance.mMethodInstance->GetParamType(paramIdx));
  18124. if (!val)
  18125. return;
  18126. PushArg(val, args);
  18127. }
  18128. PushArg(writeToProp, args);
  18129. CreateCall(opToken, methodInstance.mMethodInstance, methodInstance.mFunc, false, args);
  18130. }
  18131. }
  18132. void BfExprEvaluator::PerformBinaryOperation(BfExpression* leftExpression, BfExpression* rightExpression, BfBinaryOp binaryOp, BfTokenNode* opToken, BfBinOpFlags flags, BfTypedValue leftValue)
  18133. {
  18134. BfTypedValue rightValue;
  18135. if (rightExpression == NULL)
  18136. {
  18137. mModule->AssertErrorState();
  18138. return;
  18139. }
  18140. if (!leftValue)
  18141. {
  18142. if (!rightValue)
  18143. mModule->CreateValueFromExpression(rightExpression, mExpectingType, (BfEvalExprFlags)(mBfEvalExprFlags & BfEvalExprFlags_InheritFlags));
  18144. return;
  18145. }
  18146. if (leftValue.mType->IsRef())
  18147. leftValue.mType = leftValue.mType->GetUnderlyingType();
  18148. if ((binaryOp == BfBinaryOp_ConditionalAnd) || (binaryOp == BfBinaryOp_ConditionalOr))
  18149. {
  18150. if (mModule->mCurMethodState->mDeferredLocalAssignData != NULL)
  18151. mModule->mCurMethodState->mDeferredLocalAssignData->BreakExtendChain();
  18152. if (mModule->mCurMethodState->mCurScope->mScopeKind == BfScopeKind_StatementTarget)
  18153. mModule->mCurMethodState->mCurScope->mScopeKind = BfScopeKind_StatementTarget_Conditional;
  18154. bool isAnd = binaryOp == BfBinaryOp_ConditionalAnd;
  18155. auto boolType = mModule->GetPrimitiveType(BfTypeCode_Boolean);
  18156. leftValue = mModule->Cast(leftExpression, leftValue, boolType);
  18157. if (!leftValue)
  18158. {
  18159. mModule->CreateValueFromExpression(rightExpression);
  18160. return;
  18161. }
  18162. auto prevBB = mModule->mBfIRBuilder->GetInsertBlock();
  18163. SetAndRestoreValue<bool> prevInCondBlock(mModule->mCurMethodState->mInConditionalBlock, true);
  18164. // The RHS is not guaranteed to be executed
  18165. if ((mModule->mCurMethodState->mDeferredLocalAssignData != NULL) &&
  18166. (mModule->mCurMethodState->mDeferredLocalAssignData->mIsIfCondition))
  18167. mModule->mCurMethodState->mDeferredLocalAssignData->mIfMayBeSkipped = true;
  18168. if (isAnd)
  18169. {
  18170. bool isConstBranch = false;
  18171. bool constResult = false;
  18172. if (leftValue.mValue.IsConst())
  18173. {
  18174. auto constValue = mModule->mBfIRBuilder->GetConstant(leftValue.mValue);
  18175. if (constValue->mTypeCode == BfTypeCode_Boolean)
  18176. {
  18177. isConstBranch = true;
  18178. constResult = constValue->mBool;
  18179. }
  18180. }
  18181. if (isConstBranch)
  18182. {
  18183. if ((constResult) || (HasVariableDeclaration(rightExpression)))
  18184. {
  18185. // Only right side
  18186. rightValue = mModule->CreateValueFromExpression(rightExpression, boolType, (BfEvalExprFlags)(mBfEvalExprFlags & BfEvalExprFlags_InheritFlags));
  18187. mResult = rightValue;
  18188. }
  18189. else
  18190. {
  18191. // Always false
  18192. SetAndRestoreValue<bool> prevIgnoreWrites(mModule->mBfIRBuilder->mIgnoreWrites, true);
  18193. rightValue = mModule->CreateValueFromExpression(rightExpression, boolType, (BfEvalExprFlags)(mBfEvalExprFlags & BfEvalExprFlags_InheritFlags));
  18194. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConst(BfTypeCode_Boolean, 0), boolType);
  18195. }
  18196. }
  18197. else
  18198. {
  18199. auto rhsBB = mModule->mBfIRBuilder->CreateBlock("land.rhs");
  18200. auto endBB = mModule->mBfIRBuilder->CreateBlock("land.end");
  18201. // This makes any 'scope' allocs be dyn since we aren't sure if this will be short-circuited
  18202. SetAndRestoreValue<bool> prevIsConditional(mModule->mCurMethodState->mCurScope->mIsConditional, true);
  18203. mModule->mBfIRBuilder->CreateCondBr(leftValue.mValue, rhsBB, endBB);
  18204. mModule->AddBasicBlock(rhsBB);
  18205. rightValue = mModule->CreateValueFromExpression(rightExpression, boolType, (BfEvalExprFlags)(mBfEvalExprFlags & BfEvalExprFlags_InheritFlags));
  18206. mModule->mBfIRBuilder->CreateBr(endBB);
  18207. auto endRhsBB = mModule->mBfIRBuilder->GetInsertBlock();
  18208. mModule->AddBasicBlock(endBB);
  18209. auto phi = mModule->mBfIRBuilder->CreatePhi(mModule->mBfIRBuilder->MapType(boolType), 2);
  18210. mModule->mBfIRBuilder->AddPhiIncoming(phi, mModule->GetConstValue(0, boolType), prevBB);
  18211. if (rightValue)
  18212. mModule->mBfIRBuilder->AddPhiIncoming(phi, rightValue.mValue, endRhsBB);
  18213. mResult = BfTypedValue(phi, boolType);
  18214. }
  18215. }
  18216. else
  18217. {
  18218. // Put variables in here into a 'possibly assigned' but never commit it.
  18219. // Because if we had "if ((Get(out a)) || (GetOther(out a))" then the LHS would already set it as defined, so
  18220. // the RHS is inconsequential
  18221. BfDeferredLocalAssignData deferredLocalAssignData;
  18222. deferredLocalAssignData.ExtendFrom(mModule->mCurMethodState->mDeferredLocalAssignData, false);
  18223. deferredLocalAssignData.mVarIdBarrier = mModule->mCurMethodState->GetRootMethodState()->mCurLocalVarId;
  18224. SetAndRestoreValue<BfDeferredLocalAssignData*> prevDLA(mModule->mCurMethodState->mDeferredLocalAssignData, &deferredLocalAssignData);
  18225. bool isConstBranch = false;
  18226. bool constResult = false;
  18227. if (leftValue.mValue.IsConst())
  18228. {
  18229. auto constValue = mModule->mBfIRBuilder->GetConstant(leftValue.mValue);
  18230. if (constValue->mTypeCode == BfTypeCode_Boolean)
  18231. {
  18232. isConstBranch = true;
  18233. constResult = constValue->mBool;
  18234. }
  18235. }
  18236. if (isConstBranch)
  18237. {
  18238. if ((constResult) && (!HasVariableDeclaration(rightExpression)))
  18239. {
  18240. // Always true
  18241. SetAndRestoreValue<bool> prevIgnoreWrites(mModule->mBfIRBuilder->mIgnoreWrites, true);
  18242. rightValue = mModule->CreateValueFromExpression(rightExpression, boolType, (BfEvalExprFlags)(mBfEvalExprFlags & BfEvalExprFlags_InheritFlags));
  18243. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConst(BfTypeCode_Boolean, 1), boolType);
  18244. }
  18245. else
  18246. {
  18247. // Only right side
  18248. rightValue = mModule->CreateValueFromExpression(rightExpression, boolType, (BfEvalExprFlags)(mBfEvalExprFlags & BfEvalExprFlags_InheritFlags));
  18249. mResult = rightValue;
  18250. }
  18251. }
  18252. else
  18253. {
  18254. auto rhsBB = mModule->mBfIRBuilder->CreateBlock("lor.rhs");
  18255. auto endBB = mModule->mBfIRBuilder->CreateBlock("lor.end");
  18256. // This makes any 'scope' allocs be dyn since we aren't sure if this will be short-circuited
  18257. SetAndRestoreValue<bool> prevIsConditional(mModule->mCurMethodState->mCurScope->mIsConditional, true);
  18258. mModule->mBfIRBuilder->CreateCondBr(leftValue.mValue, endBB, rhsBB);
  18259. mModule->AddBasicBlock(rhsBB);
  18260. rightValue = mModule->CreateValueFromExpression(rightExpression, boolType, (BfEvalExprFlags)(mBfEvalExprFlags & BfEvalExprFlags_InheritFlags));
  18261. mModule->mBfIRBuilder->CreateBr(endBB);
  18262. auto endRhsBB = mModule->mBfIRBuilder->GetInsertBlock();
  18263. mModule->AddBasicBlock(endBB);
  18264. auto phi = mModule->mBfIRBuilder->CreatePhi(mModule->mBfIRBuilder->MapType(boolType), 2);
  18265. mModule->mBfIRBuilder->AddPhiIncoming(phi, mModule->GetConstValue(1, boolType), prevBB);
  18266. if (rightValue)
  18267. mModule->mBfIRBuilder->AddPhiIncoming(phi, rightValue.mValue, endRhsBB);
  18268. mResult = BfTypedValue(phi, boolType);
  18269. }
  18270. }
  18271. return;
  18272. }
  18273. BfType* wantType = leftValue.mType;
  18274. BfType* origWantType = wantType;
  18275. if ((binaryOp == BfBinaryOp_LeftShift) || (binaryOp == BfBinaryOp_RightShift))
  18276. wantType = NULL; // Don't presume
  18277. wantType = mModule->FixIntUnknown(wantType);
  18278. if ((binaryOp == BfBinaryOp_NullCoalesce) && (PerformBinaryOperation_NullCoalesce(opToken, leftExpression, rightExpression, leftValue, wantType, NULL)))
  18279. return;
  18280. BfType* rightWantType = wantType;
  18281. if (origWantType->IsIntUnknown())
  18282. rightWantType = NULL;
  18283. else if ((mExpectingType != NULL) && (wantType != NULL) && (mExpectingType->IsIntegral()) && (wantType->IsIntegral()) && (mExpectingType->mSize > wantType->mSize) &&
  18284. ((binaryOp == BfBinaryOp_Add) || (binaryOp == BfBinaryOp_Subtract) || (binaryOp == BfBinaryOp_Multiply)))
  18285. rightWantType = mExpectingType;
  18286. rightValue = mModule->CreateValueFromExpression(rightExpression, rightWantType, (BfEvalExprFlags)((mBfEvalExprFlags & BfEvalExprFlags_InheritFlags) | BfEvalExprFlags_NoCast));
  18287. if ((rightWantType != wantType) && (rightValue.mType == rightWantType))
  18288. wantType = rightWantType;
  18289. if ((!leftValue) || (!rightValue))
  18290. return;
  18291. PerformBinaryOperation(leftExpression, rightExpression, binaryOp, opToken, flags, leftValue, rightValue);
  18292. }
  18293. bool BfExprEvaluator::PerformBinaryOperation_NullCoalesce(BfTokenNode* opToken, BfExpression* leftExpression, BfExpression* rightExpression, BfTypedValue leftValue, BfType* wantType, BfTypedValue* assignTo)
  18294. {
  18295. if ((leftValue) && ((leftValue.mType->IsPointer()) || (leftValue.mType->IsFunction()) || (leftValue.mType->IsObject())))
  18296. {
  18297. leftValue = mModule->LoadValue(leftValue);
  18298. auto prevBB = mModule->mBfIRBuilder->GetInsertBlock();
  18299. auto rhsBB = mModule->mBfIRBuilder->CreateBlock("nullc.rhs");
  18300. auto endBB = mModule->mBfIRBuilder->CreateBlock("nullc.end");
  18301. auto lhsBB = endBB;
  18302. auto endLhsBB = prevBB;
  18303. BfIRValue isNull;
  18304. if (leftValue.mType->IsFunction())
  18305. isNull = mModule->mBfIRBuilder->CreateIsNull(
  18306. mModule->mBfIRBuilder->CreateIntToPtr(leftValue.mValue, mModule->mBfIRBuilder->MapType(mModule->GetPrimitiveType(BfTypeCode_NullPtr))));
  18307. else
  18308. isNull = mModule->mBfIRBuilder->CreateIsNull(leftValue.mValue);
  18309. mModule->AddBasicBlock(rhsBB);
  18310. BfTypedValue rightValue;
  18311. if (assignTo != NULL)
  18312. rightValue = mModule->CreateValueFromExpression(rightExpression, wantType, (BfEvalExprFlags)((mBfEvalExprFlags & BfEvalExprFlags_InheritFlags)));
  18313. else
  18314. rightValue = mModule->CreateValueFromExpression(rightExpression, wantType, (BfEvalExprFlags)((mBfEvalExprFlags & BfEvalExprFlags_InheritFlags) | BfEvalExprFlags_NoCast));
  18315. if (!rightValue)
  18316. {
  18317. mModule->AssertErrorState();
  18318. return true;
  18319. }
  18320. rightValue = mModule->LoadValue(rightValue);
  18321. if (assignTo == NULL)
  18322. {
  18323. auto rightToLeftValue = mModule->CastToValue(rightExpression, rightValue, leftValue.mType, BfCastFlags_SilentFail);
  18324. if (rightToLeftValue)
  18325. {
  18326. rightValue = BfTypedValue(rightToLeftValue, leftValue.mType);
  18327. }
  18328. else
  18329. {
  18330. lhsBB = mModule->mBfIRBuilder->CreateBlock("nullc.lhs", true);
  18331. mModule->mBfIRBuilder->SetInsertPoint(lhsBB);
  18332. auto leftToRightValue = mModule->CastToValue(leftExpression, leftValue, rightValue.mType, BfCastFlags_SilentFail);
  18333. if (leftToRightValue)
  18334. {
  18335. leftValue = BfTypedValue(leftToRightValue, rightValue.mType);
  18336. }
  18337. else
  18338. {
  18339. // Note: Annoying trigraph split for '??'
  18340. mModule->Fail(StrFormat("Operator '?" "?' cannot be applied to operands of type '%s' and '%s'",
  18341. mModule->TypeToString(leftValue.mType).c_str(), mModule->TypeToString(rightValue.mType).c_str()), opToken);
  18342. leftValue = mModule->GetDefaultTypedValue(rightValue.mType);
  18343. }
  18344. mModule->mBfIRBuilder->CreateBr(endBB);
  18345. endLhsBB = mModule->mBfIRBuilder->GetInsertBlock();
  18346. mModule->mBfIRBuilder->SetInsertPoint(rhsBB);
  18347. }
  18348. }
  18349. if (assignTo != NULL)
  18350. mModule->mBfIRBuilder->CreateStore(rightValue.mValue, assignTo->mValue);
  18351. mModule->mBfIRBuilder->CreateBr(endBB);
  18352. auto endRhsBB = mModule->mBfIRBuilder->GetInsertBlock();
  18353. // Actually add CondBr at start
  18354. mModule->mBfIRBuilder->SetInsertPoint(prevBB);
  18355. mModule->mBfIRBuilder->CreateCondBr(isNull, rhsBB, lhsBB);
  18356. mModule->AddBasicBlock(endBB);
  18357. if (assignTo != NULL)
  18358. {
  18359. mResult = *assignTo;
  18360. }
  18361. else
  18362. {
  18363. auto phi = mModule->mBfIRBuilder->CreatePhi(mModule->mBfIRBuilder->MapType(leftValue.mType), 2);
  18364. mModule->mBfIRBuilder->AddPhiIncoming(phi, leftValue.mValue, endLhsBB);
  18365. mModule->mBfIRBuilder->AddPhiIncoming(phi, rightValue.mValue, endRhsBB);
  18366. mResult = BfTypedValue(phi, leftValue.mType);
  18367. }
  18368. return true;
  18369. }
  18370. return false;
  18371. }
  18372. void BfExprEvaluator::PerformBinaryOperation(BfExpression* leftExpression, BfExpression* rightExpression, BfBinaryOp binaryOp, BfTokenNode* opToken, BfBinOpFlags flags)
  18373. {
  18374. if ((binaryOp == BfBinaryOp_Range) || (binaryOp == BfBinaryOp_ClosedRange))
  18375. {
  18376. auto intType = mModule->GetPrimitiveType(BfTypeCode_IntPtr);
  18377. bool isIndexExpr = false;
  18378. BfTypeDef* typeDef = NULL;
  18379. if (auto unaryOpExpr = BfNodeDynCast<BfUnaryOperatorExpression>(leftExpression))
  18380. if (unaryOpExpr->mOp == BfUnaryOp_FromEnd)
  18381. isIndexExpr = true;
  18382. if (rightExpression == NULL)
  18383. isIndexExpr = true;
  18384. if (auto unaryOpExpr = BfNodeDynCast<BfUnaryOperatorExpression>(rightExpression))
  18385. if (unaryOpExpr->mOp == BfUnaryOp_FromEnd)
  18386. isIndexExpr = true;
  18387. if (isIndexExpr)
  18388. typeDef = mModule->mCompiler->mIndexRangeTypeDef;
  18389. else
  18390. typeDef = (binaryOp == BfBinaryOp_Range) ? mModule->mCompiler->mRangeTypeDef : mModule->mCompiler->mClosedRangeTypeDef;
  18391. auto allocType = mModule->ResolveTypeDef(typeDef)->ToTypeInstance();
  18392. auto alloca = mModule->CreateAlloca(allocType);
  18393. BfTypedValueExpression leftTypedValueExpr;
  18394. BfTypedValueExpression rightTypedValueExpr;
  18395. BfTypedValueExpression isClosedTypedValueExpr;
  18396. SizedArray<BfExpression*, 2> argExprs;
  18397. if (leftExpression != NULL)
  18398. {
  18399. argExprs.Add(leftExpression);
  18400. }
  18401. else
  18402. {
  18403. leftTypedValueExpr.mRefNode = opToken;
  18404. leftTypedValueExpr.mTypedValue = BfTypedValue(mModule->mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, 0), mModule->GetPrimitiveType(BfTypeCode_IntPtr));
  18405. argExprs.Add(&leftTypedValueExpr);
  18406. }
  18407. if (rightExpression != NULL)
  18408. {
  18409. argExprs.Add(rightExpression);
  18410. }
  18411. else
  18412. {
  18413. // Add as a `^1`
  18414. auto indexType = mModule->ResolveTypeDef(mModule->mCompiler->mIndexTypeDef)->ToTypeInstance();
  18415. rightTypedValueExpr.mRefNode = opToken;
  18416. auto valueTypeEmpty = mModule->mBfIRBuilder->CreateConstAgg(mModule->mBfIRBuilder->MapType(indexType->mBaseType->mBaseType), {});
  18417. SizedArray<BfIRValue, 8> enumMembers;
  18418. enumMembers.Add(valueTypeEmpty);
  18419. auto enumValue = mModule->mBfIRBuilder->CreateConstAgg(mModule->mBfIRBuilder->MapType(indexType->mBaseType), enumMembers);
  18420. SizedArray<BfIRValue, 8> tupleMembers;
  18421. tupleMembers.Add(valueTypeEmpty);
  18422. tupleMembers.Add(mModule->mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, 1));
  18423. auto tupleValue = mModule->mBfIRBuilder->CreateConstAgg(mModule->mBfIRBuilder->MapType(indexType->mFieldInstances[0].mResolvedType), tupleMembers);
  18424. SizedArray<BfIRValue, 8> indexMembers;
  18425. indexMembers.Add(enumValue);
  18426. indexMembers.Add(tupleValue);
  18427. indexMembers.Add(mModule->mBfIRBuilder->CreateConst(BfTypeCode_Int8, 1));
  18428. auto indexValue = mModule->mBfIRBuilder->CreateConstAgg(mModule->mBfIRBuilder->MapType(indexType), indexMembers);
  18429. rightTypedValueExpr.mTypedValue = BfTypedValue(indexValue, indexType);
  18430. argExprs.Add(&rightTypedValueExpr);
  18431. }
  18432. if (isIndexExpr)
  18433. {
  18434. isClosedTypedValueExpr.mRefNode = opToken;
  18435. isClosedTypedValueExpr.mTypedValue = BfTypedValue(mModule->mBfIRBuilder->CreateConst(BfTypeCode_Boolean, (binaryOp == BfBinaryOp_ClosedRange) ? 1 : 0), mModule->GetPrimitiveType(BfTypeCode_Boolean));
  18436. argExprs.Add(&isClosedTypedValueExpr);
  18437. }
  18438. BfSizedArray<BfExpression*> args = argExprs;
  18439. BfResolvedArgs argValues;
  18440. argValues.Init(&args);
  18441. ResolveArgValues(argValues, BfResolveArgsFlag_DeferParamEval);
  18442. mResult = BfTypedValue(alloca, allocType, true);
  18443. MatchConstructor(opToken, NULL, mResult, allocType, argValues, true, false);
  18444. return;
  18445. }
  18446. BfTypedValue leftValue;
  18447. if (leftExpression != NULL)
  18448. {
  18449. leftValue = mModule->CreateValueFromExpression(leftExpression, mExpectingType, (BfEvalExprFlags)((mBfEvalExprFlags & BfEvalExprFlags_InheritFlags) | BfEvalExprFlags_NoCast | BfEvalExprFlags_AllowIntUnknown));
  18450. }
  18451. PerformBinaryOperation(leftExpression, rightExpression, binaryOp, opToken, flags, leftValue);
  18452. }
  18453. bool BfExprEvaluator::CheckConstCompare(BfBinaryOp binaryOp, BfAstNode* opToken, const BfTypedValue& leftValue, const BfTypedValue& rightValue)
  18454. {
  18455. if ((binaryOp < BfBinaryOp_Equality) || (binaryOp > BfBinaryOp_LessThanOrEqual))
  18456. return false;
  18457. // LHS is expected to be a value and RHS is expected to be a const
  18458. if (!leftValue.mType->IsIntegral())
  18459. return false;
  18460. BF_ASSERT(rightValue.mValue.IsConst());
  18461. auto rightConst = mModule->mBfIRBuilder->GetConstant(rightValue.mValue);
  18462. if (!mModule->mBfIRBuilder->IsInt(rightConst->mTypeCode))
  18463. return false;
  18464. BfType* checkType = leftValue.mType;
  18465. if (checkType->IsTypedPrimitive())
  18466. checkType = checkType->GetUnderlyingType();
  18467. if (!checkType->IsPrimitiveType())
  18468. return false;
  18469. BfTypeCode typeCode = ((BfPrimitiveType*)checkType)->mTypeDef->mTypeCode;
  18470. int64 minValue = 0;
  18471. int64 maxValue = 0;
  18472. switch (typeCode)
  18473. {
  18474. case BfTypeCode_Int8:
  18475. minValue = -0x80;
  18476. maxValue = 0x7F;
  18477. break;
  18478. case BfTypeCode_Int16:
  18479. minValue = -0x8000;
  18480. maxValue = 0x7FFF;
  18481. break;
  18482. case BfTypeCode_Int32:
  18483. minValue = -0x80000000LL;
  18484. maxValue = 0x7FFFFFFF;
  18485. break;
  18486. case BfTypeCode_Int64:
  18487. minValue = -0x8000000000000000LL;
  18488. maxValue = 0x7FFFFFFFFFFFFFFFLL;
  18489. break;
  18490. case BfTypeCode_UInt8:
  18491. maxValue = 0xFF;
  18492. break;
  18493. case BfTypeCode_UInt16:
  18494. maxValue = 0xFFFF;
  18495. break;
  18496. case BfTypeCode_UInt32:
  18497. maxValue = 0xFFFFFFFF;
  18498. break;
  18499. default:
  18500. return false;
  18501. }
  18502. int constResult = -1;
  18503. if (typeCode == BfTypeCode_UInt64)
  18504. {
  18505. switch (binaryOp)
  18506. {
  18507. case BfBinaryOp_Equality:
  18508. case BfBinaryOp_StrictEquality:
  18509. if (rightConst->mInt64 < minValue)
  18510. constResult = 0;
  18511. break;
  18512. case BfBinaryOp_InEquality:
  18513. case BfBinaryOp_StrictInEquality:
  18514. if (rightConst->mInt64 < minValue)
  18515. constResult = 1;
  18516. break;
  18517. case BfBinaryOp_LessThan:
  18518. if (rightConst->mInt64 <= minValue)
  18519. constResult = 0;
  18520. break;
  18521. case BfBinaryOp_LessThanOrEqual:
  18522. if (rightConst->mInt64 < minValue)
  18523. constResult = 0;
  18524. break;
  18525. default: break;
  18526. }
  18527. return false;
  18528. }
  18529. else
  18530. {
  18531. switch (binaryOp)
  18532. {
  18533. case BfBinaryOp_Equality:
  18534. case BfBinaryOp_StrictEquality:
  18535. if (rightConst->mInt64 < minValue)
  18536. constResult = 0;
  18537. else if (rightConst->mInt64 > maxValue)
  18538. constResult = 0;
  18539. break;
  18540. case BfBinaryOp_InEquality:
  18541. case BfBinaryOp_StrictInEquality:
  18542. if (rightConst->mInt64 < minValue)
  18543. constResult = 1;
  18544. else if (rightConst->mInt64 > maxValue)
  18545. constResult = 1;
  18546. break;
  18547. case BfBinaryOp_LessThan:
  18548. if (rightConst->mInt64 <= minValue)
  18549. constResult = 0;
  18550. else if (rightConst->mInt64 > maxValue)
  18551. constResult = 1;
  18552. break;
  18553. case BfBinaryOp_LessThanOrEqual:
  18554. if (rightConst->mInt64 < minValue)
  18555. constResult = 0;
  18556. else if (rightConst->mInt64 >= maxValue)
  18557. constResult = 1;
  18558. break;
  18559. case BfBinaryOp_GreaterThan:
  18560. if (rightConst->mInt64 >= maxValue)
  18561. constResult = 0;
  18562. else if (rightConst->mInt64 < minValue)
  18563. constResult = 1;
  18564. break;
  18565. case BfBinaryOp_GreaterThanOrEqual:
  18566. if (rightConst->mInt64 > maxValue)
  18567. constResult = 0;
  18568. else if (rightConst->mInt64 <= minValue)
  18569. constResult = 1;
  18570. break;
  18571. default: break;
  18572. }
  18573. }
  18574. if (constResult == 0)
  18575. {
  18576. mModule->Warn(0, "The result of this operation is always 'false'", opToken);
  18577. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConst(BfTypeCode_Boolean, 0), mModule->GetPrimitiveType(BfTypeCode_Boolean));
  18578. return true;
  18579. }
  18580. else if (constResult == 1)
  18581. {
  18582. mModule->Warn(0, "The result of this operation is always 'true'", opToken);
  18583. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConst(BfTypeCode_Boolean, 1), mModule->GetPrimitiveType(BfTypeCode_Boolean));
  18584. return true;
  18585. }
  18586. return false;
  18587. }
  18588. void BfExprEvaluator::AddStrings(const BfTypedValue& leftValue, const BfTypedValue& rightValue, BfAstNode* refNode)
  18589. {
  18590. if ((leftValue.mValue.IsConst()) && (rightValue.mValue.IsConst()))
  18591. {
  18592. String* lhsStr = mModule->GetStringPoolString(leftValue.mValue, mModule->mBfIRBuilder);
  18593. String* rhsStr = mModule->GetStringPoolString(rightValue.mValue, mModule->mBfIRBuilder);
  18594. if ((lhsStr != NULL) && (rhsStr != NULL))
  18595. {
  18596. String resultStr = *lhsStr + *rhsStr;
  18597. BfVariant variant;
  18598. variant.mTypeCode = BfTypeCode_CharPtr;
  18599. variant.mString = &resultStr;
  18600. GetLiteral(refNode, variant);
  18601. return;
  18602. }
  18603. }
  18604. mModule->Fail("Strings can only be added when they are constants. Consider allocating a string and using Concat.", refNode);
  18605. return;
  18606. }
  18607. void BfExprEvaluator::PerformBinaryOperation(BfAstNode* leftExpression, BfAstNode* rightExpression, BfBinaryOp binaryOp, BfAstNode* opToken, BfBinOpFlags flags, BfTypedValue leftValue, BfTypedValue rightValue)
  18608. {
  18609. bool noClassify = (flags & BfBinOpFlag_NoClassify) != 0;
  18610. bool forceLeftType = (flags & BfBinOpFlag_ForceLeftType) != 0;
  18611. bool deferRight = (flags & BfBinOpFlag_DeferRight) != 0;
  18612. if (deferRight)
  18613. {
  18614. rightValue = mModule->GetDefaultTypedValue(mModule->GetPrimitiveType(BfTypeCode_Var));
  18615. }
  18616. if ((rightValue.mValue.IsConst()) && (!leftValue.mValue.IsConst()))
  18617. {
  18618. if (CheckConstCompare(binaryOp, opToken, leftValue, rightValue))
  18619. return;
  18620. }
  18621. else if ((leftValue.mValue.IsConst()) && (!rightValue.mValue.IsConst()))
  18622. {
  18623. if (CheckConstCompare(BfGetOppositeBinaryOp(binaryOp), opToken, rightValue, leftValue))
  18624. return;
  18625. }
  18626. if ((binaryOp == BfBinaryOp_LeftShift) || (binaryOp == BfBinaryOp_RightShift))
  18627. {
  18628. forceLeftType = true;
  18629. }
  18630. if (rightValue.mType->IsRef())
  18631. rightValue.mType = rightValue.mType->GetUnderlyingType();
  18632. mModule->FixIntUnknown(leftValue, rightValue);
  18633. // Prefer floats, prefer chars
  18634. int leftCompareSize = leftValue.mType->mSize;
  18635. if (leftValue.mType->IsFloat())
  18636. leftCompareSize += 0x10;
  18637. if (leftValue.mType->IsChar())
  18638. leftCompareSize += 0x100;
  18639. if (!leftValue.mType->IsPrimitiveType())
  18640. leftCompareSize += 0x1000;
  18641. int rightCompareSize = rightValue.mType->mSize;
  18642. if (rightValue.mType->IsFloat())
  18643. rightCompareSize += 0x10;
  18644. if (rightValue.mType->IsChar())
  18645. rightCompareSize += 0x100;
  18646. if (!rightValue.mType->IsPrimitiveType())
  18647. rightCompareSize += 0x1000;
  18648. if ((leftValue.mType->IsTypeInstance()) && (rightValue.mType->IsTypeInstance()))
  18649. {
  18650. int leftInheritDepth = leftValue.mType->ToTypeInstance()->mInheritDepth;
  18651. int rightInheritDepth = rightValue.mType->ToTypeInstance()->mInheritDepth;
  18652. if (leftInheritDepth < rightInheritDepth)
  18653. {
  18654. // If both are type instances then choose the type with the lowest inherit depth
  18655. // so we will choose the base type when applicable
  18656. forceLeftType = true;
  18657. }
  18658. }
  18659. auto resultType = leftValue.mType;
  18660. if (!forceLeftType)
  18661. {
  18662. bool handled = false;
  18663. if (leftValue.mType == rightValue.mType)
  18664. {
  18665. // All good
  18666. handled = true;
  18667. }
  18668. else if ((mExpectingType != NULL) &&
  18669. (mModule->CanCast(leftValue, mExpectingType, BfCastFlags_NoBox)) &&
  18670. (mModule->CanCast(rightValue, mExpectingType, BfCastFlags_NoBox)) &&
  18671. (!leftValue.mType->IsVar()) && (!rightValue.mType->IsVar()))
  18672. {
  18673. resultType = mExpectingType;
  18674. handled = true;
  18675. }
  18676. else
  18677. {
  18678. // If one of these is a constant that can be converted into a smaller type, then do that
  18679. if (rightValue.mValue.IsConst())
  18680. {
  18681. if (mModule->CanCast(rightValue, leftValue.mType, BfCastFlags_NoBox))
  18682. {
  18683. resultType = leftValue.mType;
  18684. handled = true;
  18685. }
  18686. }
  18687. // If left is an IntUnknown, allow the right to inform the type
  18688. if (leftValue.mType->IsIntUnknown())
  18689. {
  18690. if (leftValue.mValue.IsConst())
  18691. {
  18692. if (mModule->CanCast(leftValue, rightValue.mType))
  18693. {
  18694. resultType = rightValue.mType;
  18695. handled = true;
  18696. }
  18697. }
  18698. }
  18699. if ((leftValue.mType->IsPointer()) &&
  18700. (rightValue.mType->IsPointer()))
  18701. {
  18702. BfPointerType* leftPointerType = (BfPointerType*)leftValue.mType;
  18703. BfPointerType* rightPointerType = (BfPointerType*)rightValue.mType;
  18704. // If one is a pointer to a sized array then use the other type
  18705. if (leftPointerType->mElementType->IsSizedArray())
  18706. {
  18707. resultType = rightPointerType;
  18708. handled = true;
  18709. }
  18710. else if (rightPointerType->mElementType->IsSizedArray())
  18711. {
  18712. resultType = leftPointerType;
  18713. handled = true;
  18714. }
  18715. }
  18716. }
  18717. if (!handled)
  18718. {
  18719. if ((resultType->IsNull()) ||
  18720. (rightCompareSize > leftCompareSize) ||
  18721. (((rightCompareSize == leftCompareSize) && (!rightValue.mType->IsSigned()))) ||
  18722. (rightValue.mType->IsTypedPrimitive()))
  18723. {
  18724. // Select the type with the "most information"
  18725. if (!rightValue.mType->IsNull())
  18726. resultType = rightValue.mType;
  18727. }
  18728. if ((!resultType->IsPointer()) && (rightValue.mType->IsPointer()))
  18729. resultType = rightValue.mType;
  18730. }
  18731. }
  18732. bool explicitCast = false;
  18733. BfTypedValue* resultTypedValue;
  18734. BfTypedValue* otherTypedValue;
  18735. BfType* otherType;
  18736. BfAstNode* resultTypeSrc;
  18737. BfAstNode* otherTypeSrc;
  18738. if (resultType == leftValue.mType)
  18739. {
  18740. resultTypedValue = &leftValue;
  18741. resultTypeSrc = leftExpression;
  18742. otherTypedValue = &rightValue;
  18743. otherTypeSrc = rightExpression;
  18744. otherType = otherTypedValue->mType;
  18745. }
  18746. else
  18747. {
  18748. resultTypedValue = &rightValue;
  18749. resultTypeSrc = rightExpression;
  18750. otherTypedValue = &leftValue;
  18751. otherTypeSrc = leftExpression;
  18752. otherType = otherTypedValue->mType;
  18753. }
  18754. auto _OpFail = [&]()
  18755. {
  18756. if ((rightValue.mType != NULL) && (leftValue.mType != NULL))
  18757. {
  18758. if (rightValue.mType != leftValue.mType)
  18759. mModule->Fail(StrFormat("Cannot perform binary operation '%s' between types '%s' and '%s'",
  18760. BfGetOpName(binaryOp), mModule->TypeToString(leftValue.mType).c_str(), mModule->TypeToString(rightValue.mType).c_str()), opToken);
  18761. else
  18762. {
  18763. if (leftValue.mType->IsInterface())
  18764. {
  18765. 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.",
  18766. BfGetOpName(binaryOp), mModule->TypeToString(leftValue.mType).c_str()), opToken);
  18767. }
  18768. else
  18769. {
  18770. mModule->Fail(StrFormat("Cannot perform binary operation '%s' between two instances of type '%s'",
  18771. BfGetOpName(binaryOp), mModule->TypeToString(leftValue.mType).c_str()), opToken);
  18772. }
  18773. }
  18774. }
  18775. else
  18776. mModule->Fail(StrFormat("Cannot perform binary operation '%s'", BfGetOpName(binaryOp)), opToken);
  18777. };
  18778. // This case fixes cases like "c == 0" where "0" is technically an int but can be reduced
  18779. if (BfBinOpEqualityCheck(binaryOp))
  18780. {
  18781. if ((resultType != otherType) && (resultTypedValue->mValue.IsConst()) && (mModule->CanCast(*resultTypedValue, otherType)))
  18782. {
  18783. std::swap(resultTypedValue, otherTypedValue);
  18784. std::swap(resultTypeSrc, otherTypeSrc);
  18785. std::swap(resultType, otherType);
  18786. }
  18787. }
  18788. BfIRValue convLeftValue;
  18789. BfIRValue convRightValue;
  18790. if (((resultType->IsVar()) || (otherType->IsVar())) && (!deferRight))
  18791. {
  18792. bool isComparison = (binaryOp >= BfBinaryOp_Equality) && (binaryOp <= BfBinaryOp_LessThanOrEqual);
  18793. if (isComparison)
  18794. mResult = mModule->GetDefaultTypedValue(mModule->GetPrimitiveType(BfTypeCode_Boolean), false, BfDefaultValueKind_Addr);
  18795. else if (mExpectingType != NULL)
  18796. mResult = mModule->GetDefaultTypedValue(mExpectingType, false, BfDefaultValueKind_Addr);
  18797. else
  18798. mResult = mModule->GetDefaultTypedValue(resultType, false, BfDefaultValueKind_Addr);
  18799. return;
  18800. }
  18801. if ((otherType->IsNull()) && (BfBinOpEqualityCheck(binaryOp)))
  18802. {
  18803. bool isEquality = (binaryOp == BfBinaryOp_Equality) || (binaryOp == BfBinaryOp_StrictEquality);
  18804. if ((resultType->IsValueType()) && (!resultType->IsFunction()))
  18805. {
  18806. auto boolType = mModule->GetPrimitiveType(BfTypeCode_Boolean);
  18807. if (resultType->IsNullable())
  18808. {
  18809. auto elementType = resultType->GetUnderlyingType();
  18810. mModule->PopulateType(elementType);
  18811. if (elementType->IsValuelessType())
  18812. {
  18813. mModule->mBfIRBuilder->PopulateType(resultType);
  18814. BfTypedValue nullableTypedVale = mModule->MakeAddressable(*resultTypedValue);
  18815. BfIRValue hasValuePtr = mModule->mBfIRBuilder->CreateInBoundsGEP(nullableTypedVale.mValue, 0, 1);
  18816. BfIRValue hasValueValue = mModule->mBfIRBuilder->CreateLoad(hasValuePtr);
  18817. if (isEquality)
  18818. hasValueValue = mModule->mBfIRBuilder->CreateNot(hasValueValue);
  18819. mResult = BfTypedValue(hasValueValue, boolType);
  18820. }
  18821. else
  18822. {
  18823. mModule->mBfIRBuilder->PopulateType(resultType);
  18824. BfTypedValue nullableTypedVale = mModule->MakeAddressable(*resultTypedValue);
  18825. BfIRValue hasValuePtr = mModule->mBfIRBuilder->CreateInBoundsGEP(nullableTypedVale.mValue, 0, 2);
  18826. BfIRValue hasValueValue = mModule->mBfIRBuilder->CreateLoad(hasValuePtr);
  18827. if (isEquality)
  18828. hasValueValue = mModule->mBfIRBuilder->CreateNot(hasValueValue);
  18829. mResult = BfTypedValue(hasValueValue, boolType);
  18830. }
  18831. return;
  18832. }
  18833. if (resultType->IsNull())
  18834. {
  18835. // Null always equals null
  18836. mResult = BfTypedValue(mModule->GetConstValue(isEquality ? 1 : 0, boolType), boolType);
  18837. return;
  18838. }
  18839. if (!mModule->IsInSpecializedSection())
  18840. {
  18841. //CS0472: The result of the expression is always 'true' since a value of type 'int' is never equal to 'null' of type '<null>'
  18842. mModule->Warn(BfWarning_CS0472_ValueTypeNullCompare,
  18843. StrFormat("The result of the expression is always '%s' since a value of type '%s' can never be null",
  18844. isEquality ? "false" : "true", mModule->TypeToString(resultType).c_str()), otherTypeSrc);
  18845. }
  18846. // Valuetypes never equal null
  18847. mResult = BfTypedValue(mModule->GetConstValue(isEquality ? 0 : 1, boolType), boolType);
  18848. return;
  18849. }
  18850. }
  18851. // Check for constant equality checks (mostly for strings)
  18852. if (BfBinOpEqualityCheck(binaryOp))
  18853. {
  18854. auto leftConstant = mModule->mBfIRBuilder->GetConstant(leftValue.mValue);
  18855. auto rightConstant = mModule->mBfIRBuilder->GetConstant(rightValue.mValue);
  18856. if ((leftConstant != NULL) && (rightConstant != NULL))
  18857. {
  18858. auto boolType = mModule->GetPrimitiveType(BfTypeCode_Boolean);
  18859. int leftStringPoolIdx = mModule->GetStringPoolIdx(leftValue.mValue, mModule->mBfIRBuilder);
  18860. if (leftStringPoolIdx != -1)
  18861. {
  18862. int rightStringPoolIdx = mModule->GetStringPoolIdx(rightValue.mValue, mModule->mBfIRBuilder);
  18863. if (rightStringPoolIdx != -1)
  18864. {
  18865. bool isEqual = leftStringPoolIdx == rightStringPoolIdx;
  18866. if ((binaryOp == BfBinaryOp_InEquality) || (binaryOp == BfBinaryOp_StrictInEquality))
  18867. isEqual = !isEqual;
  18868. mResult = BfTypedValue(mModule->GetConstValue(isEqual ? 1 : 0, boolType), boolType);
  18869. return;
  18870. }
  18871. }
  18872. int eqResult = mModule->mBfIRBuilder->CheckConstEquality(leftValue.mValue, rightValue.mValue);
  18873. if (eqResult != -1)
  18874. {
  18875. bool isEqual = eqResult == 1;
  18876. if ((binaryOp == BfBinaryOp_InEquality) || (binaryOp == BfBinaryOp_StrictInEquality))
  18877. isEqual = !isEqual;
  18878. mResult = BfTypedValue(mModule->GetConstValue(isEqual ? 1 : 0, boolType), boolType);
  18879. return;
  18880. }
  18881. }
  18882. }
  18883. if ((leftValue.mType->IsTypeInstance()) || (leftValue.mType->IsGenericParam()) ||
  18884. (rightValue.mType->IsTypeInstance()) || (rightValue.mType->IsGenericParam()))
  18885. {
  18886. // As an optimization, we don't call user operator overloads for null checks
  18887. bool skipOpOverload = false;
  18888. if ((binaryOp == BfBinaryOp_StrictEquality) || (binaryOp == BfBinaryOp_StrictInEquality))
  18889. skipOpOverload = true;
  18890. else if (BfBinOpEqualityCheck(binaryOp))
  18891. {
  18892. if (!leftValue.IsAddr())
  18893. {
  18894. auto leftConstant = mModule->mBfIRBuilder->GetConstant(leftValue.mValue);
  18895. if ((leftConstant != NULL) && (leftConstant->IsNull()))
  18896. skipOpOverload = true;
  18897. }
  18898. if (!rightValue.IsAddr())
  18899. {
  18900. auto rightConstant = mModule->mBfIRBuilder->GetConstant(rightValue.mValue);
  18901. if ((rightConstant != NULL) && (rightConstant->IsNull()))
  18902. skipOpOverload = true;
  18903. }
  18904. }
  18905. if ((binaryOp == BfBinaryOp_Add) && (resultType->IsInstanceOf(mModule->mCompiler->mStringTypeDef)))
  18906. {
  18907. // Allow failover to constant string addition
  18908. if ((leftValue.mValue.IsConst()) && (rightValue.mValue.IsConst()))
  18909. skipOpOverload = true;
  18910. }
  18911. if (!skipOpOverload)
  18912. {
  18913. BfBinaryOp findBinaryOp = binaryOp;
  18914. bool isComparison = (binaryOp >= BfBinaryOp_Equality) && (binaryOp <= BfBinaryOp_LessThanOrEqual);
  18915. for (int pass = 0; pass < 2; pass++)
  18916. {
  18917. BfBinaryOp oppositeBinaryOp = BfGetOppositeBinaryOp(findBinaryOp);
  18918. BfBinaryOp overflowBinaryOp = BfBinaryOp_None;
  18919. if (findBinaryOp == BfBinaryOp_OverflowAdd)
  18920. overflowBinaryOp = BfBinaryOp_Add;
  18921. else if (findBinaryOp == BfBinaryOp_OverflowSubtract)
  18922. overflowBinaryOp = BfBinaryOp_Subtract;
  18923. else if (findBinaryOp == BfBinaryOp_OverflowMultiply)
  18924. overflowBinaryOp = BfBinaryOp_Multiply;
  18925. bool foundOp = false;
  18926. BfResolvedArg leftArg;
  18927. leftArg.mExpression = leftExpression;
  18928. leftArg.mTypedValue = leftValue;
  18929. BfResolvedArg rightArg;
  18930. rightArg.mExpression = rightExpression;
  18931. rightArg.mTypedValue = rightValue;
  18932. if (deferRight)
  18933. {
  18934. BfResolvedArgs argValues;
  18935. SizedArray<BfExpression*, 2> argExprs;
  18936. argExprs.push_back(BfNodeDynCast<BfExpression>(rightExpression));
  18937. BfSizedArray<BfExpression*> sizedArgExprs(argExprs);
  18938. argValues.Init(&sizedArgExprs);
  18939. ResolveArgValues(argValues, BfResolveArgsFlag_DeferParamEval);
  18940. rightArg = argValues.mResolvedArgs[0];
  18941. }
  18942. SizedArray<BfResolvedArg, 2> args;
  18943. if (pass == 0)
  18944. {
  18945. args.push_back(leftArg);
  18946. args.push_back(rightArg);
  18947. }
  18948. else
  18949. {
  18950. args.push_back(rightArg);
  18951. args.push_back(leftArg);
  18952. }
  18953. auto checkLeftType = leftValue.mType;
  18954. auto checkRightType = rightValue.mType;
  18955. BfMethodMatcher methodMatcher(opToken, mModule, "", args, NULL);
  18956. methodMatcher.mAllowImplicitRef = true;
  18957. methodMatcher.mBfEvalExprFlags = BfEvalExprFlags_NoAutoComplete;
  18958. BfBaseClassWalker baseClassWalker(checkLeftType, checkRightType, mModule);
  18959. bool invertResult = false;
  18960. BfType* operatorConstraintReturnType = NULL;
  18961. bool wasTransformedUsage = (pass == 1);
  18962. while (true)
  18963. {
  18964. auto entry = baseClassWalker.Next();
  18965. auto checkType = entry.mTypeInstance;
  18966. if (checkType == NULL)
  18967. break;
  18968. bool foundExactMatch = false;
  18969. SizedArray<BfOperatorDef*, 8> oppositeOperatorDefs;
  18970. for (auto operatorDef : checkType->mTypeDef->mOperators)
  18971. {
  18972. bool allowOp = operatorDef->mOperatorDeclaration->mBinOp == findBinaryOp;
  18973. if ((isComparison) && (operatorDef->mOperatorDeclaration->mBinOp == BfBinaryOp_Compare))
  18974. allowOp = true;
  18975. if (allowOp)
  18976. {
  18977. foundOp = true;
  18978. if (!methodMatcher.IsMemberAccessible(checkType, operatorDef->mDeclaringType))
  18979. continue;
  18980. if ((flags & BfBinOpFlag_IsConstraintCheck) != 0)
  18981. {
  18982. if (operatorDef->mGenericParams.IsEmpty())
  18983. {
  18984. // Fast check
  18985. auto returnType = mModule->CheckOperator(checkType, operatorDef, args[0].mTypedValue, args[1].mTypedValue);
  18986. if (returnType != NULL)
  18987. {
  18988. operatorConstraintReturnType = returnType;
  18989. methodMatcher.mBestMethodDef = operatorDef;
  18990. methodMatcher.mBestMethodTypeInstance = checkType;
  18991. foundExactMatch = true;
  18992. }
  18993. }
  18994. else
  18995. {
  18996. if (methodMatcher.CheckMethod(NULL, checkType, operatorDef, false))
  18997. {
  18998. auto rawMethodInstance = mModule->GetRawMethodInstance(checkType, operatorDef);
  18999. auto returnType = mModule->ResolveGenericType(rawMethodInstance->mReturnType, NULL, &methodMatcher.mBestMethodGenericArguments);
  19000. if (returnType != NULL)
  19001. {
  19002. operatorConstraintReturnType = returnType;
  19003. foundExactMatch = true;
  19004. }
  19005. }
  19006. }
  19007. }
  19008. else
  19009. {
  19010. if (methodMatcher.CheckMethod(NULL, checkType, operatorDef, false))
  19011. {
  19012. methodMatcher.mSelfType = entry.mSrcType;
  19013. if (operatorDef->mOperatorDeclaration->mBinOp == findBinaryOp)
  19014. foundExactMatch = true;
  19015. }
  19016. }
  19017. }
  19018. else if ((operatorDef->mOperatorDeclaration->mBinOp == oppositeBinaryOp) || (operatorDef->mOperatorDeclaration->mBinOp == overflowBinaryOp))
  19019. oppositeOperatorDefs.Add(operatorDef);
  19020. }
  19021. if ((((methodMatcher.mBestMethodDef == NULL) && (operatorConstraintReturnType == NULL)) || (!foundExactMatch)) && (!oppositeOperatorDefs.IsEmpty()))
  19022. {
  19023. foundOp = true;
  19024. for (auto oppositeOperatorDef : oppositeOperatorDefs)
  19025. {
  19026. if ((flags & BfBinOpFlag_IsConstraintCheck) != 0)
  19027. {
  19028. if (oppositeOperatorDef->mGenericParams.IsEmpty())
  19029. {
  19030. // Fast check
  19031. auto returnType = mModule->CheckOperator(checkType, oppositeOperatorDef, args[0].mTypedValue, args[1].mTypedValue);
  19032. if (returnType != NULL)
  19033. {
  19034. operatorConstraintReturnType = returnType;
  19035. methodMatcher.mBestMethodDef = oppositeOperatorDef;
  19036. methodMatcher.mBestMethodTypeInstance = checkType;
  19037. methodMatcher.mSelfType = entry.mSrcType;
  19038. if (oppositeBinaryOp != BfBinaryOp_None)
  19039. wasTransformedUsage = true;
  19040. }
  19041. }
  19042. else
  19043. {
  19044. if (methodMatcher.CheckMethod(NULL, checkType, oppositeOperatorDef, false))
  19045. {
  19046. auto rawMethodInstance = mModule->GetRawMethodInstance(checkType, oppositeOperatorDef);
  19047. auto returnType = mModule->ResolveGenericType(rawMethodInstance->mReturnType, NULL, &methodMatcher.mBestMethodGenericArguments);
  19048. if (returnType != NULL)
  19049. {
  19050. operatorConstraintReturnType = returnType;
  19051. methodMatcher.mSelfType = entry.mSrcType;
  19052. if (oppositeBinaryOp != BfBinaryOp_None)
  19053. wasTransformedUsage = true;
  19054. }
  19055. }
  19056. }
  19057. }
  19058. else
  19059. {
  19060. if (methodMatcher.CheckMethod(NULL, checkType, oppositeOperatorDef, false))
  19061. {
  19062. methodMatcher.mSelfType = entry.mSrcType;
  19063. if (oppositeBinaryOp != BfBinaryOp_None)
  19064. wasTransformedUsage = true;
  19065. }
  19066. }
  19067. }
  19068. }
  19069. }
  19070. bool hadMatch = (methodMatcher.mBestMethodDef != NULL);
  19071. if ((methodMatcher.mBestMethodDef != NULL) && ((flags & BfBinOpFlag_IgnoreOperatorWithWrongResult) != 0))
  19072. {
  19073. auto matchedOp = ((BfOperatorDeclaration*)methodMatcher.mBestMethodDef->mMethodDeclaration)->mBinOp;
  19074. methodMatcher.mBestMethodInstance = GetSelectedMethod(methodMatcher.mTargetSrc, methodMatcher.mBestMethodTypeInstance, methodMatcher.mBestMethodDef, methodMatcher);
  19075. if ((methodMatcher.mBestMethodInstance.mMethodInstance->mReturnType != mExpectingType) &&
  19076. ((matchedOp == binaryOp) || (matchedOp == oppositeBinaryOp)))
  19077. {
  19078. if (binaryOp == BfBinaryOp_Equality)
  19079. binaryOp = BfBinaryOp_StrictEquality;
  19080. if (binaryOp == BfBinaryOp_InEquality)
  19081. binaryOp = BfBinaryOp_StrictEquality;
  19082. hadMatch = false;
  19083. break;
  19084. }
  19085. }
  19086. if (hadMatch)
  19087. {
  19088. methodMatcher.FlushAmbiguityError();
  19089. auto matchedOp = ((BfOperatorDeclaration*)methodMatcher.mBestMethodDef->mMethodDeclaration)->mBinOp;
  19090. bool invertResult = matchedOp == oppositeBinaryOp;
  19091. auto methodDef = methodMatcher.mBestMethodDef;
  19092. auto autoComplete = GetAutoComplete();
  19093. bool wasCapturingMethodInfo = false;
  19094. if ((autoComplete != NULL) && (autoComplete->IsAutocompleteNode(opToken)))
  19095. {
  19096. auto operatorDecl = BfNodeDynCast<BfOperatorDeclaration>(methodDef->mMethodDeclaration);
  19097. if ((operatorDecl != NULL) && (operatorDecl->mOpTypeToken != NULL))
  19098. autoComplete->SetDefinitionLocation(operatorDecl->mOpTypeToken);
  19099. }
  19100. if ((wasTransformedUsage) && (methodDef->mCommutableKind != BfCommutableKind_Operator))
  19101. {
  19102. auto error = mModule->Warn(BfWarning_BF4206_OperatorCommutableUsage, "Transformed operator usage requires 'Commutable' attribute to be added to the operator declaration", opToken);
  19103. if ((error != NULL) && (methodDef->GetRefNode() != NULL))
  19104. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("See operator declaration"), methodDef->GetRefNode());
  19105. }
  19106. if (opToken != NULL)
  19107. {
  19108. if ((opToken->IsA<BfTokenNode>()) && (!noClassify) && (!baseClassWalker.mMayBeFromInterface))
  19109. mModule->SetElementType(opToken, BfSourceElementType_Method);
  19110. }
  19111. if ((flags & BfBinOpFlag_IsConstraintCheck) != 0)
  19112. {
  19113. mResult = BfTypedValue(mModule->mBfIRBuilder->GetFakeVal(), operatorConstraintReturnType);
  19114. }
  19115. else
  19116. {
  19117. SetAndRestoreValue<BfEvalExprFlags> prevFlags(mBfEvalExprFlags, (BfEvalExprFlags)(mBfEvalExprFlags | BfEvalExprFlags_NoAutoComplete));
  19118. mResult = CreateCall(&methodMatcher, BfTypedValue());
  19119. }
  19120. if ((mResult.mType != NULL) && (methodMatcher.mSelfType != NULL) && (mResult.mType->IsSelf()))
  19121. {
  19122. BF_ASSERT(mModule->IsInGeneric());
  19123. mResult = mModule->GetDefaultTypedValue(methodMatcher.mSelfType, false, BfDefaultValueKind_Value);
  19124. }
  19125. if ((invertResult) && (mResult.mType == mModule->GetPrimitiveType(BfTypeCode_Boolean)))
  19126. mResult.mValue = mModule->mBfIRBuilder->CreateNot(mResult.mValue);
  19127. if (pass == 1)
  19128. {
  19129. if (findBinaryOp == BfBinaryOp_Compare)
  19130. {
  19131. mResult = mModule->LoadValue(mResult);
  19132. if (mResult.mType->IsIntegral())
  19133. mResult.mValue = mModule->mBfIRBuilder->CreateNeg(mResult.mValue);
  19134. }
  19135. }
  19136. if ((isComparison) && (matchedOp == BfBinaryOp_Compare))
  19137. {
  19138. auto intType = mModule->GetPrimitiveType(BfTypeCode_IntPtr);
  19139. mResult = mModule->LoadValue(mResult);
  19140. if (mResult.mType != intType)
  19141. mResult = mModule->GetDefaultTypedValue(intType);
  19142. auto zeroVal = mModule->mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, 0);
  19143. auto useBinaryOp = binaryOp;
  19144. if (pass == 1)
  19145. useBinaryOp = BfGetFlippedBinaryOp(useBinaryOp);
  19146. auto boolType = mModule->GetPrimitiveType(BfTypeCode_Boolean);
  19147. switch (useBinaryOp)
  19148. {
  19149. case BfBinaryOp_Equality:
  19150. case BfBinaryOp_StrictEquality:
  19151. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateCmpEQ(mResult.mValue, zeroVal), boolType);
  19152. break;
  19153. case BfBinaryOp_InEquality:
  19154. case BfBinaryOp_StrictInEquality:
  19155. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateCmpNE(mResult.mValue, zeroVal), boolType);
  19156. break;
  19157. case BfBinaryOp_GreaterThan:
  19158. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateCmpGT(mResult.mValue, zeroVal, true), boolType);
  19159. break;
  19160. case BfBinaryOp_LessThan:
  19161. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateCmpLT(mResult.mValue, zeroVal, true), boolType);
  19162. break;
  19163. case BfBinaryOp_GreaterThanOrEqual:
  19164. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateCmpGTE(mResult.mValue, zeroVal, true), boolType);
  19165. break;
  19166. case BfBinaryOp_LessThanOrEqual:
  19167. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateCmpLTE(mResult.mValue, zeroVal, true), boolType);
  19168. break;
  19169. default: break;
  19170. }
  19171. }
  19172. return;
  19173. }
  19174. auto _CheckBinaryOp = [&](BfGenericParamInstance* genericParam)
  19175. {
  19176. for (auto& opConstraint : genericParam->mOperatorConstraints)
  19177. {
  19178. BfType* returnType = genericParam->mExternType;
  19179. bool works = false;
  19180. if (opConstraint.mBinaryOp == findBinaryOp)
  19181. {
  19182. if ((mModule->CanCast(args[0].mTypedValue, opConstraint.mLeftType)) &&
  19183. (mModule->CanCast(args[1].mTypedValue, opConstraint.mRightType)))
  19184. {
  19185. works = true;
  19186. }
  19187. }
  19188. if ((isComparison) && (opConstraint.mBinaryOp == BfBinaryOp_Compare))
  19189. {
  19190. if ((mModule->CanCast(args[0].mTypedValue, opConstraint.mLeftType)) &&
  19191. (mModule->CanCast(args[1].mTypedValue, opConstraint.mRightType)))
  19192. {
  19193. works = true;
  19194. }
  19195. else if ((mModule->CanCast(args[0].mTypedValue, opConstraint.mRightType)) &&
  19196. (mModule->CanCast(args[1].mTypedValue, opConstraint.mLeftType)))
  19197. {
  19198. works = true;
  19199. }
  19200. if (works)
  19201. {
  19202. returnType = mModule->GetPrimitiveType(BfTypeCode_Boolean);
  19203. }
  19204. }
  19205. if (works)
  19206. {
  19207. BF_ASSERT(genericParam->mExternType != NULL);
  19208. mResult = BfTypedValue(mModule->mBfIRBuilder->GetFakeVal(), returnType);
  19209. return true;
  19210. }
  19211. }
  19212. return false;
  19213. };
  19214. // Check method generic constraints
  19215. if ((mModule->mCurMethodInstance != NULL) && (mModule->mCurMethodInstance->mIsUnspecialized) && (mModule->mCurMethodInstance->mMethodInfoEx != NULL))
  19216. {
  19217. for (int genericParamIdx = 0; genericParamIdx < mModule->mCurMethodInstance->mMethodInfoEx->mGenericParams.size(); genericParamIdx++)
  19218. {
  19219. auto genericParam = mModule->mCurMethodInstance->mMethodInfoEx->mGenericParams[genericParamIdx];
  19220. if (_CheckBinaryOp(genericParam))
  19221. return;
  19222. }
  19223. }
  19224. // Check type generic constraints
  19225. if ((mModule->mCurTypeInstance->IsGenericTypeInstance()) && (mModule->mCurTypeInstance->IsUnspecializedType()))
  19226. {
  19227. SizedArray<BfGenericParamInstance*, 4> genericParams;
  19228. mModule->GetActiveTypeGenericParamInstances(genericParams);
  19229. for (auto genericParam : genericParams)
  19230. {
  19231. if (_CheckBinaryOp(genericParam))
  19232. return;
  19233. }
  19234. }
  19235. if (pass == 1)
  19236. break;
  19237. auto flippedBinaryOp = BfGetFlippedBinaryOp(findBinaryOp);
  19238. if (flippedBinaryOp != BfBinaryOp_None)
  19239. findBinaryOp = flippedBinaryOp;
  19240. }
  19241. auto prevResultType = resultType;
  19242. if ((leftValue.mType->IsPrimitiveType()) && (!rightValue.mType->IsTypedPrimitive()))
  19243. resultType = leftValue.mType;
  19244. if ((rightValue.mType->IsPrimitiveType()) && (!leftValue.mType->IsTypedPrimitive()))
  19245. resultType = rightValue.mType;
  19246. }
  19247. }
  19248. if (deferRight)
  19249. {
  19250. auto expectedType = resultType;
  19251. if ((binaryOp == BfBinaryOp_LeftShift) || (binaryOp == BfBinaryOp_RightShift))
  19252. expectedType = mModule->GetPrimitiveType(BfTypeCode_IntPtr);
  19253. rightValue = mModule->CreateValueFromExpression(BfNodeDynCast<BfExpression>(rightExpression), expectedType, (BfEvalExprFlags)((mBfEvalExprFlags & BfEvalExprFlags_InheritFlags) | BfEvalExprFlags_AllowSplat | BfEvalExprFlags_NoCast));
  19254. if (rightValue)
  19255. PerformBinaryOperation(leftExpression, rightExpression, binaryOp, opToken, (BfBinOpFlags)(flags & ~BfBinOpFlag_DeferRight), leftValue, rightValue);
  19256. return;
  19257. }
  19258. if (mModule->IsUnboundGeneric(resultType))
  19259. {
  19260. mResult = mModule->GetDefaultTypedValue(mModule->GetPrimitiveType(BfTypeCode_Var));
  19261. return;
  19262. }
  19263. if (resultType->IsPointer() && otherType->IsPointer())
  19264. {
  19265. if ((binaryOp == BfBinaryOp_Add) && (resultType == otherType) &&
  19266. (resultType->GetUnderlyingType() == mModule->GetPrimitiveType(BfTypeCode_Char8)))
  19267. {
  19268. AddStrings(leftValue, rightValue, opToken);
  19269. return;
  19270. }
  19271. //TODO: Allow all pointer comparisons, but only allow SUBTRACTION between equal pointer types
  19272. if ((binaryOp == BfBinaryOp_Subtract) || (binaryOp == BfBinaryOp_OverflowSubtract))
  19273. {
  19274. if (!mModule->CanCast(*otherTypedValue, resultType))
  19275. {
  19276. mModule->Fail(StrFormat("Operands '%s' and '%s' are not comparable types.",
  19277. mModule->TypeToString(leftValue.mType).c_str(), mModule->TypeToString(rightValue.mType).c_str()),
  19278. opToken);
  19279. return;
  19280. }
  19281. BfPointerType* resultPointerType = (BfPointerType*)resultType;
  19282. BfType* intPtrType = mModule->GetPrimitiveType(BfTypeCode_IntPtr);
  19283. convLeftValue = mModule->CastToValue(leftExpression, leftValue, intPtrType, (BfCastFlags)(BfCastFlags_Explicit | BfCastFlags_FromCompiler));
  19284. convRightValue = mModule->CastToValue(rightExpression, rightValue, intPtrType, (BfCastFlags)(BfCastFlags_Explicit | BfCastFlags_FromCompiler));
  19285. BfIRValue diffValue = mModule->mBfIRBuilder->CreateSub(convLeftValue, convRightValue);
  19286. diffValue = mModule->mBfIRBuilder->CreateDiv(diffValue, mModule->GetConstValue(resultPointerType->mElementType->mSize, intPtrType), true);
  19287. mResult = BfTypedValue(diffValue, intPtrType);
  19288. return;
  19289. }
  19290. else if ((binaryOp != BfBinaryOp_Equality) && (binaryOp != BfBinaryOp_StrictEquality) &&
  19291. (binaryOp != BfBinaryOp_InEquality) && (binaryOp != BfBinaryOp_StrictInEquality) &&
  19292. (binaryOp != BfBinaryOp_LessThan) && (binaryOp != BfBinaryOp_LessThanOrEqual) &&
  19293. (binaryOp != BfBinaryOp_GreaterThan) && (binaryOp != BfBinaryOp_GreaterThanOrEqual))
  19294. {
  19295. if (mModule->PreFail())
  19296. mModule->Fail("Invalid operation on pointers", opToken);
  19297. return;
  19298. }
  19299. if ((!BfBinOpEqualityCheck(binaryOp)) || (resultType != otherType))
  19300. {
  19301. resultType = mModule->GetPrimitiveType(BfTypeCode_UIntPtr);
  19302. explicitCast = true;
  19303. }
  19304. }
  19305. else if (resultType->IsPointer())
  19306. {
  19307. if (otherType->IsNull())
  19308. {
  19309. if (!BfBinOpEqualityCheck(binaryOp))
  19310. {
  19311. if (mModule->PreFail())
  19312. mModule->Fail(StrFormat("Invalid operation between '%s' and null", mModule->TypeToString(resultType).c_str()), opToken);
  19313. return;
  19314. }
  19315. if ((binaryOp == BfBinaryOp_Equality) || (binaryOp == BfBinaryOp_StrictEquality))
  19316. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateIsNull(resultTypedValue->mValue), mModule->GetPrimitiveType(BfTypeCode_Boolean));
  19317. else
  19318. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateIsNotNull(resultTypedValue->mValue), mModule->GetPrimitiveType(BfTypeCode_Boolean));
  19319. return;
  19320. }
  19321. // One pointer
  19322. if ((!otherType->IsIntegral()) ||
  19323. ((binaryOp != BfBinaryOp_Add) && (binaryOp != BfBinaryOp_Subtract) && (binaryOp != BfBinaryOp_OverflowAdd) && (binaryOp != BfBinaryOp_OverflowSubtract)))
  19324. {
  19325. _OpFail();
  19326. return;
  19327. }
  19328. auto underlyingType = resultType->GetUnderlyingType();
  19329. BfIRValue addValue = otherTypedValue->mValue;
  19330. if ((!otherTypedValue->mType->IsSigned()) && (otherTypedValue->mType->mSize < mModule->mSystem->mPtrSize))
  19331. addValue = mModule->mBfIRBuilder->CreateNumericCast(addValue, false, BfTypeCode_UIntPtr);
  19332. if ((binaryOp == BfBinaryOp_Subtract) || (binaryOp == BfBinaryOp_OverflowSubtract))
  19333. {
  19334. if (resultTypeSrc == rightExpression)
  19335. mModule->Fail("Cannot subtract a pointer from an integer", resultTypeSrc);
  19336. addValue = mModule->mBfIRBuilder->CreateNeg(addValue);
  19337. }
  19338. mModule->PopulateType(underlyingType);
  19339. if (underlyingType->IsValuelessType())
  19340. {
  19341. if (!mModule->IsInSpecializedSection())
  19342. {
  19343. mModule->Warn(0, "Adding to a pointer to a zero-sized element has no effect", opToken);
  19344. }
  19345. mResult = *resultTypedValue;
  19346. return;
  19347. }
  19348. mModule->mBfIRBuilder->PopulateType(underlyingType);
  19349. mResult = BfTypedValue(mModule->CreateIndexedValue(underlyingType, resultTypedValue->mValue, addValue), resultType);
  19350. return;
  19351. }
  19352. if ((resultType->IsFunction()) || (resultType->IsPointer()) || (resultType->IsObject()) || (resultType->IsInterface()) || (resultType->IsGenericParam()))
  19353. {
  19354. if ((binaryOp == BfBinaryOp_Add) &&
  19355. (resultType->IsInstanceOf(mModule->mCompiler->mStringTypeDef)) &&
  19356. (otherType->IsInstanceOf(mModule->mCompiler->mStringTypeDef)))
  19357. {
  19358. AddStrings(leftValue, rightValue, opToken);
  19359. return;
  19360. }
  19361. if (!BfGetBinaryOpPrecendence(binaryOp))
  19362. {
  19363. //mModule->Fail("Invalid operation for objects", opToken);
  19364. _OpFail();
  19365. return;
  19366. }
  19367. if ((binaryOp == BfBinaryOp_Equality) || (binaryOp == BfBinaryOp_StrictEquality) || (binaryOp == BfBinaryOp_InEquality) || (binaryOp == BfBinaryOp_StrictInEquality))
  19368. {
  19369. if (resultType->IsInterface())
  19370. {
  19371. // Compare as objects instead
  19372. resultType = mModule->mContext->mBfObjectType;
  19373. *resultTypedValue = mModule->Cast(resultTypeSrc, *resultTypedValue, resultType);
  19374. }
  19375. if (otherType->IsNull())
  19376. {
  19377. if (resultType->IsFunction())
  19378. {
  19379. if ((binaryOp == BfBinaryOp_Equality) || (binaryOp == BfBinaryOp_StrictEquality))
  19380. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateCmpEQ(mModule->mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, 0), resultTypedValue->mValue), mModule->GetPrimitiveType(BfTypeCode_Boolean));
  19381. else
  19382. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateCmpNE(mModule->mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, 0), resultTypedValue->mValue), mModule->GetPrimitiveType(BfTypeCode_Boolean));
  19383. }
  19384. else
  19385. {
  19386. if ((binaryOp == BfBinaryOp_Equality) || (binaryOp == BfBinaryOp_StrictEquality))
  19387. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateIsNull(resultTypedValue->mValue), mModule->GetPrimitiveType(BfTypeCode_Boolean));
  19388. else
  19389. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateIsNotNull(resultTypedValue->mValue), mModule->GetPrimitiveType(BfTypeCode_Boolean));
  19390. }
  19391. }
  19392. else
  19393. {
  19394. auto convertedValue = mModule->Cast(otherTypeSrc, *otherTypedValue, resultType, BfCastFlags_NoBox);
  19395. if (!convertedValue)
  19396. return;
  19397. convertedValue = mModule->LoadValue(convertedValue);
  19398. if ((binaryOp == BfBinaryOp_Equality) || (binaryOp == BfBinaryOp_StrictEquality))
  19399. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateCmpEQ(resultTypedValue->mValue, convertedValue.mValue), mModule->GetPrimitiveType(BfTypeCode_Boolean));
  19400. else
  19401. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateCmpNE(resultTypedValue->mValue, convertedValue.mValue), mModule->GetPrimitiveType(BfTypeCode_Boolean));
  19402. }
  19403. return;
  19404. }
  19405. }
  19406. if (resultType->IsTypedPrimitive())
  19407. {
  19408. bool needsOtherCast = true;
  19409. if (otherType != resultType)
  19410. {
  19411. if ((otherType->IsPrimitiveType()) && (!otherType->IsValuelessType()))
  19412. {
  19413. // Allow zero comparisons to match all typed primitives
  19414. if ((binaryOp == BfBinaryOp_Equality) || (binaryOp == BfBinaryOp_InEquality))
  19415. {
  19416. auto constant = mModule->mBfIRBuilder->GetConstant(otherTypedValue->mValue);
  19417. if ((constant != NULL) && (mModule->mBfIRBuilder->IsInt(constant->mTypeCode)) && (constant->mInt64 == 0))
  19418. needsOtherCast = false;
  19419. }
  19420. // Allow integer offsetting
  19421. if ((binaryOp == BfBinaryOp_Add) || (binaryOp == BfBinaryOp_Subtract) || (binaryOp == BfBinaryOp_OverflowAdd) || (binaryOp == BfBinaryOp_OverflowSubtract))
  19422. {
  19423. if (otherType->IsIntegral())
  19424. needsOtherCast = false;
  19425. }
  19426. }
  19427. if (needsOtherCast)
  19428. {
  19429. // The only purpose of this cast is to potentially throw a casting error
  19430. BfIRValue otherCastResult = mModule->CastToValue(otherTypeSrc, *otherTypedValue, resultType, explicitCast ? BfCastFlags_Explicit : BfCastFlags_None);
  19431. if (!otherCastResult)
  19432. return;
  19433. }
  19434. }
  19435. auto underlyingType = resultType->GetUnderlyingType();
  19436. BfIRValue convResultValue = mModule->CastToValue(resultTypeSrc, *resultTypedValue, underlyingType, BfCastFlags_Explicit);
  19437. BfIRValue convOtherValue = mModule->CastToValue(otherTypeSrc, *otherTypedValue, underlyingType, BfCastFlags_Explicit);
  19438. if ((!underlyingType->IsValuelessType()) && ((!convResultValue) || (!convOtherValue)))
  19439. return;
  19440. if (resultTypedValue == &leftValue)
  19441. PerformBinaryOperation(underlyingType, convResultValue, convOtherValue, binaryOp, opToken);
  19442. else
  19443. PerformBinaryOperation(underlyingType, convOtherValue, convResultValue, binaryOp, opToken);
  19444. if (mResult.mType == underlyingType)
  19445. mResult.mType = resultType;
  19446. return;
  19447. }
  19448. auto _CallValueTypeEquals = [&]()
  19449. {
  19450. BfModuleMethodInstance moduleMethodInstance;
  19451. auto typeInst = leftValue.mType->ToTypeInstance();
  19452. if (typeInst != NULL)
  19453. {
  19454. if ((binaryOp == BfBinaryOp_StrictEquality) || (binaryOp == BfBinaryOp_StrictInEquality))
  19455. moduleMethodInstance = mModule->GetMethodByName(typeInst, BF_METHODNAME_DEFAULT_STRICT_EQUALS);
  19456. else
  19457. moduleMethodInstance = mModule->GetMethodByName(typeInst, BF_METHODNAME_DEFAULT_EQUALS);
  19458. }
  19459. else
  19460. {
  19461. BF_ASSERT(leftValue.mType->IsSizedArray() || leftValue.mType->IsMethodRef());
  19462. auto valueTypeInst = mModule->ResolveTypeDef(mModule->mCompiler->mValueTypeTypeDef)->ToTypeInstance();
  19463. BfMethodDef* equalsMethodDef = mModule->mCompiler->mValueTypeTypeDef->GetMethodByName("Equals");
  19464. BfTypeVector typeVec;
  19465. typeVec.push_back(leftValue.mType);
  19466. moduleMethodInstance = mModule->GetMethodInstance(valueTypeInst, equalsMethodDef, typeVec);
  19467. }
  19468. if (moduleMethodInstance)
  19469. {
  19470. if ((opToken != NULL) && (!noClassify))
  19471. mModule->SetElementType(opToken, BfSourceElementType_Method);
  19472. SizedArray<BfResolvedArg, 4> argValues;
  19473. BfResolvedArg resolvedArg;
  19474. resolvedArg.mTypedValue = leftValue;
  19475. argValues.push_back(resolvedArg);
  19476. resolvedArg.mTypedValue = rightValue;
  19477. argValues.push_back(resolvedArg);
  19478. mResult = CreateCall(opToken, BfTypedValue(), BfTypedValue(), moduleMethodInstance.mMethodInstance->mMethodDef, moduleMethodInstance, BfCreateCallFlags_None, argValues);
  19479. if ((mResult) &&
  19480. ((binaryOp == BfBinaryOp_InEquality) || (binaryOp == BfBinaryOp_StrictInEquality)))
  19481. mResult.mValue = mModule->mBfIRBuilder->CreateNot(mResult.mValue);
  19482. return true;
  19483. }
  19484. return false;
  19485. };
  19486. //if (((leftValue.mType->IsComposite()) || (leftValue.mType->IsObject())))
  19487. if (((resultType->IsComposite()) || (resultType->IsObject())))
  19488. {
  19489. bool areEquivalentTuples = false;
  19490. if ((leftValue.mType->IsTuple()) && (rightValue.mType->IsTuple()))
  19491. {
  19492. auto leftTupleType = (BfTypeInstance*)leftValue.mType;
  19493. auto rightTupleType = (BfTypeInstance*)rightValue.mType;
  19494. // We only do this for tuples, because we would allow an implicit struct
  19495. // truncation if we allow it for all structs, which would result in only
  19496. // the base class's fields being compared
  19497. if (mModule->CanCast(rightValue, leftValue.mType))
  19498. rightValue = mModule->Cast(opToken, rightValue, leftValue.mType, BfCastFlags_Explicit);
  19499. else if (mModule->CanCast(leftValue, rightValue.mType))
  19500. leftValue = mModule->Cast(opToken, leftValue, rightValue.mType, BfCastFlags_Explicit);
  19501. }
  19502. if (leftValue.mType == rightValue.mType)
  19503. {
  19504. if (BfBinOpEqualityCheck(binaryOp))
  19505. {
  19506. auto intCoercibleType = mModule->GetIntCoercibleType(leftValue.mType);
  19507. if (intCoercibleType != NULL)
  19508. {
  19509. auto intLHS = mModule->GetIntCoercible(leftValue);
  19510. auto intRHS = mModule->GetIntCoercible(rightValue);
  19511. auto boolType = mModule->GetPrimitiveType(BfTypeCode_Boolean);
  19512. if ((binaryOp == BfBinaryOp_Equality) || (binaryOp == BfBinaryOp_StrictEquality))
  19513. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateCmpEQ(intLHS.mValue, intRHS.mValue), boolType);
  19514. else
  19515. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateCmpNE(intLHS.mValue, intRHS.mValue), boolType);
  19516. return;
  19517. }
  19518. // Valueless types always compare as 'equal' if we can ensure no members could have an equality operator overload
  19519. if (leftValue.mType->IsComposite())
  19520. {
  19521. mModule->PopulateType(leftValue.mType);
  19522. if (leftValue.mType->IsValuelessType())
  19523. {
  19524. bool mayHaveEqualOverload = false;
  19525. auto leftTypeInst = leftValue.mType->ToTypeInstance();
  19526. if (leftTypeInst != NULL)
  19527. {
  19528. std::function<bool(BfType*)> _HasTypeInstance = [&](BfType* type)
  19529. {
  19530. if (type == NULL)
  19531. return false;
  19532. if (type->IsTypeInstance())
  19533. return true;
  19534. if (type->IsSizedArray())
  19535. return _HasTypeInstance(((BfSizedArrayType*)type)->mElementType);
  19536. return false;
  19537. };
  19538. for (auto& fieldInstance : leftTypeInst->mFieldInstances)
  19539. {
  19540. if (_HasTypeInstance(fieldInstance.mResolvedType))
  19541. mayHaveEqualOverload = true;
  19542. }
  19543. }
  19544. if (!mayHaveEqualOverload)
  19545. {
  19546. auto boolType = mModule->GetPrimitiveType(BfTypeCode_Boolean);
  19547. bool isEqual = (binaryOp == BfBinaryOp_Equality) || (binaryOp == BfBinaryOp_StrictEquality);
  19548. mResult = BfTypedValue(mModule->GetConstValue(isEqual ? 1 : 0, boolType), boolType);
  19549. return;
  19550. }
  19551. }
  19552. }
  19553. if (_CallValueTypeEquals())
  19554. return;
  19555. }
  19556. if (mModule->PreFail())
  19557. {
  19558. mModule->Fail(StrFormat("Operator '%s' cannot be applied to operands of type '%s'",
  19559. BfGetOpName(binaryOp),
  19560. mModule->TypeToString(leftValue.mType).c_str()), opToken);
  19561. }
  19562. return;
  19563. }
  19564. else
  19565. {
  19566. bool handled = false;
  19567. for (int pass = 0; pass < 2; pass++)
  19568. {
  19569. BfTypedValue& fromValue = (pass == 0) ? leftValue : rightValue;
  19570. BfType* toType = (pass == 0) ? rightValue.mType : leftValue.mType;
  19571. if (mModule->CanCast(fromValue, toType))
  19572. {
  19573. auto result = mModule->Cast(opToken, fromValue, toType);
  19574. if (result)
  19575. {
  19576. resultType = toType;
  19577. fromValue = result;
  19578. handled = true;
  19579. break;
  19580. }
  19581. }
  19582. }
  19583. if (!handled)
  19584. {
  19585. if ((leftValue.mType->IsUndefSizedArray()) || (rightValue.mType->IsUndefSizedArray()))
  19586. {
  19587. if ((leftValue.mType->IsSizedArray()) && (rightValue.mType->IsSizedArray() &&
  19588. (leftValue.mType->GetUnderlyingType() == rightValue.mType->GetUnderlyingType())))
  19589. {
  19590. if (BfBinOpEqualityCheck(binaryOp))
  19591. {
  19592. auto boolType = mModule->GetPrimitiveType(BfTypeCode_Boolean);
  19593. mResult = mModule->GetDefaultTypedValue(boolType, false, BfDefaultValueKind_Undef);
  19594. return;
  19595. }
  19596. }
  19597. }
  19598. mModule->Fail(StrFormat("Operator '%s' cannot be applied to operands of type '%s' and '%s'",
  19599. BfGetOpName(binaryOp),
  19600. mModule->TypeToString(leftValue.mType).c_str(),
  19601. mModule->TypeToString(rightValue.mType).c_str()), opToken);
  19602. return;
  19603. }
  19604. }
  19605. }
  19606. if (resultType->IsMethodRef() && otherType->IsMethodRef())
  19607. {
  19608. if (BfBinOpEqualityCheck(binaryOp))
  19609. {
  19610. auto boolType = mModule->GetPrimitiveType(BfTypeCode_Boolean);
  19611. BfMethodRefType* lhsMethodRefType = (BfMethodRefType*)leftValue.mType;
  19612. BfMethodRefType* rhsMethodRefType = (BfMethodRefType*)rightValue.mType;
  19613. if (lhsMethodRefType->mMethodRef != rhsMethodRefType->mMethodRef)
  19614. {
  19615. mResult = BfTypedValue(mModule->GetConstValue(((binaryOp == BfBinaryOp_Equality) || (binaryOp == BfBinaryOp_StrictEquality)) ? 0 : 1, boolType), boolType);
  19616. return;
  19617. }
  19618. if (_CallValueTypeEquals())
  19619. return;
  19620. }
  19621. }
  19622. if (resultType->IsIntegral())
  19623. {
  19624. if ((binaryOp == BfBinaryOp_LeftShift) || (binaryOp == BfBinaryOp_RightShift))
  19625. {
  19626. if (rightValue.mValue.IsConst())
  19627. {
  19628. auto constVal = mModule->mBfIRBuilder->GetConstant(rightValue.mValue);
  19629. if ((constVal->mInt64 < 0) || (constVal->mInt64 >= 8 * resultType->mSize))
  19630. {
  19631. mModule->Fail(StrFormat("Shift value '%lld' is out of range for type '%s'", constVal->mInt64, mModule->TypeToString(resultType).c_str()), opToken);
  19632. }
  19633. }
  19634. }
  19635. // We're trying a simplified scheme that doesn't always try to up-convert into an 'int'
  19636. if (leftValue.mType != rightValue.mType)
  19637. {
  19638. bool isBitwiseExpr =
  19639. (binaryOp == BfBinaryOp_BitwiseAnd) ||
  19640. (binaryOp == BfBinaryOp_BitwiseOr) ||
  19641. (binaryOp == BfBinaryOp_ExclusiveOr) ||
  19642. (binaryOp == BfBinaryOp_LeftShift) ||
  19643. (binaryOp == BfBinaryOp_RightShift) ||
  19644. (binaryOp == BfBinaryOp_Equality) ||
  19645. (binaryOp == BfBinaryOp_InEquality) ||
  19646. (binaryOp == BfBinaryOp_StrictEquality) ||
  19647. (binaryOp == BfBinaryOp_StrictInEquality);
  19648. if ((binaryOp == BfBinaryOp_LeftShift) || (binaryOp == BfBinaryOp_RightShift))
  19649. {
  19650. // For shifts we have more lenient rules - shifts are naturally limited so any int type is equally valid
  19651. if (rightValue.mType->IsIntegral())
  19652. explicitCast = true;
  19653. }
  19654. else if (((binaryOp == BfBinaryOp_Add) || (binaryOp == BfBinaryOp_Subtract) || (binaryOp == BfBinaryOp_OverflowAdd) || (binaryOp == BfBinaryOp_OverflowSubtract)) && (resultType->IsChar()) && (otherType->IsInteger()))
  19655. {
  19656. // charVal += intVal;
  19657. explicitCast = true;
  19658. }
  19659. else if ((!resultType->IsSigned()) && (otherType->IsSigned()))
  19660. {
  19661. if (mModule->CanCast(*otherTypedValue, resultType))
  19662. {
  19663. // If we can convert the 'other' value implicitly then it's a convertible literal, leave as uint
  19664. }
  19665. else
  19666. {
  19667. mModule->Fail(StrFormat("Operator cannot be applied to operands of type '%s' and '%s'",
  19668. mModule->TypeToString(leftValue.mType).c_str(),
  19669. mModule->TypeToString(rightValue.mType).c_str()), opToken);
  19670. return;
  19671. }
  19672. }
  19673. else if ((isBitwiseExpr) && (otherType->IsIntegral()) && (resultType->mSize == otherType->mSize))
  19674. {
  19675. // Forget about signed/unsigned mismatches for bitwise operations
  19676. explicitCast = true;
  19677. }
  19678. else
  19679. {
  19680. if (((binaryOp == BfBinaryOp_Subtract) || (binaryOp == BfBinaryOp_OverflowSubtract)) &&
  19681. (resultType->IsChar()) && (otherType->IsChar()))
  19682. {
  19683. // "wchar - char" subtraction will always fit into int32, because of unicode range
  19684. resultType = mModule->GetPrimitiveType(BfTypeCode_Int32);
  19685. explicitCast = true;
  19686. }
  19687. else if ((otherType->IsChar()) &&
  19688. ((binaryOp == BfBinaryOp_Add) || (binaryOp == BfBinaryOp_Subtract) || (binaryOp == BfBinaryOp_OverflowAdd) || (binaryOp == BfBinaryOp_OverflowSubtract)))
  19689. {
  19690. mModule->Fail(StrFormat("Cannot perform operation between types '%s' and '%s'",
  19691. mModule->TypeToString(leftValue.mType).c_str(),
  19692. mModule->TypeToString(rightValue.mType).c_str()), opToken);
  19693. }
  19694. }
  19695. }
  19696. else if ((!resultType->IsSigned()) && (binaryOp == BfBinaryOp_Subtract) && (!forceLeftType))
  19697. {
  19698. if ((mExpectingType == NULL) || (mExpectingType->IsSigned()) || (resultType->IsChar()))
  19699. {
  19700. if ((resultType->IsChar()) && (resultType->mSize == 4))
  19701. {
  19702. // "wchar - wchar" subtraction will always fit into int32, because of unicode range
  19703. resultType = mModule->GetPrimitiveType(BfTypeCode_Int32);
  19704. }
  19705. else
  19706. {
  19707. // The result of uint8 - uint8 is int16 (for example)
  19708. switch (resultType->mSize)
  19709. {
  19710. case 1:
  19711. resultType = mModule->GetPrimitiveType(BfTypeCode_Int16);
  19712. break;
  19713. case 2:
  19714. resultType = mModule->GetPrimitiveType(BfTypeCode_Int32);
  19715. break;
  19716. case 4:
  19717. resultType = mModule->GetPrimitiveType(BfTypeCode_Int64);
  19718. break;
  19719. }
  19720. }
  19721. explicitCast = true;
  19722. }
  19723. }
  19724. else if (resultType->IsChar())
  19725. {
  19726. bool canDoOp =
  19727. (binaryOp == BfBinaryOp_BitwiseAnd) ||
  19728. (binaryOp == BfBinaryOp_BitwiseOr) ||
  19729. ((binaryOp >= BfBinaryOp_Equality) && (binaryOp <= BfBinaryOp_Compare));
  19730. if (!canDoOp)
  19731. {
  19732. mModule->Fail(StrFormat("Cannot perform operation on type '%s'", mModule->TypeToString(resultType).c_str()), opToken);
  19733. return;
  19734. }
  19735. }
  19736. }
  19737. if (!convLeftValue)
  19738. convLeftValue = mModule->CastToValue(leftExpression, leftValue, resultType,
  19739. explicitCast ? (BfCastFlags)(BfCastFlags_Explicit | BfCastFlags_FromCompiler) : BfCastFlags_None);
  19740. if (!convRightValue)
  19741. convRightValue = mModule->CastToValue(rightExpression, rightValue, resultType,
  19742. explicitCast ? (BfCastFlags)(BfCastFlags_Explicit | BfCastFlags_FromCompiler) : BfCastFlags_None);
  19743. PerformBinaryOperation(resultType, convLeftValue, convRightValue, binaryOp, opToken);
  19744. }
  19745. void BfExprEvaluator::PerformBinaryOperation(BfType* resultType, BfIRValue convLeftValue, BfIRValue convRightValue, BfBinaryOp binaryOp, BfAstNode* opToken)
  19746. {
  19747. if (resultType->IsValuelessType())
  19748. {
  19749. switch (binaryOp)
  19750. {
  19751. case BfBinaryOp_Equality:
  19752. case BfBinaryOp_StrictEquality:
  19753. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConst(BfTypeCode_Boolean, 1),
  19754. mModule->GetPrimitiveType(BfTypeCode_Boolean));
  19755. return;
  19756. case BfBinaryOp_InEquality:
  19757. case BfBinaryOp_StrictInEquality:
  19758. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConst(BfTypeCode_Boolean, 0),
  19759. mModule->GetPrimitiveType(BfTypeCode_Boolean));
  19760. return;
  19761. default:
  19762. break;
  19763. }
  19764. }
  19765. if ((!convLeftValue) || (!convRightValue))
  19766. return;
  19767. if (resultType->IsPrimitiveType())
  19768. {
  19769. auto primType = (BfPrimitiveType*)resultType;
  19770. if (primType->mTypeDef->mTypeCode == BfTypeCode_Boolean)
  19771. {
  19772. bool passThrough = false;
  19773. switch (binaryOp)
  19774. {
  19775. case BfBinaryOp_Equality:
  19776. case BfBinaryOp_StrictEquality:
  19777. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateCmpEQ(convLeftValue, convRightValue),
  19778. mModule->GetPrimitiveType(BfTypeCode_Boolean));
  19779. break;
  19780. case BfBinaryOp_InEquality:
  19781. case BfBinaryOp_StrictInEquality:
  19782. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateCmpNE(convLeftValue, convRightValue),
  19783. mModule->GetPrimitiveType(BfTypeCode_Boolean));
  19784. break;
  19785. case BfBinaryOp_BitwiseAnd:
  19786. case BfBinaryOp_ConditionalAnd:
  19787. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateAnd(convLeftValue, convRightValue),
  19788. mModule->GetPrimitiveType(BfTypeCode_Boolean));
  19789. break;
  19790. case BfBinaryOp_BitwiseOr:
  19791. case BfBinaryOp_ConditionalOr:
  19792. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateOr(convLeftValue, convRightValue),
  19793. mModule->GetPrimitiveType(BfTypeCode_Boolean));
  19794. break;
  19795. case BfBinaryOp_ExclusiveOr:
  19796. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateXor(convLeftValue, convRightValue),
  19797. mModule->GetPrimitiveType(BfTypeCode_Boolean));
  19798. break;
  19799. case BfBinaryOp_Compare:
  19800. passThrough = true;
  19801. break;
  19802. default:
  19803. if (mModule->PreFail())
  19804. mModule->Fail("Invalid operation for booleans", opToken);
  19805. break;
  19806. }
  19807. if (!passThrough)
  19808. return;
  19809. }
  19810. }
  19811. if ((!resultType->IsIntegralOrBool()) && (!resultType->IsFloat()))
  19812. {
  19813. if (mModule->PreFail())
  19814. mModule->Fail(StrFormat("Cannot perform operation on type '%s'", mModule->TypeToString(resultType).c_str()), opToken);
  19815. return;
  19816. }
  19817. if (resultType->IsIntegral())
  19818. {
  19819. switch (binaryOp)
  19820. {
  19821. case BfBinaryOp_BitwiseAnd:
  19822. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateAnd(convLeftValue, convRightValue), resultType);
  19823. return;
  19824. case BfBinaryOp_BitwiseOr:
  19825. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateOr(convLeftValue, convRightValue), resultType);
  19826. return;
  19827. case BfBinaryOp_ExclusiveOr:
  19828. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateXor(convLeftValue, convRightValue), resultType);
  19829. return;
  19830. case BfBinaryOp_LeftShift:
  19831. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateShl(convLeftValue, convRightValue), resultType);
  19832. mModule->CheckRangeError(resultType, opToken);
  19833. return;
  19834. case BfBinaryOp_RightShift:
  19835. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateShr(convLeftValue, convRightValue, resultType->IsSigned()), resultType);
  19836. return;
  19837. default: break;
  19838. }
  19839. }
  19840. if ((resultType->IsChar()) &&
  19841. ((binaryOp == BfBinaryOp_Multiply) ||
  19842. (binaryOp == BfBinaryOp_OverflowMultiply) ||
  19843. (binaryOp == BfBinaryOp_Divide) ||
  19844. (binaryOp == BfBinaryOp_Modulus)))
  19845. {
  19846. mModule->Fail(StrFormat("Cannot perform operation on type '%s'", mModule->TypeToString(resultType).c_str()), opToken);
  19847. return;
  19848. }
  19849. auto _GetOverflowKind = [&](bool wantOverflow)
  19850. {
  19851. if (!wantOverflow)
  19852. return BfOverflowCheckKind_None;
  19853. if (mModule->GetDefaultCheckedKind() != BfCheckedKind_Checked)
  19854. return BfOverflowCheckKind_None;
  19855. bool arithmeticChecks = mModule->mCompiler->mOptions.mArithmeticChecks;
  19856. auto typeOptions = mModule->GetTypeOptions();
  19857. if (typeOptions != NULL)
  19858. arithmeticChecks = typeOptions->Apply(arithmeticChecks, BfOptionFlags_ArithmeticCheck);
  19859. if (!arithmeticChecks)
  19860. return BfOverflowCheckKind_None;
  19861. BfOverflowCheckKind overflowCheckKind = (resultType->IsSigned()) ? BfOverflowCheckKind_Signed : BfOverflowCheckKind_Unsigned;
  19862. if (!mModule->IsOptimized())
  19863. overflowCheckKind = (BfOverflowCheckKind)(overflowCheckKind | BfOverflowCheckKind_Flag_UseAsm);
  19864. return overflowCheckKind;
  19865. };
  19866. switch (binaryOp)
  19867. {
  19868. case BfBinaryOp_Add:
  19869. case BfBinaryOp_OverflowAdd:
  19870. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateAdd(convLeftValue, convRightValue, _GetOverflowKind(binaryOp == BfBinaryOp_Add)), resultType);
  19871. if (binaryOp != BfBinaryOp_OverflowAdd)
  19872. mModule->CheckRangeError(resultType, opToken);
  19873. break;
  19874. case BfBinaryOp_Subtract:
  19875. case BfBinaryOp_OverflowSubtract:
  19876. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateSub(convLeftValue, convRightValue, _GetOverflowKind(binaryOp == BfBinaryOp_Subtract)), resultType);
  19877. if (binaryOp != BfBinaryOp_OverflowSubtract)
  19878. mModule->CheckRangeError(resultType, opToken);
  19879. break;
  19880. case BfBinaryOp_Multiply:
  19881. case BfBinaryOp_OverflowMultiply:
  19882. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateMul(convLeftValue, convRightValue, _GetOverflowKind(binaryOp == BfBinaryOp_Multiply)), resultType);
  19883. if (binaryOp != BfBinaryOp_OverflowMultiply)
  19884. mModule->CheckRangeError(resultType, opToken);
  19885. break;
  19886. case BfBinaryOp_Divide:
  19887. {
  19888. bool isZero = false;
  19889. if (convRightValue.IsConst())
  19890. {
  19891. auto constVal = mModule->mBfIRBuilder->GetConstant(convRightValue);
  19892. if (BfIRBuilder::IsInt(constVal->mTypeCode))
  19893. isZero = constVal->mInt64 == 0;
  19894. }
  19895. if (isZero)
  19896. {
  19897. mModule->Fail("Divide by zero", opToken);
  19898. mResult = mModule->GetDefaultTypedValue(resultType);
  19899. }
  19900. else
  19901. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateDiv(convLeftValue, convRightValue, resultType->IsSigned()), resultType);
  19902. }
  19903. break;
  19904. case BfBinaryOp_Modulus:
  19905. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateRem(convLeftValue, convRightValue, resultType->IsSigned()), resultType);
  19906. break;
  19907. case BfBinaryOp_Equality:
  19908. case BfBinaryOp_StrictEquality:
  19909. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateCmpEQ(convLeftValue, convRightValue),
  19910. mModule->GetPrimitiveType(BfTypeCode_Boolean));
  19911. break;
  19912. case BfBinaryOp_InEquality:
  19913. case BfBinaryOp_StrictInEquality:
  19914. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateCmpNE(convLeftValue, convRightValue),
  19915. mModule->GetPrimitiveType(BfTypeCode_Boolean));
  19916. break;
  19917. case BfBinaryOp_LessThan:
  19918. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateCmpLT(convLeftValue, convRightValue, resultType->IsSigned()),
  19919. mModule->GetPrimitiveType(BfTypeCode_Boolean));
  19920. break;
  19921. case BfBinaryOp_LessThanOrEqual:
  19922. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateCmpLTE(convLeftValue, convRightValue, resultType->IsSigned()),
  19923. mModule->GetPrimitiveType(BfTypeCode_Boolean));
  19924. break;
  19925. case BfBinaryOp_GreaterThan:
  19926. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateCmpGT(convLeftValue, convRightValue, resultType->IsSigned()),
  19927. mModule->GetPrimitiveType(BfTypeCode_Boolean));
  19928. break;
  19929. case BfBinaryOp_GreaterThanOrEqual:
  19930. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateCmpGTE(convLeftValue, convRightValue, resultType->IsSigned()),
  19931. mModule->GetPrimitiveType(BfTypeCode_Boolean));
  19932. break;
  19933. case BfBinaryOp_Compare:
  19934. {
  19935. auto intType = mModule->GetPrimitiveType(BfTypeCode_IntPtr);
  19936. if ((convLeftValue.IsConst()) && (convRightValue.IsConst()))
  19937. {
  19938. auto cmpLtVal = mModule->mBfIRBuilder->CreateCmpLT(convLeftValue, convRightValue, resultType->IsSigned());
  19939. auto ltConstant = mModule->mBfIRBuilder->GetConstant(cmpLtVal);
  19940. if (ltConstant->mBool)
  19941. {
  19942. mResult = BfTypedValue(mModule->GetConstValue(-1, mModule->GetPrimitiveType(BfTypeCode_IntPtr)), intType);
  19943. }
  19944. else
  19945. {
  19946. auto cmpGtVal = mModule->mBfIRBuilder->CreateCmpGT(convLeftValue, convRightValue, resultType->IsSigned());
  19947. auto rtConstant = mModule->mBfIRBuilder->GetConstant(cmpGtVal);
  19948. if (rtConstant->mBool)
  19949. mResult = BfTypedValue(mModule->GetConstValue(1, mModule->GetPrimitiveType(BfTypeCode_IntPtr)), intType);
  19950. else
  19951. mResult = BfTypedValue(mModule->GetConstValue(0, mModule->GetPrimitiveType(BfTypeCode_IntPtr)), intType);
  19952. }
  19953. }
  19954. else if ((resultType->IsIntegralOrBool()) && (resultType->mSize < intType->mSize))
  19955. {
  19956. auto leftIntValue = mModule->mBfIRBuilder->CreateNumericCast(convLeftValue, resultType->IsSigned(), BfTypeCode_IntPtr);
  19957. auto rightIntValue = mModule->mBfIRBuilder->CreateNumericCast(convRightValue, resultType->IsSigned(), BfTypeCode_IntPtr);
  19958. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateSub(leftIntValue, rightIntValue), intType);
  19959. }
  19960. else
  19961. {
  19962. BfIRBlock checkGtBlock = mModule->mBfIRBuilder->CreateBlock("cmpCheckGt");
  19963. BfIRBlock eqBlock = mModule->mBfIRBuilder->CreateBlock("cmpEq");
  19964. BfIRBlock endBlock = mModule->mBfIRBuilder->CreateBlock("cmpEnd");
  19965. auto startBlock = mModule->mBfIRBuilder->GetInsertBlock();
  19966. auto cmpLtVal = mModule->mBfIRBuilder->CreateCmpLT(convLeftValue, convRightValue, resultType->IsSigned());
  19967. mModule->mBfIRBuilder->CreateCondBr(cmpLtVal, endBlock, checkGtBlock);
  19968. mModule->mBfIRBuilder->AddBlock(checkGtBlock);
  19969. mModule->mBfIRBuilder->SetInsertPoint(checkGtBlock);
  19970. auto cmpGtVal = mModule->mBfIRBuilder->CreateCmpGT(convLeftValue, convRightValue, resultType->IsSigned());
  19971. mModule->mBfIRBuilder->CreateCondBr(cmpGtVal, endBlock, eqBlock);
  19972. mModule->mBfIRBuilder->AddBlock(eqBlock);
  19973. mModule->mBfIRBuilder->SetInsertPoint(eqBlock);
  19974. mModule->mBfIRBuilder->CreateBr(endBlock);
  19975. mModule->mBfIRBuilder->AddBlock(endBlock);
  19976. mModule->mBfIRBuilder->SetInsertPoint(endBlock);
  19977. auto phiVal = mModule->mBfIRBuilder->CreatePhi(mModule->mBfIRBuilder->MapType(intType), 3);
  19978. mModule->mBfIRBuilder->AddPhiIncoming(phiVal, mModule->mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, -1), startBlock);
  19979. mModule->mBfIRBuilder->AddPhiIncoming(phiVal, mModule->mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, 1), checkGtBlock);
  19980. mModule->mBfIRBuilder->AddPhiIncoming(phiVal, mModule->mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, 0), eqBlock);
  19981. mResult = BfTypedValue(phiVal, intType);
  19982. }
  19983. }
  19984. break;
  19985. default:
  19986. if (mModule->PreFail())
  19987. mModule->Fail("Invalid operation", opToken);
  19988. break;
  19989. }
  19990. }
  19991. void BfExprEvaluator::Visit(BfBinaryOperatorExpression* binOpExpr)
  19992. {
  19993. BfAutoParentNodeEntry autoParentNodeEntry(mModule, binOpExpr);
  19994. // There are a few binary operations that could actually be casts followed by an unary operation
  19995. // We can't determine that until we know whether the identifier in the parens is a typename or not
  19996. // (double)-1.0 (intptr)&val (BaseStruct)*val
  19997. BfUnaryOp unaryOp = BfUnaryOp_None;
  19998. switch (binOpExpr->mOp)
  19999. {
  20000. case BfBinaryOp_Add: unaryOp = BfUnaryOp_Positive; break;
  20001. case BfBinaryOp_Subtract: unaryOp = BfUnaryOp_Negate; break;
  20002. case BfBinaryOp_Multiply: unaryOp = BfUnaryOp_Dereference; break;
  20003. case BfBinaryOp_BitwiseAnd: unaryOp = BfUnaryOp_AddressOf; break;
  20004. default: break;
  20005. }
  20006. if (unaryOp != BfUnaryOp_None)
  20007. {
  20008. if (auto parenExpr = BfNodeDynCast<BfParenthesizedExpression>(binOpExpr->mLeft))
  20009. {
  20010. if (auto castTypeExpr = BfNodeDynCast<BfIdentifierNode>(parenExpr->mExpression))
  20011. {
  20012. SetAndRestoreValue<bool> prevIgnoreError(mModule->mIgnoreErrors, true);
  20013. auto resolvedType = mModule->ResolveTypeRef(castTypeExpr, NULL);
  20014. prevIgnoreError.Restore();
  20015. if (resolvedType != NULL)
  20016. {
  20017. if (auto rightBinOpExpr = BfNodeDynCast<BfBinaryOperatorExpression>(binOpExpr->mRight))
  20018. {
  20019. int leftPrecedence = BfGetBinaryOpPrecendence(binOpExpr->mOp);
  20020. int rightPrecedence = BfGetBinaryOpPrecendence(rightBinOpExpr->mOp);
  20021. // Do we have a precedence order issue due to mis-parsing this?
  20022. // An example is: "(int)-5.5 * 10"
  20023. if (rightPrecedence > leftPrecedence)
  20024. {
  20025. mModule->FailAfter("Cast target must be wrapped in parentheses", binOpExpr->mLeft);
  20026. }
  20027. }
  20028. PerformUnaryOperation(binOpExpr->mRight, unaryOp, binOpExpr->mOpToken, BfUnaryOpFlag_None);
  20029. if (mResult)
  20030. {
  20031. mResult = mModule->LoadValue(mResult);
  20032. mResult = mModule->Cast(binOpExpr, mResult, resolvedType, BfCastFlags_Explicit);
  20033. }
  20034. return;
  20035. }
  20036. }
  20037. }
  20038. }
  20039. if ((binOpExpr->mOp == BfBinaryOp_LeftShift) || (binOpExpr->mOp == BfBinaryOp_RightShift) ||
  20040. (binOpExpr->mOp == BfBinaryOp_BitwiseAnd) || (binOpExpr->mOp == BfBinaryOp_BitwiseOr) ||
  20041. (binOpExpr->mOp == BfBinaryOp_ExclusiveOr))
  20042. {
  20043. for (int side = 0; side < 2; side++)
  20044. {
  20045. if (auto innerBinOpExpr = BfNodeDynCast<BfBinaryOperatorExpression>((side == 0) ? binOpExpr->mLeft : binOpExpr->mRight))
  20046. {
  20047. if ((innerBinOpExpr->mOp == BfBinaryOp_Add) || (innerBinOpExpr->mOp == BfBinaryOp_Subtract))
  20048. {
  20049. mModule->Warn(BfWarning_C4554_PossiblePrecedenceError, "Check operator precedence for possible error. Consider using parentheses to clarify precedence", innerBinOpExpr);
  20050. }
  20051. }
  20052. }
  20053. }
  20054. if (binOpExpr->mRight == NULL)
  20055. {
  20056. // We visit the children for autocompletion only
  20057. if (binOpExpr->mLeft != NULL)
  20058. VisitChild(binOpExpr->mLeft);
  20059. if (mResult)
  20060. {
  20061. auto autoComplete = GetAutoComplete();
  20062. if (autoComplete != NULL)
  20063. autoComplete->CheckEmptyStart(binOpExpr->mOpToken, mResult.mType);
  20064. }
  20065. if (binOpExpr->mRight != NULL)
  20066. VisitChild(binOpExpr->mRight);
  20067. return;
  20068. }
  20069. PerformBinaryOperation(binOpExpr->mLeft, binOpExpr->mRight, binOpExpr->mOp, binOpExpr->mOpToken, BfBinOpFlag_None);
  20070. }