BfExprEvaluator.cpp 708 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917
  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. mHadVarConflictingReturnType = false;
  156. mAutoFlushAmbiguityErrors = true;
  157. mMethodCheckCount = 0;
  158. mCheckedKind = BfCheckedKind_NotSet;
  159. mMatchFailKind = MatchFailKind_None;
  160. mBfEvalExprFlags = BfEvalExprFlags_None;
  161. for (auto& arg : mArguments)
  162. {
  163. auto bfType = arg.mTypedValue.mType;
  164. if (bfType != NULL)
  165. {
  166. mHasVarArguments |= bfType->IsVar();
  167. if (bfType->IsGenericParam())
  168. {
  169. auto genericParamInstance = mModule->GetGenericParamInstance((BfGenericParamType*)bfType);
  170. if ((genericParamInstance->mGenericParamFlags & BfGenericParamFlag_Var) != 0)
  171. mHasVarArguments = true;
  172. }
  173. }
  174. }
  175. if (methodGenericArguments != NULL)
  176. {
  177. for (BfTypeReference* genericArg : *methodGenericArguments)
  178. {
  179. auto genericArgType = mModule->ResolveTypeRef(genericArg);
  180. if ((genericArgType != NULL) && (genericArgType->IsGenericParam()))
  181. {
  182. auto genericParamInstance = mModule->GetGenericParamInstance((BfGenericParamType*)genericArgType);
  183. if ((genericParamInstance->mGenericParamFlags & BfGenericParamFlag_Var) != 0)
  184. mHasVarArguments = true;
  185. }
  186. mExplicitMethodGenericArguments.push_back(genericArgType);
  187. }
  188. mHadExplicitGenericArguments = true;
  189. }
  190. }
  191. bool BfMethodMatcher::IsMemberAccessible(BfTypeInstance* typeInst, BfTypeDef* declaringType)
  192. {
  193. if (!declaringType->mIsPartial)
  194. return true;
  195. if (mActiveTypeDef == NULL)
  196. mActiveTypeDef = mModule->GetActiveTypeDef();
  197. // Note that mActiveTypeDef does not pose a constraint here
  198. if (!typeInst->IsTypeMemberIncluded(declaringType, mActiveTypeDef, mModule))
  199. return false;
  200. auto visibleProjectSet = mModule->GetVisibleProjectSet();
  201. if ((visibleProjectSet != NULL) && (!typeInst->IsTypeMemberAccessible(declaringType, visibleProjectSet)))
  202. {
  203. return false;
  204. }
  205. return true;
  206. }
  207. bool BfGenericInferContext::InferGenericArgument(BfMethodInstance* methodInstance, BfType* argType, BfType* wantType, BfIRValue argValue)
  208. {
  209. if (argType == NULL)
  210. return false;
  211. if (!wantType->IsUnspecializedType())
  212. return true;
  213. bool alreadyChecked = false;
  214. auto _AddToCheckedSet = [](BfType* type, HashSet<BfType*>& checkedTypeSet, bool& alreadyChecked)
  215. {
  216. if (alreadyChecked)
  217. return true;
  218. alreadyChecked = true;
  219. return checkedTypeSet.Add(type);
  220. };
  221. if (wantType->IsGenericParam())
  222. {
  223. auto wantGenericParam = (BfGenericParamType*)wantType;
  224. BfType* methodGenericTypeConstraint = NULL;
  225. auto _SetGeneric = [&]()
  226. {
  227. if (argType != NULL)
  228. {
  229. // Disallow illegal types
  230. if (argType->IsRef())
  231. return;
  232. if (argType->IsNull())
  233. return;
  234. }
  235. if ((*mCheckMethodGenericArguments)[wantGenericParam->mGenericParamIdx] != argType)
  236. {
  237. if (methodGenericTypeConstraint != NULL)
  238. {
  239. if (methodGenericTypeConstraint->IsGenericTypeInstance())
  240. {
  241. auto wantGenericType = (BfTypeInstance*)methodGenericTypeConstraint;
  242. auto checkArgType = argType;
  243. while (checkArgType != NULL)
  244. {
  245. if (checkArgType->IsGenericTypeInstance())
  246. {
  247. auto argGenericType = (BfTypeInstance*)checkArgType;
  248. if (argGenericType->mTypeDef == wantGenericType->mTypeDef)
  249. {
  250. for (int genericArgIdx = 0; genericArgIdx < (int)argGenericType->mGenericTypeInfo->mTypeGenericArguments.size(); genericArgIdx++)
  251. InferGenericArgument(methodInstance, argGenericType->mGenericTypeInfo->mTypeGenericArguments[genericArgIdx], wantGenericType->mGenericTypeInfo->mTypeGenericArguments[genericArgIdx], BfIRValue());
  252. }
  253. }
  254. else if (checkArgType->IsSizedArray())
  255. {
  256. auto sizedArrayType = (BfSizedArrayType*)checkArgType;
  257. if (wantGenericType->mTypeDef == mModule->mCompiler->mSizedArrayTypeDef)
  258. {
  259. InferGenericArgument(methodInstance, sizedArrayType->mElementType, wantGenericType->mGenericTypeInfo->mTypeGenericArguments[0], BfIRValue());
  260. auto intType = mModule->GetPrimitiveType(BfTypeCode_IntPtr);
  261. BfTypedValue arraySize = BfTypedValue(mModule->mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, (uint64)sizedArrayType->mElementCount), intType);
  262. InferGenericArgument(methodInstance, mModule->CreateConstExprValueType(arraySize), wantGenericType->mGenericTypeInfo->mTypeGenericArguments[1], BfIRValue());
  263. }
  264. }
  265. else if (checkArgType->IsPointer())
  266. {
  267. auto pointerType = (BfPointerType*)checkArgType;
  268. if (wantGenericType->mTypeDef == mModule->mCompiler->mPointerTTypeDef)
  269. {
  270. InferGenericArgument(methodInstance, pointerType->mElementType, wantGenericType->mGenericTypeInfo->mTypeGenericArguments[0], BfIRValue());
  271. }
  272. }
  273. auto checkTypeInst = checkArgType->ToTypeInstance();
  274. if ((checkTypeInst == NULL) || (!checkTypeInst->mHasParameterizedBase))
  275. break;
  276. checkArgType = checkTypeInst->mBaseType;
  277. }
  278. }
  279. }
  280. }
  281. if ((*mCheckMethodGenericArguments)[wantGenericParam->mGenericParamIdx] == NULL)
  282. mInferredCount++;
  283. (*mCheckMethodGenericArguments)[wantGenericParam->mGenericParamIdx] = argType;
  284. mPrevArgValues[wantGenericParam->mGenericParamIdx] = argValue;
  285. };
  286. if (argType->IsVar())
  287. {
  288. _SetGeneric();
  289. return true;
  290. }
  291. if (wantGenericParam->mGenericParamKind == BfGenericParamKind_Method)
  292. {
  293. auto genericParamInst = methodInstance->mMethodInfoEx->mGenericParams[wantGenericParam->mGenericParamIdx];
  294. methodGenericTypeConstraint = genericParamInst->mTypeConstraint;
  295. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_Const) != 0)
  296. {
  297. if (argValue.IsConst())
  298. {
  299. argType = mModule->CreateConstExprValueType(BfTypedValue(argValue, argType));
  300. }
  301. else if (!argType->IsConstExprValue())
  302. {
  303. return false;
  304. }
  305. }
  306. if (argType == mModule->mContext->mBfObjectType)
  307. {
  308. if ((genericParamInst->mTypeConstraint != NULL) && (genericParamInst->mTypeConstraint->IsDelegate()))
  309. {
  310. argType = genericParamInst->mTypeConstraint;
  311. }
  312. }
  313. auto prevGenericMethodArg = (*mCheckMethodGenericArguments)[wantGenericParam->mGenericParamIdx];
  314. auto prevArgValue = mPrevArgValues[wantGenericParam->mGenericParamIdx];
  315. if (prevGenericMethodArg == NULL)
  316. {
  317. _SetGeneric();
  318. return true;
  319. }
  320. if ((prevGenericMethodArg->IsIntUnknown()) && (!argType->IsIntUnknown()))
  321. {
  322. // Old int fits into new argType, that's good
  323. if (mModule->CanCast(BfTypedValue(prevArgValue, prevGenericMethodArg), argType))
  324. {
  325. _SetGeneric();
  326. return true;
  327. }
  328. // Doesn't fit, upgrade type to 'int'
  329. argType = mModule->GetPrimitiveType(BfTypeCode_IntPtr);
  330. if (mModule->CanCast(BfTypedValue(prevArgValue, prevGenericMethodArg), argType))
  331. {
  332. _SetGeneric();
  333. return true;
  334. }
  335. }
  336. if (argType->IsIntUnknown())
  337. {
  338. // New int fits into previous arg type, that's good
  339. if (mModule->CanCast(BfTypedValue(argValue, argType), prevGenericMethodArg))
  340. return true;
  341. // Doesn't fit, upgrade type to 'int'
  342. argType = mModule->GetPrimitiveType(BfTypeCode_IntPtr);
  343. }
  344. else
  345. {
  346. // Prev is already best
  347. if (mModule->CanCast(mModule->GetFakeTypedValue(argType), prevGenericMethodArg))
  348. return true;
  349. }
  350. // New best?
  351. if (mModule->CanCast(mModule->GetFakeTypedValue(prevGenericMethodArg), argType))
  352. {
  353. _SetGeneric();
  354. return true;
  355. }
  356. // No implicit conversion, FAIL!
  357. (*mCheckMethodGenericArguments)[wantGenericParam->mGenericParamIdx] = NULL;
  358. return false;
  359. }
  360. return true;
  361. }
  362. if (wantType->IsTuple())
  363. {
  364. if (argType->IsTuple())
  365. {
  366. auto wantTupleType = (BfTupleType*)wantType;
  367. auto argTupleType = (BfTupleType*)argType;
  368. if (wantTupleType->mFieldInstances.size() == argTupleType->mFieldInstances.size())
  369. {
  370. for (int fieldIdx = 0; fieldIdx < (int)wantTupleType->mFieldInstances.size(); fieldIdx++)
  371. {
  372. InferGenericArgument(methodInstance, argTupleType->mFieldInstances[fieldIdx].mResolvedType,
  373. wantTupleType->mFieldInstances[fieldIdx].mResolvedType, BfIRValue());
  374. }
  375. }
  376. }
  377. }
  378. if ((wantType->IsGenericTypeInstance()) && (wantType->IsUnspecializedTypeVariation()))
  379. {
  380. auto wantGenericType = (BfTypeInstance*)wantType;
  381. if (argType->IsGenericParam())
  382. {
  383. auto genericParam = mModule->GetGenericParamInstance((BfGenericParamType*)argType);
  384. if ((genericParam->mGenericParamFlags & BfGenericParamFlag_Var) != 0)
  385. {
  386. InferGenericArgument(methodInstance, mModule->GetPrimitiveType(BfTypeCode_Var), wantType, BfIRValue());
  387. return true;
  388. }
  389. if ((genericParam->mTypeConstraint != NULL) && (genericParam->mTypeConstraint->IsGenericTypeInstance()))
  390. InferGenericArgument(methodInstance, genericParam->mTypeConstraint, wantType, BfIRValue());
  391. }
  392. if (argType->IsVar())
  393. {
  394. for (int genericArgIdx = 0; genericArgIdx < (int)wantGenericType->mGenericTypeInfo->mTypeGenericArguments.size(); genericArgIdx++)
  395. {
  396. BfType* wantGenericArgument = wantGenericType->mGenericTypeInfo->mTypeGenericArguments[genericArgIdx];
  397. if (!wantGenericArgument->IsUnspecializedType())
  398. continue;
  399. InferGenericArgument(methodInstance, mModule->GetPrimitiveType(BfTypeCode_Var), wantGenericArgument, BfIRValue());
  400. }
  401. return true;
  402. }
  403. auto typeInstance = argType->ToTypeInstance();
  404. if (typeInstance == NULL)
  405. return true;
  406. if (wantGenericType->IsInterface())
  407. {
  408. for (auto& ifaceEntry : typeInstance->mInterfaces)
  409. InferGenericArgument(methodInstance, ifaceEntry.mInterfaceType, wantType, BfIRValue());
  410. }
  411. else if (typeInstance->mBaseType != NULL)
  412. InferGenericArgument(methodInstance, typeInstance->mBaseType, wantType, BfIRValue());
  413. if (!argType->IsGenericTypeInstance())
  414. return true;
  415. auto argGenericType = (BfTypeInstance*)argType;
  416. if (argGenericType->mTypeDef != wantGenericType->mTypeDef)
  417. return true;
  418. for (int genericArgIdx = 0; genericArgIdx < (int)argGenericType->mGenericTypeInfo->mTypeGenericArguments.size(); genericArgIdx++)
  419. {
  420. BfType* wantGenericArgument = wantGenericType->mGenericTypeInfo->mTypeGenericArguments[genericArgIdx];
  421. if (!wantGenericArgument->IsUnspecializedType())
  422. continue;
  423. if (!_AddToCheckedSet(argType, mCheckedTypeSet, alreadyChecked))
  424. return true;
  425. InferGenericArgument(methodInstance, argGenericType->mGenericTypeInfo->mTypeGenericArguments[genericArgIdx], wantGenericArgument, BfIRValue());
  426. }
  427. return true;
  428. }
  429. if (wantType->IsRef())
  430. {
  431. auto wantRefType = (BfRefType*)wantType;
  432. if (!argType->IsRef())
  433. {
  434. // Match to non-ref
  435. InferGenericArgument(methodInstance, argType, wantRefType->mElementType, BfIRValue());
  436. return true;
  437. }
  438. auto argRefType = (BfRefType*)argType;
  439. //TODO: We removed this check so we still infer even if we have the wrong ref kind
  440. //if (wantRefType->mRefKind != argRefType->mRefKind)
  441. //return true;
  442. return InferGenericArgument(methodInstance, argRefType->mElementType, wantRefType->mElementType, BfIRValue());
  443. }
  444. if (wantType->IsPointer())
  445. {
  446. if (!argType->IsPointer())
  447. return true;
  448. auto wantPointerType = (BfPointerType*) wantType;
  449. auto argPointerType = (BfPointerType*) argType;
  450. return InferGenericArgument(methodInstance, argPointerType->mElementType, wantPointerType->mElementType, BfIRValue());
  451. }
  452. if (wantType->IsUnknownSizedArray())
  453. {
  454. auto wantArrayType = (BfUnknownSizedArrayType*)wantType;
  455. if (argType->IsUnknownSizedArray())
  456. {
  457. auto argArrayType = (BfUnknownSizedArrayType*)argType;
  458. InferGenericArgument(methodInstance, argArrayType->mElementCountSource, wantArrayType->mElementCountSource, BfIRValue());
  459. }
  460. else if (argType->IsSizedArray())
  461. {
  462. auto argArrayType = (BfSizedArrayType*)argType;
  463. BfTypedValue sizeValue(mModule->GetConstValue(argArrayType->mElementCount), mModule->GetPrimitiveType(BfTypeCode_IntPtr));
  464. auto sizedType = mModule->CreateConstExprValueType(sizeValue);
  465. InferGenericArgument(methodInstance, sizedType, wantArrayType->mElementCountSource, BfIRValue());
  466. }
  467. }
  468. if (wantType->IsSizedArray())
  469. {
  470. if (argType->IsSizedArray())
  471. {
  472. auto wantArrayType = (BfSizedArrayType*)wantType;
  473. auto argArrayType = (BfSizedArrayType*)argType;
  474. InferGenericArgument(methodInstance, argArrayType->mElementType, wantArrayType->mElementType, BfIRValue());
  475. }
  476. }
  477. if ((wantType->IsDelegate()) || (wantType->IsFunction()))
  478. {
  479. if (((argType->IsDelegate()) || (argType->IsFunction())) &&
  480. (wantType->IsDelegate() == argType->IsDelegate()))
  481. {
  482. if (!_AddToCheckedSet(argType, mCheckedTypeSet, alreadyChecked))
  483. return true;
  484. auto argInvokeMethod = mModule->GetRawMethodByName(argType->ToTypeInstance(), "Invoke");
  485. auto wantInvokeMethod = mModule->GetRawMethodByName(wantType->ToTypeInstance(), "Invoke");
  486. if ((argInvokeMethod != NULL) && (wantInvokeMethod != NULL) && (argInvokeMethod->GetParamCount() == wantInvokeMethod->GetParamCount()))
  487. {
  488. InferGenericArgument(methodInstance, argInvokeMethod->mReturnType, wantInvokeMethod->mReturnType, BfIRValue());
  489. for (int argIdx = 0; argIdx < (int)argInvokeMethod->GetParamCount(); argIdx++)
  490. InferGenericArgument(methodInstance, argInvokeMethod->GetParamType(argIdx), wantInvokeMethod->GetParamType(argIdx), BfIRValue());
  491. }
  492. }
  493. else if (argType->IsMethodRef())
  494. {
  495. auto methodTypeRef = (BfMethodRefType*)argType;
  496. if (!_AddToCheckedSet(argType, mCheckedTypeSet, alreadyChecked))
  497. return true;
  498. auto argInvokeMethod = methodTypeRef->mMethodRef;
  499. auto delegateInfo = wantType->GetDelegateInfo();
  500. auto wantInvokeMethod = mModule->GetRawMethodByName(wantType->ToTypeInstance(), "Invoke");
  501. if ((delegateInfo->mHasExplicitThis) && (argInvokeMethod->HasThis()))
  502. InferGenericArgument(methodInstance, argInvokeMethod->GetParamType(-1), delegateInfo->mParams[0], BfIRValue());
  503. int wantInvokeOffset = delegateInfo->mHasExplicitThis ? 1 : 0;
  504. if ((argInvokeMethod != NULL) && (wantInvokeMethod != NULL) && (argInvokeMethod->GetParamCount() == wantInvokeMethod->GetParamCount() - wantInvokeOffset))
  505. {
  506. InferGenericArgument(methodInstance, argInvokeMethod->mReturnType, wantInvokeMethod->mReturnType, BfIRValue());
  507. for (int argIdx = 0; argIdx < (int)argInvokeMethod->GetParamCount(); argIdx++)
  508. InferGenericArgument(methodInstance, argInvokeMethod->GetParamType(argIdx), wantInvokeMethod->GetParamType(argIdx + wantInvokeOffset), BfIRValue());
  509. }
  510. }
  511. }
  512. return true;
  513. }
  514. int BfMethodMatcher::GetMostSpecificType(BfType* lhs, BfType* rhs)
  515. {
  516. if ((lhs->IsRef()) && (rhs->IsRef()))
  517. return GetMostSpecificType(lhs->GetUnderlyingType(), rhs->GetUnderlyingType());
  518. if ((lhs->IsPointer()) && (rhs->IsPointer()))
  519. return GetMostSpecificType(lhs->GetUnderlyingType(), rhs->GetUnderlyingType());
  520. if ((lhs->IsSizedArray()) && (rhs->IsSizedArray()))
  521. return GetMostSpecificType(lhs->GetUnderlyingType(), rhs->GetUnderlyingType());
  522. if (lhs->IsGenericParam())
  523. return rhs->IsGenericParam() ? -1 : 1;
  524. if (rhs->IsGenericParam())
  525. return 0;
  526. if ((lhs->IsUnspecializedType()) && (lhs->IsGenericTypeInstance()))
  527. {
  528. if ((!rhs->IsUnspecializedType()) || (!rhs->IsGenericTypeInstance()))
  529. return 1;
  530. auto lhsTypeInst = lhs->ToTypeInstance();
  531. auto rhsTypeInst = rhs->ToTypeInstance();
  532. if ((rhsTypeInst == NULL) || (lhsTypeInst == NULL) || (lhsTypeInst->mTypeDef != rhsTypeInst->mTypeDef))
  533. return -1;
  534. bool hadLHSMoreSpecific = false;
  535. bool hadRHSMoreSpecific = false;
  536. for (int generigArgIdx = 0; generigArgIdx < (int)lhsTypeInst->mGenericTypeInfo->mTypeGenericArguments.size(); generigArgIdx++)
  537. {
  538. int argMoreSpecific = GetMostSpecificType(lhsTypeInst->mGenericTypeInfo->mTypeGenericArguments[generigArgIdx],
  539. rhsTypeInst->mGenericTypeInfo->mTypeGenericArguments[generigArgIdx]);
  540. if (argMoreSpecific == 0)
  541. hadLHSMoreSpecific = true;
  542. else if (argMoreSpecific == 1)
  543. hadRHSMoreSpecific = true;
  544. }
  545. if ((hadLHSMoreSpecific) && (!hadRHSMoreSpecific))
  546. return 0;
  547. if ((hadRHSMoreSpecific) && (!hadLHSMoreSpecific))
  548. return 1;
  549. return -1;
  550. }
  551. if (rhs->IsUnspecializedType())
  552. return 0;
  553. return -1;
  554. }
  555. void BfMethodMatcher::CompareMethods(BfMethodInstance* prevMethodInstance, BfTypeVector* prevGenericArgumentsSubstitute,
  556. BfMethodInstance* newMethodInstance, BfTypeVector* genericArgumentsSubstitute,
  557. bool* outNewIsBetter, bool* outNewIsWorse, bool allowSpecializeFail)
  558. {
  559. if (prevMethodInstance == newMethodInstance)
  560. {
  561. *outNewIsBetter = false;
  562. *outNewIsWorse = true;
  563. return;
  564. }
  565. #define SET_BETTER_OR_WORSE(lhs, rhs) \
  566. if ((!isBetter) && (lhs) && !(rhs)) isBetter = true; \
  567. if ((!isWorse) && !(lhs) && (rhs)) isWorse = true;
  568. #define RETURN_BETTER_OR_WORSE(lhs, rhs) \
  569. if ((!isBetter) && (lhs) && !(rhs)) { *outNewIsBetter = true; *outNewIsWorse = false; return; } \
  570. if ((!isWorse) && !(lhs) && (rhs)) { *outNewIsBetter = false; *outNewIsWorse = true; return; };
  571. #define RETURN_RESULTS \
  572. *outNewIsBetter = isBetter; \
  573. *outNewIsWorse = isWorse; \
  574. return;
  575. int numUsedParams = 0;
  576. int prevNumUsedParams = 0;
  577. bool usedExtendedForm = false;
  578. bool prevUsedExtendedForm = false;
  579. bool isBetter = false;
  580. bool isWorse = false;
  581. int argIdx;
  582. BfMethodDef* prevMethodDef = prevMethodInstance->mMethodDef;
  583. BfMethodDef* newMethodDef = newMethodInstance->mMethodDef;
  584. if (prevMethodDef == mBackupMethodDef)
  585. {
  586. // This can happen for extension methods and such
  587. *outNewIsBetter = true;
  588. *outNewIsWorse = false;
  589. return;
  590. }
  591. if (newMethodDef->mExplicitInterface != prevMethodDef->mExplicitInterface)
  592. {
  593. if (mModule->CompareMethodSignatures(newMethodInstance, prevMethodInstance))
  594. {
  595. SET_BETTER_OR_WORSE(newMethodDef->mExplicitInterface != NULL, prevMethodDef->mExplicitInterface != NULL);
  596. *outNewIsBetter = isBetter;
  597. *outNewIsWorse = isWorse;
  598. return;
  599. }
  600. }
  601. bool anyIsExtension = false;
  602. int newImplicitParamCount = newMethodInstance->GetImplicitParamCount();
  603. if (newMethodInstance->mMethodDef->mHasAppend)
  604. newImplicitParamCount++;
  605. if (newMethodInstance->mMethodDef->mMethodType == BfMethodType_Extension)
  606. {
  607. newImplicitParamCount++;
  608. anyIsExtension = true;
  609. }
  610. int prevImplicitParamCount = prevMethodInstance->GetImplicitParamCount();
  611. if (prevMethodInstance->mMethodDef->mHasAppend)
  612. prevImplicitParamCount++;
  613. if (prevMethodInstance->mMethodDef->mMethodType == BfMethodType_Extension)
  614. {
  615. prevImplicitParamCount++;
  616. anyIsExtension = true;
  617. }
  618. bool hadEnoughArgs = newMethodInstance->GetParamCount() - newImplicitParamCount < (int)mArguments.size();
  619. bool prevHadEnoughArgs = prevMethodInstance->GetParamCount() - prevImplicitParamCount < (int)mArguments.size();
  620. RETURN_BETTER_OR_WORSE(hadEnoughArgs, prevHadEnoughArgs);
  621. bool chainSkip = (newMethodInstance->mChainType == BfMethodChainType_ChainMember) || (newMethodInstance->mChainType == BfMethodChainType_ChainSkip);
  622. bool prevChainSkip = (prevMethodInstance->mChainType == BfMethodChainType_ChainMember) || (prevMethodInstance->mChainType == BfMethodChainType_ChainSkip);
  623. RETURN_BETTER_OR_WORSE(!chainSkip, !prevChainSkip);
  624. if ((!isBetter) && (!isWorse))
  625. {
  626. bool betterByGenericParam = false;
  627. bool worseByGenericParam = false;
  628. bool betterByConstExprParam = false;
  629. bool worseByConstExprParam = false;
  630. bool someArgWasBetter = false;
  631. bool someArgWasWorse = false;
  632. for (argIdx = anyIsExtension ? -1 : 0; argIdx < (int)mArguments.size(); argIdx++)
  633. {
  634. BfTypedValue arg;
  635. BfResolvedArg* resolvedArg = NULL;
  636. bool wasArgDeferred = false;
  637. if (argIdx == -1)
  638. {
  639. arg = mTarget;
  640. }
  641. else
  642. {
  643. resolvedArg = &mArguments[argIdx];
  644. wasArgDeferred = resolvedArg->mArgFlags != 0;
  645. arg = resolvedArg->mTypedValue;
  646. }
  647. int newArgIdx = argIdx + newImplicitParamCount;
  648. int prevArgIdx = argIdx + prevImplicitParamCount;
  649. bool wasGenericParam = (newArgIdx >= 0) && newMethodInstance->WasGenericParam(newArgIdx);
  650. bool prevWasGenericParam = (prevArgIdx >= 0) && prevMethodInstance->WasGenericParam(prevArgIdx);
  651. BfType* paramType = newMethodInstance->GetParamType(newArgIdx, true);
  652. BfType* prevParamType = prevMethodInstance->GetParamType(prevArgIdx, true);
  653. numUsedParams++;
  654. prevNumUsedParams++;
  655. BfType* origParamType = paramType;
  656. BfType* origPrevParamType = prevParamType;
  657. bool paramWasConstExpr = false;
  658. bool prevParamWasConstExpr = false;
  659. bool paramWasUnspecialized = paramType->IsUnspecializedType();
  660. if ((genericArgumentsSubstitute != NULL) && (paramWasUnspecialized))
  661. {
  662. paramType = mModule->ResolveGenericType(paramType, NULL, genericArgumentsSubstitute, allowSpecializeFail);
  663. paramType = mModule->FixIntUnknown(paramType);
  664. }
  665. if (paramType->IsConstExprValue())
  666. {
  667. prevParamWasConstExpr = true;
  668. paramType = ((BfConstExprValueType*)paramType)->mType;
  669. }
  670. bool prevParamWasUnspecialized = prevParamType->IsUnspecializedType();
  671. if ((prevGenericArgumentsSubstitute != NULL) && (prevParamWasUnspecialized))
  672. {
  673. prevParamType = mModule->ResolveGenericType(prevParamType, NULL, prevGenericArgumentsSubstitute, allowSpecializeFail);
  674. prevParamType = mModule->FixIntUnknown(prevParamType);
  675. }
  676. if (prevParamType->IsConstExprValue())
  677. {
  678. prevParamWasConstExpr = true;
  679. prevParamType = ((BfConstExprValueType*)prevParamType)->mType;
  680. }
  681. bool paramsEquivalent = paramType == prevParamType;
  682. if ((prevParamType == NULL) || (paramType == NULL))
  683. {
  684. SET_BETTER_OR_WORSE(paramType != NULL, prevParamType != NULL);
  685. }
  686. else if (paramType != prevParamType)
  687. {
  688. bool isUnspecializedParam = paramType->IsUnspecializedType();
  689. bool isPrevUnspecializedParam = prevParamType->IsUnspecializedType();
  690. SET_BETTER_OR_WORSE((!isUnspecializedParam) && (!paramType->IsVar()),
  691. (!isPrevUnspecializedParam) && (!prevParamType->IsVar()));
  692. if ((!isBetter) && (!isWorse) && (!isUnspecializedParam) && (!isPrevUnspecializedParam))
  693. {
  694. SET_BETTER_OR_WORSE((paramType != NULL) && (!paramType->IsUnspecializedType()),
  695. (prevParamType != NULL) && (!prevParamType->IsUnspecializedType()));
  696. if ((!isBetter) && (!isWorse))
  697. {
  698. // The resolved argument type may actually match for both considered functions. IE:
  699. // Method(int8 val) and Method(int16 val) called with Method(0) will create arguments that match their param types
  700. if ((!wasArgDeferred) && (!wasGenericParam) && (IsType(arg, paramType)) && ((resolvedArg == NULL) || (prevParamType != resolvedArg->mBestBoundType)))
  701. isBetter = true;
  702. //else if ((!prevWasGenericParam) && (IsType(arg, prevParamType)) && (!IsType(arg, paramType)))
  703. else if ((!wasArgDeferred) && (!prevWasGenericParam) && (IsType(arg, prevParamType)) && ((resolvedArg == NULL) || (paramType != resolvedArg->mBestBoundType)))
  704. isWorse = true;
  705. else
  706. {
  707. bool canCastFromCurToPrev = mModule->CanCast(mModule->GetFakeTypedValue(paramType), prevParamType);
  708. bool canCastFromPrevToCur = mModule->CanCast(mModule->GetFakeTypedValue(prevParamType), paramType);
  709. if ((canCastFromCurToPrev) && (canCastFromPrevToCur))
  710. paramsEquivalent = true;
  711. if ((canCastFromCurToPrev) && (!canCastFromPrevToCur))
  712. isBetter = true;
  713. else if ((canCastFromPrevToCur) && (!canCastFromCurToPrev))
  714. isWorse = true;
  715. else if ((paramType->IsIntegral()) && (prevParamType->IsIntegral()))
  716. {
  717. if (paramType == arg.mType)
  718. isBetter = true;
  719. else if (prevParamType == arg.mType)
  720. isWorse = true;
  721. else
  722. {
  723. if (paramType->mSize < prevParamType->mSize)
  724. isBetter = true;
  725. else if (paramType->mSize > prevParamType->mSize)
  726. isWorse = true;
  727. else if (paramType->IsSigned())
  728. isBetter = true;
  729. else
  730. isWorse = true;
  731. }
  732. }
  733. else if ((wasArgDeferred) && ((paramType->IsIntegral()) || (prevParamType->IsIntegral())))
  734. {
  735. SET_BETTER_OR_WORSE(paramType->IsIntegral(), prevParamType->IsIntegral());
  736. }
  737. }
  738. }
  739. }
  740. }
  741. if ((!isBetter) & (!isWorse) && (paramsEquivalent))
  742. {
  743. if ((origParamType != origPrevParamType) && (paramWasConstExpr) && (!prevParamWasConstExpr))
  744. betterByConstExprParam = true;
  745. else if ((origParamType != origPrevParamType) && (!paramWasConstExpr) && (prevParamWasConstExpr))
  746. worseByConstExprParam = true;
  747. else if (((paramWasUnspecialized) || (prevParamWasUnspecialized)))
  748. {
  749. int origTypeMoreSpecific = GetMostSpecificType(origParamType, origPrevParamType);
  750. if (origTypeMoreSpecific == 0)
  751. betterByGenericParam = true;
  752. else if (origTypeMoreSpecific == 1)
  753. worseByGenericParam = true;
  754. }
  755. }
  756. if ((newArgIdx >= 0) && (newMethodInstance->GetParamKind(newArgIdx) == BfParamKind_Params))
  757. usedExtendedForm = true;
  758. if ((prevArgIdx >= 0) && (prevMethodInstance->GetParamKind(prevArgIdx) == BfParamKind_Params))
  759. prevUsedExtendedForm = true;
  760. if ((usedExtendedForm) || (prevUsedExtendedForm))
  761. break;
  762. someArgWasBetter |= isBetter;
  763. someArgWasWorse |= isWorse;
  764. isBetter = false;
  765. isWorse = false;
  766. }
  767. isBetter |= someArgWasBetter;
  768. isWorse |= someArgWasWorse;
  769. if ((!isBetter) && (!isWorse))
  770. {
  771. // Don't allow ambiguity
  772. if ((betterByGenericParam && !worseByGenericParam) ||
  773. (!betterByGenericParam && worseByGenericParam))
  774. {
  775. isBetter = betterByGenericParam;
  776. isWorse = worseByGenericParam;
  777. }
  778. }
  779. if ((!isBetter) && (!isWorse))
  780. {
  781. // Don't allow ambiguity
  782. if ((betterByConstExprParam && !worseByConstExprParam) ||
  783. (!betterByConstExprParam && worseByConstExprParam))
  784. {
  785. isBetter = betterByConstExprParam;
  786. isWorse = worseByConstExprParam;
  787. }
  788. }
  789. if ((isBetter) || (isWorse))
  790. {
  791. RETURN_RESULTS;
  792. }
  793. }
  794. // Check for unused extended params as next param - that still counts as using extended form
  795. usedExtendedForm = newMethodInstance->HasParamsArray();
  796. prevUsedExtendedForm = prevMethodInstance->HasParamsArray();
  797. RETURN_BETTER_OR_WORSE(newMethodInstance->GetNumGenericArguments() == 0, prevMethodInstance->GetNumGenericArguments() == 0);
  798. // Not using generic delegate params is better
  799. RETURN_BETTER_OR_WORSE(!newMethodInstance->mHadGenericDelegateParams, !prevMethodInstance->mHadGenericDelegateParams);
  800. // Normal form trumps extended form
  801. RETURN_BETTER_OR_WORSE(!usedExtendedForm, !prevUsedExtendedForm);
  802. // More used params trumps less params
  803. int paramDiff = (int) numUsedParams - (int) prevNumUsedParams;
  804. RETURN_BETTER_OR_WORSE(paramDiff > 0, paramDiff < 0);
  805. // Fewer defaults trumps more defaults
  806. // Since we know the number of used params is the same (previous check), we infer that the rest are defaults
  807. paramDiff = (int) newMethodInstance->GetParamCount() - (int) prevMethodInstance->GetParamCount();
  808. RETURN_BETTER_OR_WORSE(paramDiff < 0, paramDiff > 0);
  809. // Check specificity of args
  810. std::function<void(BfType*, BfType*)> _CompareParamTypes = [&](BfType* newType, BfType* prevType)
  811. {
  812. if ((newType->IsGenericParam()) && (prevType->IsGenericParam()))
  813. {
  814. auto newGenericParamType = (BfGenericParamType*)newType;
  815. auto prevGenericParamType = (BfGenericParamType*)prevType;
  816. if ((newGenericParamType->mGenericParamKind == BfGenericParamKind_Method) && (prevGenericParamType->mGenericParamKind == BfGenericParamKind_Method))
  817. {
  818. auto newMethodGenericParam = newMethodInstance->mMethodInfoEx->mGenericParams[newGenericParamType->mGenericParamIdx];
  819. auto prevMethodGenericParam = prevMethodInstance->mMethodInfoEx->mGenericParams[prevGenericParamType->mGenericParamIdx];
  820. SET_BETTER_OR_WORSE(mModule->AreConstraintsSubset(prevMethodGenericParam, newMethodGenericParam), mModule->AreConstraintsSubset(newMethodGenericParam, prevMethodGenericParam));
  821. }
  822. }
  823. else if (newType == prevType)
  824. {
  825. if ((newType->IsUnspecializedType()) && (newType->IsGenericTypeInstance()))
  826. {
  827. BfTypeInstance* newGenericType = (BfTypeInstance*)newType;
  828. BfTypeInstance* prevGenericType = (BfTypeInstance*)prevType;
  829. for (int genericArgIdx = 0; genericArgIdx < (int)newGenericType->mGenericTypeInfo->mTypeGenericArguments.size(); genericArgIdx++)
  830. {
  831. _CompareParamTypes(newGenericType->mGenericTypeInfo->mTypeGenericArguments[genericArgIdx], prevGenericType->mGenericTypeInfo->mTypeGenericArguments[genericArgIdx]);
  832. }
  833. }
  834. }
  835. else
  836. {
  837. //TODO: Why did we need this?
  838. //isBetter |= mModule->IsTypeMoreSpecific(newType, prevType);
  839. //isWorse |= mModule->IsTypeMoreSpecific(prevType, newType);
  840. }
  841. };
  842. int paramCheckCount = (int)BF_MIN(newMethodInstance->GetParamCount() - newImplicitParamCount, prevMethodInstance->GetParamCount() - prevImplicitParamCount);
  843. for (argIdx = 0; argIdx < (int)paramCheckCount/*mArguments.size()*/; argIdx++)
  844. {
  845. int newArgIdx = argIdx + newImplicitParamCount;
  846. int prevArgIdx = argIdx + prevImplicitParamCount;
  847. _CompareParamTypes(newMethodInstance->GetParamType(newArgIdx), prevMethodInstance->GetParamType(prevArgIdx));
  848. }
  849. // Do generic constraint subset test directly to handle cases like "NotDisposed<T>()" vs "NotDisposed<T>() where T : IDisposable"
  850. if ((newMethodInstance->GetNumGenericArguments() > 0) && (newMethodInstance->GetNumGenericArguments() == prevMethodInstance->GetNumGenericArguments()))
  851. {
  852. for (int genericParamIdx = 0; genericParamIdx < (int)newMethodInstance->GetNumGenericArguments(); genericParamIdx++)
  853. {
  854. auto newMethodGenericParam = newMethodInstance->mMethodInfoEx->mGenericParams[genericParamIdx];
  855. auto prevMethodGenericParam = prevMethodInstance->mMethodInfoEx->mGenericParams[genericParamIdx];
  856. SET_BETTER_OR_WORSE(mModule->AreConstraintsSubset(prevMethodGenericParam, newMethodGenericParam), mModule->AreConstraintsSubset(newMethodGenericParam, prevMethodGenericParam));
  857. }
  858. if ((!isBetter) && (!isWorse))
  859. {
  860. SET_BETTER_OR_WORSE(newMethodInstance->HasExternConstraints(), prevMethodInstance->HasExternConstraints());
  861. }
  862. }
  863. if ((isBetter) || (isWorse))
  864. {
  865. RETURN_RESULTS;
  866. }
  867. // Does one have a body and one doesn't? Obvious!
  868. isBetter = prevMethodDef->IsEmptyPartial();
  869. isWorse = newMethodDef->IsEmptyPartial();
  870. if ((isBetter) && (isWorse))
  871. {
  872. // If both are empty partials then just bind to either
  873. isWorse = true;
  874. RETURN_RESULTS;
  875. }
  876. // For operators, prefer explicit comparison over '<=>' comparison operator
  877. if ((!isBetter) && (!isWorse))
  878. {
  879. if ((prevMethodDef->mIsOperator) && (newMethodDef->mIsOperator))
  880. {
  881. bool newIsComparison = ((BfOperatorDeclaration*)newMethodDef->mMethodDeclaration)->mBinOp == BfBinaryOp_Compare;
  882. bool prevIsComparison = ((BfOperatorDeclaration*)prevMethodDef->mMethodDeclaration)->mBinOp == BfBinaryOp_Compare;
  883. RETURN_BETTER_OR_WORSE(!newIsComparison, !prevIsComparison);
  884. }
  885. }
  886. // For extensions, select the version in the most-specific project (only applicable for ctors)
  887. if ((!isBetter) && (!isWorse))
  888. {
  889. auto newProject = newMethodDef->mDeclaringType->mProject;
  890. auto prevProject = prevMethodDef->mDeclaringType->mProject;
  891. if (newProject != prevProject)
  892. {
  893. RETURN_BETTER_OR_WORSE(newProject->ContainsReference(prevProject), prevProject->ContainsReference(newProject));
  894. }
  895. }
  896. // If we have conditional type extensions that both define an implementation for a method, use the most-specific conditional extension constraints
  897. auto owner = newMethodInstance->GetOwner();
  898. if ((newMethodDef->mDeclaringType != prevMethodDef->mDeclaringType) && (owner->IsGenericTypeInstance()))
  899. {
  900. auto genericOwner = (BfTypeInstance*)owner;
  901. if (genericOwner->mGenericTypeInfo->mGenericExtensionInfo != NULL)
  902. {
  903. BfGenericExtensionEntry* newGenericExtesionEntry = NULL;
  904. BfGenericExtensionEntry* prevGenericExtesionEntry = NULL;
  905. if ((genericOwner->mGenericTypeInfo->mGenericExtensionInfo->mExtensionMap.TryGetValue(newMethodDef->mDeclaringType, &newGenericExtesionEntry)) &&
  906. (genericOwner->mGenericTypeInfo->mGenericExtensionInfo->mExtensionMap.TryGetValue(prevMethodDef->mDeclaringType, &prevGenericExtesionEntry)))
  907. {
  908. if ((newGenericExtesionEntry->mGenericParams.size() == prevGenericExtesionEntry->mGenericParams.size()))
  909. {
  910. for (int genericParamIdx = 0; genericParamIdx < (int)newGenericExtesionEntry->mGenericParams.size(); genericParamIdx++)
  911. {
  912. auto newMethodGenericParam = newGenericExtesionEntry->mGenericParams[genericParamIdx];
  913. auto prevMethodGenericParam = prevGenericExtesionEntry->mGenericParams[genericParamIdx];
  914. SET_BETTER_OR_WORSE(mModule->AreConstraintsSubset(prevMethodGenericParam, newMethodGenericParam), mModule->AreConstraintsSubset(newMethodGenericParam, prevMethodGenericParam));
  915. }
  916. }
  917. if ((isBetter) || (isWorse))
  918. {
  919. RETURN_RESULTS;
  920. }
  921. }
  922. }
  923. }
  924. RETURN_BETTER_OR_WORSE(newMethodDef->mCheckedKind == mCheckedKind, prevMethodDef->mCheckedKind == mCheckedKind);
  925. RETURN_BETTER_OR_WORSE(newMethodDef->mCommutableKind != BfCommutableKind_Reverse, prevMethodDef->mCommutableKind != BfCommutableKind_Reverse);
  926. // If one of these methods is local to the current extension then choose that one
  927. auto activeDef = mModule->GetActiveTypeDef();
  928. RETURN_BETTER_OR_WORSE(newMethodDef->mDeclaringType == activeDef, prevMethodDef->mDeclaringType == activeDef);
  929. RETURN_BETTER_OR_WORSE(newMethodDef->mDeclaringType->IsExtension(), prevMethodDef->mDeclaringType->IsExtension());
  930. RETURN_BETTER_OR_WORSE(newMethodDef->mIsMutating, prevMethodDef->mIsMutating);
  931. RETURN_RESULTS;
  932. }
  933. BfTypedValue BfMethodMatcher::ResolveArgTypedValue(BfResolvedArg& resolvedArg, BfType* checkType, BfTypeVector* genericArgumentsSubstitute, BfType *origCheckType)
  934. {
  935. BfTypedValue argTypedValue = resolvedArg.mTypedValue;
  936. if ((resolvedArg.mArgFlags & BfArgFlag_DelegateBindAttempt) != 0)
  937. {
  938. BfExprEvaluator exprEvaluator(mModule);
  939. exprEvaluator.mExpectingType = checkType;
  940. BF_ASSERT(resolvedArg.mExpression->IsA<BfDelegateBindExpression>());
  941. auto delegateBindExpr = BfNodeDynCast<BfDelegateBindExpression>(resolvedArg.mExpression);
  942. BfMethodInstance* boundMethodInstance = NULL;
  943. if (exprEvaluator.CanBindDelegate(delegateBindExpr, &boundMethodInstance, origCheckType, genericArgumentsSubstitute))
  944. {
  945. if (delegateBindExpr->mNewToken == NULL)
  946. {
  947. if (boundMethodInstance->GetOwner()->IsFunction())
  948. {
  949. return BfTypedValue(mModule->mBfIRBuilder->GetFakeVal(), boundMethodInstance->GetOwner());
  950. }
  951. else if (boundMethodInstance->mDisallowCalling)
  952. {
  953. argTypedValue = BfTypedValue(mModule->mBfIRBuilder->GetFakeVal(), checkType);
  954. }
  955. else
  956. {
  957. resolvedArg.mExpectedType = checkType;
  958. auto methodRefType = mModule->CreateMethodRefType(boundMethodInstance);
  959. mModule->AddDependency(methodRefType, mModule->mCurTypeInstance, BfDependencyMap::DependencyFlag_Calls);
  960. mModule->AddCallDependency(boundMethodInstance);
  961. argTypedValue = BfTypedValue(mModule->mBfIRBuilder->GetFakeVal(), methodRefType);
  962. }
  963. }
  964. else
  965. argTypedValue = BfTypedValue(BfTypedValueKind_UntypedValue);
  966. }
  967. }
  968. else if ((resolvedArg.mArgFlags & BfArgFlag_LambdaBindAttempt) != 0)
  969. {
  970. BfExprEvaluator exprEvaluator(mModule);
  971. exprEvaluator.mExpectingType = checkType;
  972. BF_ASSERT(resolvedArg.mExpression->IsA<BfLambdaBindExpression>());
  973. auto lambdaBindExpr = (BfLambdaBindExpression*)resolvedArg.mExpression;
  974. if ((checkType != NULL) && (checkType->IsDelegate()))
  975. {
  976. BfMethodInstance* methodInstance = mModule->GetRawMethodInstanceAtIdx(checkType->ToTypeInstance(), 0, "Invoke");
  977. if (methodInstance != NULL)
  978. {
  979. if (methodInstance->GetParamCount() == (int)lambdaBindExpr->mParams.size())
  980. {
  981. if (lambdaBindExpr->mNewToken == NULL)
  982. {
  983. if (!resolvedArg.mTypedValue)
  984. {
  985. // Resolve for real
  986. resolvedArg.mTypedValue = mModule->CreateValueFromExpression(lambdaBindExpr, checkType, BfEvalExprFlags_NoCast);
  987. }
  988. argTypedValue = resolvedArg.mTypedValue;
  989. }
  990. else
  991. argTypedValue = BfTypedValue(BfTypedValueKind_UntypedValue);
  992. //argTypedValue = BfTypedValue(mModule->mBfIRBuilder->GetFakeVal(), checkType);
  993. }
  994. }
  995. }
  996. }
  997. else if ((resolvedArg.mArgFlags & BfArgFlag_UnqualifiedDotAttempt) != 0)
  998. {
  999. if ((checkType != NULL) && (checkType->IsPayloadEnum()))
  1000. {
  1001. // Should we actually check the member name?
  1002. argTypedValue = BfTypedValue(BfTypedValueKind_UntypedValue);
  1003. }
  1004. }
  1005. else if ((resolvedArg.mArgFlags & BfArgFlag_UntypedDefault) != 0)
  1006. {
  1007. if (checkType != NULL)
  1008. argTypedValue = BfTypedValue(BfTypedValueKind_UntypedValue);
  1009. }
  1010. else if ((resolvedArg.mArgFlags & BfArgFlag_DeferredEval) != 0)
  1011. {
  1012. if (resolvedArg.mExpression != NULL)
  1013. {
  1014. if ((resolvedArg.mExpectedType != checkType) || (resolvedArg.mExpectedType == NULL)) // Did our last check match for this type?
  1015. {
  1016. SetAndRestoreValue<bool> prevIgnoreWrites(mModule->mBfIRBuilder->mIgnoreWrites, true);
  1017. SetAndRestoreValue<bool> prevIgnoreError(mModule->mIgnoreErrors, true);
  1018. bool prevNoBind = false;
  1019. if (mModule->mCurMethodState != NULL)
  1020. {
  1021. prevNoBind = mModule->mCurMethodState->mNoBind;
  1022. mModule->mCurMethodState->mNoBind = true;
  1023. }
  1024. auto prevBlock = mModule->mBfIRBuilder->GetInsertBlock();
  1025. BfExprEvaluator exprEvaluator(mModule);
  1026. exprEvaluator.mBfEvalExprFlags = (BfEvalExprFlags)(exprEvaluator.mBfEvalExprFlags | BfEvalExprFlags_AllowIntUnknown | BfEvalExprFlags_NoAutoComplete);
  1027. if ((resolvedArg.mArgFlags & BfArgFlag_ParamsExpr) != 0)
  1028. exprEvaluator.mBfEvalExprFlags = (BfEvalExprFlags)(exprEvaluator.mBfEvalExprFlags | BfEvalExprFlags_AllowParamsExpr);
  1029. auto expectType = checkType;
  1030. if (expectType != NULL)
  1031. {
  1032. if (expectType->IsRef())
  1033. {
  1034. auto refType = (BfRefType*)expectType;
  1035. expectType = refType->mElementType;
  1036. }
  1037. if ((genericArgumentsSubstitute != NULL) && (expectType->IsUnspecializedType()))
  1038. expectType = mModule->ResolveGenericType(expectType, NULL, genericArgumentsSubstitute, true);
  1039. }
  1040. exprEvaluator.mExpectingType = expectType;
  1041. exprEvaluator.Evaluate(resolvedArg.mExpression);
  1042. argTypedValue = exprEvaluator.GetResult();
  1043. if (mModule->mCurMethodState != NULL)
  1044. mModule->mCurMethodState->mNoBind = prevNoBind;
  1045. if ((argTypedValue) && (!argTypedValue.mType->IsVar()))
  1046. {
  1047. if (checkType != NULL)
  1048. resolvedArg.mExpectedType = checkType;
  1049. auto storeTypedValue = argTypedValue;
  1050. if ((storeTypedValue.mValue) & (!storeTypedValue.mValue.IsFake()))
  1051. {
  1052. // We actually want to ensure that this cached value is a fake val. There are potential cases where a fake val
  1053. // won't be generated but we should throw an error, so we need to make sure we actually re-evaluate when the call
  1054. // is generated
  1055. //storeTypedValue.mValue = mModule->mBfIRBuilder->GetFakeVal();
  1056. resolvedArg.mWantsRecalc = true;
  1057. }
  1058. resolvedArg.mTypedValue = storeTypedValue;
  1059. //BF_ASSERT(argTypedValue.mValue.mId != -1);
  1060. }
  1061. mModule->mBfIRBuilder->SetInsertPoint(prevBlock);
  1062. }
  1063. }
  1064. }
  1065. else if ((resolvedArg.mArgFlags & BfArgFlag_VariableDeclaration) != 0)
  1066. {
  1067. if ((checkType != NULL) && (checkType->IsRef()))
  1068. argTypedValue = BfTypedValue(BfTypedValueKind_UntypedValue);
  1069. }
  1070. return argTypedValue;
  1071. }
  1072. bool BfMethodMatcher::WantsCheckMethod(BfProtectionCheckFlags& flags, BfTypeInstance* startTypeInstance, BfTypeInstance* checkTypeInstance, BfMethodDef* checkMethod)
  1073. {
  1074. MatchFailKind matchFailKind = MatchFailKind_None;
  1075. if (!mModule->CheckProtection(flags, checkTypeInstance, checkMethod->mDeclaringType->mProject, checkMethod->mProtection, startTypeInstance))
  1076. {
  1077. if ((mBypassVirtual) &&
  1078. ((checkMethod->mProtection == BfProtection_Protected) || (checkMethod->mProtection == BfProtection_ProtectedInternal)) &&
  1079. (mModule->TypeIsSubTypeOf(mModule->mCurTypeInstance, startTypeInstance)))
  1080. {
  1081. // Allow explicit 'base' call
  1082. }
  1083. else
  1084. {
  1085. return false;
  1086. }
  1087. }
  1088. if (mCheckedKind != checkMethod->mCheckedKind)
  1089. {
  1090. bool passes = true;
  1091. if (mCheckedKind != BfCheckedKind_NotSet)
  1092. {
  1093. passes = false;
  1094. }
  1095. else
  1096. {
  1097. auto defaultCheckedKind = mModule->GetDefaultCheckedKind();
  1098. if (defaultCheckedKind != checkMethod->mCheckedKind)
  1099. passes = false;
  1100. }
  1101. if (!passes)
  1102. {
  1103. return false;
  1104. }
  1105. }
  1106. return true;
  1107. }
  1108. bool BfMethodMatcher::InferFromGenericConstraints(BfGenericParamInstance* genericParamInst, BfTypeVector* methodGenericArgs)
  1109. {
  1110. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_Equals) == 0)
  1111. return false;
  1112. if (!genericParamInst->mExternType->IsGenericParam())
  1113. return false;
  1114. auto genericParamType = (BfGenericParamType*)genericParamInst->mExternType;
  1115. if (genericParamType->mGenericParamKind != BfGenericParamKind_Method)
  1116. return false;
  1117. BfType* checkArgType = NULL;
  1118. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_Equals_Type) != 0)
  1119. {
  1120. checkArgType = genericParamInst->mTypeConstraint;
  1121. }
  1122. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_Equals_IFace) != 0)
  1123. {
  1124. if (!genericParamInst->mInterfaceConstraints.IsEmpty())
  1125. checkArgType = genericParamInst->mInterfaceConstraints[0];
  1126. }
  1127. for (auto& checkOpConstraint : genericParamInst->mOperatorConstraints)
  1128. {
  1129. auto leftType = checkOpConstraint.mLeftType;
  1130. if ((leftType != NULL) && (leftType->IsUnspecializedType()))
  1131. leftType = mModule->ResolveGenericType(leftType, NULL, methodGenericArgs);
  1132. if (leftType != NULL)
  1133. leftType = mModule->FixIntUnknown(leftType);
  1134. auto rightType = checkOpConstraint.mRightType;
  1135. if ((rightType != NULL) && (rightType->IsUnspecializedType()))
  1136. rightType = mModule->ResolveGenericType(rightType, NULL, methodGenericArgs);
  1137. if (rightType != NULL)
  1138. rightType = mModule->FixIntUnknown(rightType);
  1139. BfConstraintState constraintSet;
  1140. constraintSet.mPrevState = mModule->mContext->mCurConstraintState;
  1141. constraintSet.mGenericParamInstance = genericParamInst;
  1142. constraintSet.mLeftType = leftType;
  1143. constraintSet.mRightType = rightType;
  1144. SetAndRestoreValue<BfConstraintState*> prevConstraintSet(mModule->mContext->mCurConstraintState, &constraintSet);
  1145. if (!mModule->CheckConstraintState(NULL))
  1146. return false;
  1147. if (checkOpConstraint.mBinaryOp != BfBinaryOp_None)
  1148. {
  1149. BfExprEvaluator exprEvaluator(mModule);
  1150. BfTypedValue leftValue(mModule->mBfIRBuilder->GetFakeVal(), leftType);
  1151. BfTypedValue rightValue(mModule->mBfIRBuilder->GetFakeVal(), rightType);
  1152. //
  1153. {
  1154. SetAndRestoreValue<bool> prevIgnoreErrors(mModule->mIgnoreErrors, true);
  1155. SetAndRestoreValue<bool> prevIgnoreWrites(mModule->mBfIRBuilder->mIgnoreWrites, true);
  1156. exprEvaluator.PerformBinaryOperation(NULL, NULL, checkOpConstraint.mBinaryOp, NULL, BfBinOpFlag_NoClassify, leftValue, rightValue);
  1157. }
  1158. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_Equals_Op) != 0)
  1159. checkArgType = exprEvaluator.mResult.mType;
  1160. }
  1161. else
  1162. {
  1163. BfTypedValue rightValue(mModule->mBfIRBuilder->GetFakeVal(), rightType);
  1164. StringT<128> failedOpName;
  1165. if (checkOpConstraint.mCastToken == BfToken_Implicit)
  1166. {
  1167. }
  1168. else
  1169. {
  1170. SetAndRestoreValue<bool> prevIgnoreErrors(mModule->mIgnoreErrors, true);
  1171. SetAndRestoreValue<bool> prevIgnoreWrites(mModule->mBfIRBuilder->mIgnoreWrites, true);
  1172. if (checkOpConstraint.mCastToken == BfToken_Explicit)
  1173. {
  1174. }
  1175. else
  1176. {
  1177. BfExprEvaluator exprEvaluator(mModule);
  1178. exprEvaluator.mResult = rightValue;
  1179. exprEvaluator.PerformUnaryOperation(NULL, checkOpConstraint.mUnaryOp, NULL, BfUnaryOpFlag_IsConstraintCheck);
  1180. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_Equals_Op) != 0)
  1181. checkArgType = exprEvaluator.mResult.mType;
  1182. }
  1183. }
  1184. }
  1185. }
  1186. if (checkArgType == NULL)
  1187. return false;
  1188. if (checkArgType->IsVar())
  1189. return false;
  1190. (*methodGenericArgs)[genericParamType->mGenericParamIdx] = checkArgType;
  1191. return true;
  1192. }
  1193. bool BfMethodMatcher::CheckMethod(BfTypeInstance* targetTypeInstance, BfTypeInstance* typeInstance, BfMethodDef* checkMethod, bool isFailurePass)
  1194. {
  1195. BP_ZONE("BfMethodMatcher::CheckMethod");
  1196. BackupMatchKind curMatchKind = BackupMatchKind_None;
  1197. bool hadMatch = false;
  1198. // Never consider overrides - they only get found at original method declaration
  1199. // mBypassVirtual gets set when we are doing an explicit "base" call, or when we are a struct --
  1200. // because on structs we know the exact type
  1201. if ((checkMethod->mIsOverride) && (!mBypassVirtual) && (!typeInstance->IsValueType()))
  1202. return false;
  1203. mMethodCheckCount++;
  1204. BfMethodInstance* methodInstance = mModule->GetRawMethodInstance(typeInstance, checkMethod);
  1205. if (methodInstance == NULL)
  1206. {
  1207. BFMODULE_FATAL(mModule, "Failed to get raw method in BfMethodMatcher::CheckMethod");
  1208. return false;
  1209. }
  1210. if ((mInterfaceMethodInstance != NULL) && (methodInstance->GetExplicitInterface() != NULL))
  1211. {
  1212. BfTypeInstance* wantInterface = mInterfaceMethodInstance->mMethodInstanceGroup->mOwner;
  1213. if (wantInterface != methodInstance->GetExplicitInterface())
  1214. return false;
  1215. }
  1216. if ((checkMethod->mIsVirtual) && (!checkMethod->mIsOverride) && (!mBypassVirtual) &&
  1217. (targetTypeInstance != NULL) && (targetTypeInstance->IsObject()))
  1218. {
  1219. mModule->PopulateType(targetTypeInstance, BfPopulateType_DataAndMethods);
  1220. if ((methodInstance->mVirtualTableIdx < targetTypeInstance->mVirtualMethodTable.mSize) && (methodInstance->mVirtualTableIdx >= 0))
  1221. {
  1222. BfVirtualMethodEntry& vEntry = targetTypeInstance->mVirtualMethodTable[methodInstance->mVirtualTableIdx];
  1223. auto implMethod = (BfMethodInstance*)vEntry.mImplementingMethod;
  1224. if ((implMethod != methodInstance) && (implMethod != NULL))
  1225. {
  1226. SetAndRestoreValue<bool> prevBypassVirtual(mBypassVirtual, true);
  1227. return CheckMethod(targetTypeInstance, implMethod->GetOwner(), implMethod->mMethodDef, isFailurePass);
  1228. }
  1229. }
  1230. else
  1231. {
  1232. // Being in autocomplete mode is the only excuse for not having the virtual method table slotted
  1233. if ((!mModule->mCompiler->IsAutocomplete()) && (!targetTypeInstance->mTypeFailed))
  1234. {
  1235. mModule->AssertErrorState();
  1236. }
  1237. }
  1238. }
  1239. BfGenericInferContext genericInferContext;
  1240. genericInferContext.mModule = mModule;
  1241. genericInferContext.mCheckMethodGenericArguments = &mCheckMethodGenericArguments;
  1242. HashSet<int> allowEmptyGenericSet;
  1243. BfAutoComplete* autoComplete = NULL;
  1244. if ((mModule->mCompiler->mResolvePassData != NULL) && (!isFailurePass) && ((mBfEvalExprFlags & BfEvalExprFlags_NoAutoComplete) == 0))
  1245. autoComplete = mModule->mCompiler->mResolvePassData->mAutoComplete;
  1246. if (checkMethod->mMethodType != BfMethodType_Extension)
  1247. {
  1248. if (((checkMethod->mIsStatic) && (!mAllowStatic)) ||
  1249. ((!checkMethod->mIsStatic) && (!mAllowNonStatic)))
  1250. {
  1251. if (!typeInstance->IsFunction())
  1252. autoComplete = NULL;
  1253. }
  1254. }
  1255. if ((autoComplete != NULL) && (autoComplete->mIsCapturingMethodMatchInfo))
  1256. {
  1257. BfAutoComplete::MethodMatchEntry methodMatchEntry;
  1258. methodMatchEntry.mMethodDef = checkMethod;
  1259. methodMatchEntry.mTypeInstance = typeInstance;
  1260. methodMatchEntry.mCurMethodInstance = mModule->mCurMethodInstance;
  1261. autoComplete->mMethodMatchInfo->mInstanceList.push_back(methodMatchEntry);
  1262. }
  1263. BfTypeVector* genericArgumentsSubstitute = NULL;
  1264. int argIdx = 0;
  1265. int argMatchCount = 0;
  1266. bool needInferGenericParams = (checkMethod->mGenericParams.size() != 0) && (!mHadExplicitGenericArguments);
  1267. int paramIdx = 0;
  1268. BfType* paramsElementType = NULL;
  1269. if (checkMethod->mHasAppend)
  1270. paramIdx++;
  1271. // int outmostGenericCount = 0;
  1272. // if (checkMethod->mIsLocalMethod)
  1273. // outmostGenericCount = (int)mModule->mCurMethodState->GetRootMethodState()->mMethodInstance->mGenericParams.size();
  1274. int uniqueGenericStartIdx = mModule->GetLocalInferrableGenericArgCount(checkMethod);
  1275. if ((mHadExplicitGenericArguments) && (checkMethod->mGenericParams.size() != mExplicitMethodGenericArguments.size() + uniqueGenericStartIdx))
  1276. goto NoMatch;
  1277. for (auto& checkGenericArgRef : mCheckMethodGenericArguments)
  1278. checkGenericArgRef = NULL;
  1279. mCheckMethodGenericArguments.resize(checkMethod->mGenericParams.size());
  1280. //mPrevArgValues.resize(checkMethod->mGenericParams.size());
  1281. for (auto& genericArgRef : mCheckMethodGenericArguments)
  1282. genericArgRef = NULL;
  1283. if (mHadExplicitGenericArguments)
  1284. {
  1285. if (uniqueGenericStartIdx > 0)
  1286. {
  1287. genericArgumentsSubstitute = &mCheckMethodGenericArguments;
  1288. mCheckMethodGenericArguments.clear();
  1289. mCheckMethodGenericArguments.reserve(mExplicitMethodGenericArguments.size() + uniqueGenericStartIdx);
  1290. for (int i = 0; i < uniqueGenericStartIdx; i++)
  1291. mCheckMethodGenericArguments.Add(NULL);
  1292. for (int i = 0; i < (int)mExplicitMethodGenericArguments.size(); i++)
  1293. mCheckMethodGenericArguments.Add(mExplicitMethodGenericArguments[i]);
  1294. }
  1295. else
  1296. {
  1297. genericArgumentsSubstitute = &mExplicitMethodGenericArguments;
  1298. }
  1299. }
  1300. else if (needInferGenericParams)
  1301. genericArgumentsSubstitute = &mCheckMethodGenericArguments;
  1302. if ((checkMethod->mIsMutating) && (targetTypeInstance != NULL) && (targetTypeInstance->IsValueType()) &&
  1303. ((mTarget.IsReadOnly()) || (!mTarget.IsAddr())) &&
  1304. (!targetTypeInstance->IsValuelessType()))
  1305. {
  1306. goto NoMatch;
  1307. }
  1308. if (mSkipImplicitParams)
  1309. {
  1310. //paramOfs = methodInstance->GetImplicitParamCount();
  1311. //paramIdx += paramOfs;
  1312. }
  1313. if (needInferGenericParams)
  1314. {
  1315. genericInferContext.mPrevArgValues.resize(checkMethod->mGenericParams.size());
  1316. int paramOfs = methodInstance->GetImplicitParamCount();
  1317. int paramCount = methodInstance->GetParamCount();
  1318. SizedArray<int, 8> deferredArgs;
  1319. int argIdx = 0;
  1320. int paramIdx = 0;
  1321. if (checkMethod->mHasAppend)
  1322. paramIdx++;
  1323. if (checkMethod->mMethodType == BfMethodType_Extension)
  1324. {
  1325. argIdx--;
  1326. }
  1327. paramIdx += paramOfs;
  1328. bool hadInferFailure = false;
  1329. int inferParamOffset = paramOfs - argIdx;
  1330. enum ResultKind
  1331. {
  1332. ResultKind_Ok,
  1333. ResultKind_Failed,
  1334. ResultKind_Deferred,
  1335. };
  1336. auto _CheckArg = [&](int argIdx)
  1337. {
  1338. paramIdx = argIdx + inferParamOffset;
  1339. auto wantType = methodInstance->GetParamType(paramIdx);
  1340. auto checkType = wantType;
  1341. auto origCheckType = checkType;
  1342. if (checkType->IsGenericParam())
  1343. {
  1344. BfGenericParamInstance* genericParamInstance = NULL;
  1345. auto genericParamType = (BfGenericParamType*)checkType;
  1346. checkType = NULL;
  1347. if (genericParamType->mGenericParamKind == BfGenericParamKind_Method)
  1348. {
  1349. if ((genericArgumentsSubstitute != NULL) && (genericParamType->mGenericParamIdx < (int)genericArgumentsSubstitute->size()))
  1350. checkType = (*genericArgumentsSubstitute)[genericParamType->mGenericParamIdx];
  1351. genericParamInstance = methodInstance->mMethodInfoEx->mGenericParams[genericParamType->mGenericParamIdx];
  1352. }
  1353. else
  1354. genericParamInstance = mModule->GetGenericParamInstance(genericParamType);
  1355. if (checkType == NULL)
  1356. {
  1357. checkType = genericParamInstance->mTypeConstraint;
  1358. origCheckType = checkType; // We can do "ResolveGenericType" on this type
  1359. }
  1360. }
  1361. bool attemptedGenericResolve = false;
  1362. if ((checkType != NULL) && (genericArgumentsSubstitute != NULL) && (checkType->IsUnspecializedType()))
  1363. {
  1364. attemptedGenericResolve = true;
  1365. checkType = mModule->ResolveGenericType(origCheckType, NULL, genericArgumentsSubstitute);
  1366. }
  1367. if (wantType->IsUnspecializedType())
  1368. {
  1369. BfTypedValue argTypedValue;
  1370. if (argIdx == -1)
  1371. {
  1372. if (mOrigTarget)
  1373. argTypedValue = mOrigTarget;
  1374. else
  1375. argTypedValue = mTarget;
  1376. }
  1377. else
  1378. argTypedValue = ResolveArgTypedValue(mArguments[argIdx], checkType, genericArgumentsSubstitute, origCheckType);
  1379. if (!argTypedValue.IsUntypedValue())
  1380. {
  1381. auto type = argTypedValue.mType;
  1382. if (!argTypedValue)
  1383. {
  1384. if ((checkType == NULL) && (attemptedGenericResolve) && (genericInferContext.GetUnresolvedCount() >= 2))
  1385. {
  1386. deferredArgs.Add(argIdx);
  1387. return ResultKind_Deferred;
  1388. }
  1389. return ResultKind_Failed;
  1390. }
  1391. if (type->IsVar())
  1392. mHasVarArguments = true;
  1393. genericInferContext.mCheckedTypeSet.Clear();
  1394. if (!genericInferContext.InferGenericArgument(methodInstance, type, wantType, argTypedValue.mValue))
  1395. return ResultKind_Failed;
  1396. }
  1397. }
  1398. return ResultKind_Ok;
  1399. };
  1400. for (; argIdx < (int)mArguments.size(); argIdx++)
  1401. {
  1402. paramIdx = argIdx + inferParamOffset;
  1403. if (paramIdx >= paramCount)
  1404. break; // Possible for delegate 'params' type methods
  1405. auto resultKind = _CheckArg(argIdx);
  1406. if (resultKind == ResultKind_Failed)
  1407. goto NoMatch;
  1408. }
  1409. while (!deferredArgs.IsEmpty())
  1410. {
  1411. int prevDeferredSize = (int)deferredArgs.size();
  1412. for (int i = 0; i < prevDeferredSize; i++)
  1413. {
  1414. auto resultKind = _CheckArg(deferredArgs[i]);
  1415. if (resultKind == ResultKind_Failed)
  1416. goto NoMatch;
  1417. }
  1418. deferredArgs.RemoveRange(0, prevDeferredSize);
  1419. if (prevDeferredSize == deferredArgs.size())
  1420. {
  1421. // No progress
  1422. goto NoMatch;
  1423. }
  1424. }
  1425. //
  1426. {
  1427. int paramIdx = (int)mArguments.size() + paramOfs;
  1428. while (paramIdx < checkMethod->mParams.size())
  1429. {
  1430. if ((paramIdx < methodInstance->mDefaultValues.size()) && (methodInstance->mDefaultValues[paramIdx]))
  1431. {
  1432. auto wantType = methodInstance->GetParamType(paramIdx);
  1433. auto checkType = wantType;
  1434. if (checkType->IsGenericParam())
  1435. {
  1436. BfGenericParamInstance* genericParamInstance = NULL;
  1437. auto genericParamType = (BfGenericParamType*)checkType;
  1438. if (genericParamType->mGenericParamKind == BfGenericParamKind_Method)
  1439. {
  1440. if ((genericArgumentsSubstitute != NULL) && (genericParamType->mGenericParamIdx < (int)genericArgumentsSubstitute->size()))
  1441. checkType = (*genericArgumentsSubstitute)[genericParamType->mGenericParamIdx];
  1442. genericParamInstance = methodInstance->mMethodInfoEx->mGenericParams[genericParamType->mGenericParamIdx];
  1443. if ((genericParamInstance->mGenericParamFlags & BfGenericParamFlag_Const) != 0)
  1444. {
  1445. if (mCheckMethodGenericArguments[genericParamType->mGenericParamIdx] == NULL)
  1446. allowEmptyGenericSet.Add(genericParamType->mGenericParamIdx);
  1447. }
  1448. }
  1449. }
  1450. }
  1451. paramIdx++;
  1452. }
  1453. }
  1454. //
  1455. for (int genericArgIdx = uniqueGenericStartIdx; genericArgIdx < (int)checkMethod->mGenericParams.size(); genericArgIdx++)
  1456. {
  1457. auto& genericArg = mCheckMethodGenericArguments[genericArgIdx];
  1458. if (genericArg == NULL)
  1459. {
  1460. auto genericParam = methodInstance->mMethodInfoEx->mGenericParams[genericArgIdx];
  1461. InferFromGenericConstraints(genericParam, &mCheckMethodGenericArguments);
  1462. if (genericArg != NULL)
  1463. continue;
  1464. if (!allowEmptyGenericSet.Contains(genericArgIdx))
  1465. goto NoMatch;
  1466. }
  1467. }
  1468. }
  1469. if (checkMethod->mMethodType == BfMethodType_Extension)
  1470. argIdx--;
  1471. // Iterate through params
  1472. while (true)
  1473. {
  1474. // Too many arguments
  1475. if (paramIdx >= (int)methodInstance->GetParamCount())
  1476. {
  1477. break;
  1478. }
  1479. bool isDeferredEval = false;
  1480. if ((argIdx >= 0) && (methodInstance->GetParamKind(paramIdx) == BfParamKind_Params) && (paramsElementType == NULL))
  1481. {
  1482. if (paramIdx >= (int) mArguments.size())
  1483. break; // No params
  1484. BfTypedValue argTypedValue = ResolveArgTypedValue(mArguments[argIdx], NULL, genericArgumentsSubstitute);
  1485. if (!argTypedValue)
  1486. goto NoMatch;
  1487. if ((!argTypedValue.HasType()) && (!mArguments[argIdx].IsDeferredEval()))
  1488. goto NoMatch;
  1489. auto paramsArrayType = methodInstance->GetParamType(paramIdx);
  1490. if ((mArguments[argIdx].mArgFlags & BfArgFlag_ParamsExpr) != 0)
  1491. {
  1492. // Direct-pass params
  1493. if ((argTypedValue.IsUntypedValue()) || (mModule->CanCast(argTypedValue, paramsArrayType)))
  1494. {
  1495. argIdx++;
  1496. argMatchCount++;
  1497. paramIdx++;
  1498. break;
  1499. }
  1500. goto NoMatch;
  1501. }
  1502. if ((paramsArrayType->IsArray()) || (paramsArrayType->IsInstanceOf(mModule->mCompiler->mSpanTypeDef)))
  1503. {
  1504. paramsElementType = paramsArrayType->GetUnderlyingType();
  1505. while (argIdx < (int)mArguments.size())
  1506. {
  1507. argTypedValue = ResolveArgTypedValue(mArguments[argIdx], paramsElementType, genericArgumentsSubstitute);
  1508. if (!argTypedValue.HasType())
  1509. goto NoMatch;
  1510. if (!mModule->CanCast(argTypedValue, paramsElementType))
  1511. goto NoMatch;
  1512. argIdx++;
  1513. argMatchCount++;
  1514. }
  1515. }
  1516. else
  1517. goto NoMatch;
  1518. break;
  1519. }
  1520. if (methodInstance->IsImplicitCapture(paramIdx))
  1521. {
  1522. paramIdx++;
  1523. continue;
  1524. }
  1525. if (argIdx >= (int) mArguments.size())
  1526. {
  1527. // We have defaults the rest of the way, so that's cool
  1528. if (methodInstance->GetParamInitializer(paramIdx) != NULL)
  1529. break;
  1530. // We have unused params left over
  1531. goto NoMatch;
  1532. }
  1533. auto wantType = methodInstance->GetParamType(paramIdx);
  1534. if ((genericArgumentsSubstitute != NULL) && (wantType->IsUnspecializedType()))
  1535. {
  1536. auto resolvedType = mModule->ResolveGenericType(wantType, NULL, genericArgumentsSubstitute, false);
  1537. if (resolvedType == NULL)
  1538. goto NoMatch;
  1539. wantType = resolvedType;
  1540. }
  1541. if (wantType->IsSelf())
  1542. wantType = typeInstance;
  1543. if ((argIdx >= 0) && ((mArguments[argIdx].mArgFlags & BfArgFlag_ParamsExpr) != 0))
  1544. {
  1545. // We had a 'params' expression but this method didn't have a params slot in this parameter
  1546. goto NoMatch;
  1547. }
  1548. BfTypedValue argTypedValue;
  1549. if (argIdx == -1)
  1550. argTypedValue = mTarget;
  1551. else
  1552. argTypedValue = ResolveArgTypedValue(mArguments[argIdx], wantType, genericArgumentsSubstitute);
  1553. if (!argTypedValue.IsUntypedValue())
  1554. {
  1555. if (!argTypedValue.HasType())
  1556. {
  1557. // Check to see if this is the last argument and that it's a potential enum match
  1558. if ((wantType->IsEnum()) && (argIdx == mArguments.size() - 1))
  1559. {
  1560. if (auto memberRefExpr = BfNodeDynCast<BfMemberReferenceExpression>(mArguments[argIdx].mExpression))
  1561. {
  1562. if (memberRefExpr->mTarget == NULL)
  1563. {
  1564. // Is dot expression
  1565. curMatchKind = BackupMatchKind_PartialLastArgMatch;
  1566. }
  1567. }
  1568. }
  1569. goto NoMatch;
  1570. }
  1571. else if (!mModule->CanCast(argTypedValue, wantType))
  1572. goto NoMatch;
  1573. }
  1574. paramIdx++;
  1575. argIdx++;
  1576. argMatchCount++;
  1577. if ((autoComplete != NULL) && (autoComplete->mIsCapturingMethodMatchInfo))
  1578. {
  1579. auto methodMatchInfo = autoComplete->mMethodMatchInfo;
  1580. if (!methodMatchInfo->mHadExactMatch)
  1581. {
  1582. bool isBetter = false;
  1583. bool isWorse = false;
  1584. int methodIdx = (int)methodMatchInfo->mInstanceList.size() - 1;
  1585. if ((methodMatchInfo->mBestIdx != -1) && (methodMatchInfo->mBestIdx < (int)methodMatchInfo->mInstanceList.size()))
  1586. {
  1587. auto prevMethodMatchEntry = &methodMatchInfo->mInstanceList[methodMatchInfo->mBestIdx];
  1588. if (checkMethod->mParams.size() < mArguments.size())
  1589. {
  1590. isWorse = true;
  1591. }
  1592. else if ((prevMethodMatchEntry->mMethodDef != NULL) && (prevMethodMatchEntry->mMethodDef->mParams.size() < (int) mArguments.size()))
  1593. {
  1594. isBetter = true;
  1595. }
  1596. }
  1597. }
  1598. }
  1599. }
  1600. // Too many arguments (not all incoming arguments processed)
  1601. if (argIdx < (int)mArguments.size())
  1602. {
  1603. if (!methodInstance->IsVarArgs())
  1604. goto NoMatch;
  1605. }
  1606. if ((genericArgumentsSubstitute != NULL) && (genericArgumentsSubstitute->size() != 0))
  1607. {
  1608. for (int checkGenericIdx = uniqueGenericStartIdx; checkGenericIdx < (int)genericArgumentsSubstitute->size(); checkGenericIdx++)
  1609. {
  1610. auto& genericParams = methodInstance->mMethodInfoEx->mGenericParams;
  1611. auto genericArg = (*genericArgumentsSubstitute)[checkGenericIdx];
  1612. if (genericArg == NULL)
  1613. {
  1614. if (allowEmptyGenericSet.Contains(checkGenericIdx))
  1615. continue;
  1616. goto NoMatch;
  1617. }
  1618. if (genericArg == NULL)
  1619. goto NoMatch;
  1620. if (!mModule->CheckGenericConstraints(BfGenericParamSource(methodInstance), genericArg, NULL, genericParams[checkGenericIdx], genericArgumentsSubstitute, NULL))
  1621. goto NoMatch;
  1622. }
  1623. }
  1624. // Method is applicable, check to see which method is better
  1625. if (mBestMethodDef != NULL)
  1626. {
  1627. bool isBetter = false;
  1628. bool isWorse = false;
  1629. BfMethodInstance* prevMethodInstance = mModule->GetRawMethodInstance(mBestMethodTypeInstance, mBestMethodDef);
  1630. bool allowSpecializeFail = mModule->mCurTypeInstance->IsUnspecializedType();
  1631. if (mModule->mCurMethodInstance != NULL)
  1632. allowSpecializeFail = mModule->mCurMethodInstance->mIsUnspecialized;
  1633. // if (mModule->mModuleName == "BeefTest_TestProgram")
  1634. // {
  1635. // OutputDebugStrF("?Prv: %s\n %s\n?New: %s\n %s\n\n",
  1636. // mModule->MethodToString(prevMethodInstance, BfMethodNameFlag_None, &mBestMethodGenericArguments).c_str(),
  1637. // mModule->MethodToString(prevMethodInstance, BfMethodNameFlag_None).c_str(),
  1638. // mModule->MethodToString(methodInstance, BfMethodNameFlag_None, genericArgumentsSubstitute).c_str(),
  1639. // mModule->MethodToString(methodInstance, BfMethodNameFlag_None).c_str());
  1640. // }
  1641. CompareMethods(prevMethodInstance, &mBestMethodGenericArguments, methodInstance, genericArgumentsSubstitute, &isBetter, &isWorse, allowSpecializeFail);
  1642. // if (mModule->mModuleName == "BeefTest_TestProgram")
  1643. // {
  1644. // OutputDebugStrF("%sPrv: %s\n %s\n%sNew: %s\n %s\n\n",
  1645. // isWorse ? "*" : " ", mModule->MethodToString(prevMethodInstance, BfMethodNameFlag_None, &mBestMethodGenericArguments).c_str(),
  1646. // mModule->MethodToString(prevMethodInstance, BfMethodNameFlag_None).c_str(),
  1647. // isBetter ? "*" : " ", mModule->MethodToString(methodInstance, BfMethodNameFlag_None, genericArgumentsSubstitute).c_str(),
  1648. // mModule->MethodToString(methodInstance, BfMethodNameFlag_None).c_str());
  1649. // }
  1650. // If we had both a 'better' and 'worse', that's ambiguous because the methods are each better in different ways (not allowed)
  1651. // And if neither better nor worse then they are equally good, which is not allowed either
  1652. if (((!isBetter) && (!isWorse)) || ((isBetter) && (isWorse)))
  1653. {
  1654. if (mHasVarArguments)
  1655. {
  1656. if (prevMethodInstance->mReturnType != prevMethodInstance->mReturnType)
  1657. mHadVarConflictingReturnType = true;
  1658. }
  1659. else
  1660. {
  1661. BfAmbiguousEntry ambiguousEntry;
  1662. ambiguousEntry.mMethodInstance = methodInstance;
  1663. if (genericArgumentsSubstitute != NULL)
  1664. ambiguousEntry.mBestMethodGenericArguments = *genericArgumentsSubstitute;
  1665. if (methodInstance->GetNumGenericParams() != 0)
  1666. {
  1667. BF_ASSERT(!ambiguousEntry.mBestMethodGenericArguments.empty());
  1668. }
  1669. mAmbiguousEntries.push_back(ambiguousEntry);
  1670. goto Done;
  1671. }
  1672. }
  1673. if (!isBetter)
  1674. goto Done;
  1675. }
  1676. if ((autoComplete != NULL) && (autoComplete->mIsCapturingMethodMatchInfo))
  1677. {
  1678. auto methodMatchInfo = autoComplete->mMethodMatchInfo;
  1679. // Try to persist with previous partial match, if we have one - this keeps us from locking onto
  1680. // an incorrect method just because it had the current number of params that we've typed so far
  1681. if (methodMatchInfo->mPrevBestIdx == -1)
  1682. {
  1683. methodMatchInfo->mHadExactMatch = true;
  1684. methodMatchInfo->mBestIdx = (int) methodMatchInfo->mInstanceList.size() - 1;
  1685. }
  1686. }
  1687. mAmbiguousEntries.Clear();
  1688. hadMatch = true;
  1689. mBestMethodDef = checkMethod;
  1690. mBestRawMethodInstance = methodInstance;
  1691. for (auto& arg : mArguments)
  1692. arg.mBestBoundType = arg.mTypedValue.mType;
  1693. NoMatch:
  1694. if (!hadMatch)
  1695. {
  1696. if (mBestMethodDef != NULL)
  1697. return false;
  1698. if (mBackupMethodDef != NULL)
  1699. {
  1700. int prevParamDiff = (int)mBackupMethodDef->GetExplicitParamCount() - (int)mArguments.size();
  1701. int paramDiff = (int)checkMethod->GetExplicitParamCount() - (int)mArguments.size();
  1702. if ((prevParamDiff < 0) && (prevParamDiff > paramDiff))
  1703. return false;
  1704. if ((prevParamDiff >= 0) && (paramDiff < 0))
  1705. return false;
  1706. if (argMatchCount < mBackupArgMatchCount)
  1707. return false;
  1708. else if (argMatchCount == mBackupArgMatchCount)
  1709. {
  1710. if (curMatchKind < mBackupMatchKind)
  1711. return false;
  1712. // We search from the most specific type, so don't prefer a less specific type
  1713. if (mBestMethodTypeInstance != typeInstance)
  1714. return false;
  1715. }
  1716. }
  1717. if ((autoComplete != NULL) && (autoComplete->mIsCapturingMethodMatchInfo))
  1718. {
  1719. auto methodMatchInfo = autoComplete->mMethodMatchInfo;
  1720. if ((methodMatchInfo->mPrevBestIdx == -1) && (!methodMatchInfo->mHadExactMatch))
  1721. {
  1722. methodMatchInfo->mBestIdx = (int)methodMatchInfo->mInstanceList.size() - 1;
  1723. }
  1724. }
  1725. mBackupMatchKind = curMatchKind;
  1726. mBackupMethodDef = checkMethod;
  1727. mBackupArgMatchCount = argMatchCount;
  1728. // Lie temporarily to store at least one candidate (but mBestMethodDef is still NULL)
  1729. hadMatch = true;
  1730. }
  1731. if (hadMatch)
  1732. {
  1733. mBestMethodTypeInstance = typeInstance;
  1734. if (genericArgumentsSubstitute != &mBestMethodGenericArguments)
  1735. {
  1736. if (genericArgumentsSubstitute != NULL)
  1737. {
  1738. for (auto& genericArg : *genericArgumentsSubstitute)
  1739. genericArg = mModule->FixIntUnknown(genericArg);
  1740. mBestMethodGenericArguments = *genericArgumentsSubstitute;
  1741. // #ifdef _DEBUG
  1742. // for (auto arg : mBestMethodGenericArguments)
  1743. // BF_ASSERT((arg == NULL) || (!arg->IsVar()));
  1744. // #endif
  1745. }
  1746. else
  1747. mBestMethodGenericArguments.clear();
  1748. }
  1749. }
  1750. Done:
  1751. if ((autoComplete != NULL) && (autoComplete->mIsCapturingMethodMatchInfo) && (genericArgumentsSubstitute != NULL))
  1752. {
  1753. auto methodMatchInfo = autoComplete->mMethodMatchInfo;
  1754. if (!methodMatchInfo->mInstanceList.IsEmpty())
  1755. {
  1756. methodMatchInfo->mInstanceList[methodMatchInfo->mInstanceList.size() - 1].mGenericArguments = *genericArgumentsSubstitute;
  1757. }
  1758. }
  1759. return mBestMethodDef == checkMethod;
  1760. }
  1761. void BfMethodMatcher::FlushAmbiguityError()
  1762. {
  1763. if (!mAmbiguousEntries.empty())
  1764. {
  1765. BfError* error;
  1766. if (!mMethodName.empty())
  1767. error = mModule->Fail(StrFormat("Ambiguous method call for '%s'", mMethodName.c_str()), mTargetSrc);
  1768. else
  1769. error = mModule->Fail("Ambiguous method call", mTargetSrc);
  1770. if (error != NULL)
  1771. {
  1772. BfMethodInstance* bestMethodInstance = mModule->GetRawMethodInstance(mBestMethodTypeInstance, mBestMethodDef);
  1773. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("'%s' is a candidate", mModule->MethodToString(bestMethodInstance, BfMethodNameFlag_ResolveGenericParamNames,
  1774. mBestMethodGenericArguments.empty() ? NULL : &mBestMethodGenericArguments).c_str()),
  1775. bestMethodInstance->mMethodDef->GetRefNode());
  1776. for (auto& ambiguousEntry : mAmbiguousEntries)
  1777. {
  1778. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("'%s' is a candidate", mModule->MethodToString(ambiguousEntry.mMethodInstance, BfMethodNameFlag_ResolveGenericParamNames,
  1779. ambiguousEntry.mBestMethodGenericArguments.empty() ? NULL : &ambiguousEntry.mBestMethodGenericArguments).c_str()),
  1780. ambiguousEntry.mMethodInstance->mMethodDef->GetRefNode());
  1781. }
  1782. }
  1783. mAmbiguousEntries.Clear();
  1784. }
  1785. }
  1786. bool BfMethodMatcher::IsType(BfTypedValue& typedVal, BfType* type)
  1787. {
  1788. if (typedVal.mType == type)
  1789. return true;
  1790. if (!typedVal)
  1791. return false;
  1792. if (!typedVal.mType->IsPrimitiveType())
  1793. return false;
  1794. if (!type->IsPrimitiveType())
  1795. return false;
  1796. auto fromPrimType = typedVal.mType->ToPrimitiveType();
  1797. if ((fromPrimType->mTypeDef->mTypeCode != BfTypeCode_IntUnknown) &&
  1798. (fromPrimType->mTypeDef->mTypeCode != BfTypeCode_UIntUnknown))
  1799. return false;
  1800. auto constant = mModule->mBfIRBuilder->GetConstant(typedVal.mValue);
  1801. if (constant == NULL)
  1802. return false;
  1803. auto toPrimType = type->ToPrimitiveType();
  1804. if (!mModule->mBfIRBuilder->IsInt(toPrimType->mTypeDef->mTypeCode))
  1805. return false;
  1806. if (type->mSize == 8)
  1807. return false;
  1808. int64 minVal = -(1LL << (8 * type->mSize - 1));
  1809. int64 maxVal = (1LL << (8 * type->mSize - 1)) - 1;
  1810. if ((constant->mInt64 >= minVal) && (constant->mInt64 <= maxVal))
  1811. return true;
  1812. return false;
  1813. }
  1814. // This method checks all base classes before checking interfaces. Is that correct?
  1815. bool BfMethodMatcher::CheckType(BfTypeInstance* typeInstance, BfTypedValue target, bool isFailurePass, bool forceOuterCheck)
  1816. {
  1817. BfMethodDef* prevBesstMethodDef = mBestMethodDef;
  1818. auto curTypeInst = typeInstance;
  1819. auto curTypeDef = typeInstance->mTypeDef;
  1820. int checkInterfaceIdx = 0;
  1821. bool targetIsBase = target.IsBase();
  1822. bool checkExtensionBase = false;
  1823. if (targetIsBase)
  1824. {
  1825. if ((curTypeInst == mModule->mCurTypeInstance) && (curTypeInst->mTypeDef->mIsCombinedPartial))
  1826. {
  1827. checkExtensionBase = true;
  1828. }
  1829. else
  1830. {
  1831. curTypeInst = curTypeInst->mBaseType;
  1832. }
  1833. }
  1834. BfTypeInstance* targetTypeInstance = NULL;
  1835. if (target.mType != NULL)
  1836. targetTypeInstance = target.mType->ToTypeInstance();
  1837. while (true)
  1838. {
  1839. bool doSearch = true;
  1840. if ((mMethodType == BfMethodType_Extension) && (!curTypeDef->mHasExtensionMethods))
  1841. doSearch = false;
  1842. BfMethodDef* nextMethodDef = NULL;
  1843. if (doSearch)
  1844. {
  1845. curTypeDef->PopulateMemberSets();
  1846. BfMemberSetEntry* entry;
  1847. if (curTypeDef->mMethodSet.TryGetWith(mMethodName, &entry))
  1848. nextMethodDef = (BfMethodDef*)entry->mMemberDef;
  1849. }
  1850. BfProtectionCheckFlags protectionCheckFlags = BfProtectionCheckFlag_None;
  1851. if (target)
  1852. {
  1853. if (mBypassVirtual)
  1854. {
  1855. // Not an "instance lookup"
  1856. }
  1857. else
  1858. {
  1859. protectionCheckFlags = (BfProtectionCheckFlags)(protectionCheckFlags | BfProtectionCheckFlag_InstanceLookup);
  1860. }
  1861. }
  1862. while (nextMethodDef != NULL)
  1863. {
  1864. bool allowExplicitInterface = curTypeInst->IsInterface() && mBypassVirtual;
  1865. auto activeTypeDef = mModule->GetActiveTypeDef();
  1866. auto visibleProjectSet = mModule->GetVisibleProjectSet();
  1867. bool isDelegate = typeInstance->IsDelegate();
  1868. auto checkMethod = nextMethodDef;
  1869. nextMethodDef = nextMethodDef->mNextWithSameName;
  1870. if (mModule->mContext->mResolvingVarField)
  1871. {
  1872. bool isResolvingVarField = false;
  1873. auto checkTypeState = mModule->mContext->mCurTypeState;
  1874. while (checkTypeState != NULL)
  1875. {
  1876. if ((checkTypeState->mResolveKind == BfTypeState::ResolveKind_ResolvingVarType) &&
  1877. (checkTypeState->mTypeInstance == typeInstance))
  1878. isResolvingVarField = true;
  1879. checkTypeState = checkTypeState->mPrevState;
  1880. }
  1881. if (isResolvingVarField)
  1882. {
  1883. // Don't even consider - we can't do method calls on ourselves when we are resolving var fields, because
  1884. // we are not allowed to generate methods when our field types are unknown. We may fix this in the future,
  1885. // but currently it breaks out expected order of operations. One issue is that our call signatures change
  1886. // depending on whether we are valueless or splattable, which depend on underlying type information
  1887. break;
  1888. }
  1889. }
  1890. if ((checkExtensionBase) && (curTypeInst == mModule->mCurTypeInstance))
  1891. {
  1892. // Accept either a method in the same project but that's the root definition, OR a method that's in a dependent project
  1893. bool accept = false;
  1894. if (activeTypeDef->mProject == checkMethod->mDeclaringType->mProject)
  1895. accept = (activeTypeDef->IsExtension()) && (!checkMethod->mDeclaringType->IsExtension());
  1896. else
  1897. accept = activeTypeDef->mProject->ContainsReference(checkMethod->mDeclaringType->mProject);
  1898. if (!accept)
  1899. continue;
  1900. }
  1901. if ((!allowExplicitInterface) && (checkMethod->mExplicitInterface != NULL) && (mInterfaceMethodInstance == NULL))
  1902. {
  1903. continue;
  1904. }
  1905. if (checkMethod->mMethodType != mMethodType)
  1906. continue;
  1907. // if (checkMethod->mName != mMethodName)
  1908. // continue;
  1909. if ((checkMethod->mDeclaringType->IsExtension()) && (mModule->mAttributeState != NULL) && (mModule->mAttributeState->mCustomAttributes != NULL) &&
  1910. (mModule->mAttributeState->mCustomAttributes->Contains(mModule->mCompiler->mNoExtensionAttributeTypeDef)))
  1911. {
  1912. mModule->mAttributeState->mUsed = true;
  1913. continue;
  1914. }
  1915. if (!isDelegate)
  1916. {
  1917. if ((!curTypeInst->IsTypeMemberIncluded(checkMethod->mDeclaringType, activeTypeDef, mModule)) ||
  1918. (!curTypeInst->IsTypeMemberAccessible(checkMethod->mDeclaringType, visibleProjectSet)))
  1919. continue;
  1920. }
  1921. MatchFailKind matchFailKind = MatchFailKind_None;
  1922. if (!mModule->CheckProtection(protectionCheckFlags, curTypeInst, checkMethod->mDeclaringType->mProject, checkMethod->mProtection, typeInstance))
  1923. {
  1924. if ((mBypassVirtual) &&
  1925. ((checkMethod->mProtection == BfProtection_Protected) || (checkMethod->mProtection == BfProtection_ProtectedInternal)) &&
  1926. (mModule->TypeIsSubTypeOf(mModule->mCurTypeInstance, typeInstance)))
  1927. {
  1928. // Allow explicit 'base' call
  1929. }
  1930. else
  1931. {
  1932. if (!isFailurePass)
  1933. continue;
  1934. matchFailKind = MatchFailKind_Protection;
  1935. }
  1936. }
  1937. if (mCheckedKind != checkMethod->mCheckedKind)
  1938. {
  1939. bool passes = true;
  1940. if (mCheckedKind != BfCheckedKind_NotSet)
  1941. {
  1942. passes = false;
  1943. }
  1944. else
  1945. {
  1946. auto defaultCheckedKind = mModule->GetDefaultCheckedKind();
  1947. if (defaultCheckedKind != checkMethod->mCheckedKind)
  1948. passes = false;
  1949. }
  1950. if (!passes)
  1951. {
  1952. if (!isFailurePass)
  1953. continue;
  1954. matchFailKind = MatchFailKind_CheckedMismatch;
  1955. }
  1956. }
  1957. CheckMethod(targetTypeInstance, curTypeInst, checkMethod, isFailurePass);
  1958. if ((isFailurePass) &&
  1959. ((mBestMethodDef == checkMethod) || (mBackupMethodDef == checkMethod)))
  1960. mMatchFailKind = matchFailKind;
  1961. }
  1962. if ((mBestMethodDef != NULL) && (mMethodType != BfMethodType_Extension))
  1963. {
  1964. if (mAutoFlushAmbiguityErrors)
  1965. FlushAmbiguityError();
  1966. return true;
  1967. }
  1968. auto baseType = curTypeInst->mBaseType;
  1969. if (baseType == NULL)
  1970. {
  1971. //TODO: Why were we doing the interface checking?
  1972. if ((curTypeInst->IsInterface()) && (curTypeInst == target.mType))
  1973. {
  1974. // When we are directly calling on interfaces rather than indirectly matching through binding
  1975. baseType = mModule->mContext->mBfObjectType;
  1976. }
  1977. else if ((curTypeInst != mModule->mContext->mBfObjectType) && (!curTypeInst->IsInterface()))
  1978. {
  1979. // This can happen for structs
  1980. baseType = mModule->mContext->mBfObjectType;
  1981. }
  1982. else if ((typeInstance->IsInterface()) && (checkInterfaceIdx < (int)typeInstance->mInterfaces.size()))
  1983. {
  1984. baseType = typeInstance->mInterfaces[checkInterfaceIdx].mInterfaceType;
  1985. checkInterfaceIdx++;
  1986. }
  1987. else
  1988. {
  1989. break;
  1990. }
  1991. }
  1992. curTypeDef = baseType->mTypeDef;
  1993. curTypeInst = baseType;
  1994. if ((isFailurePass) && (mBackupMethodDef != NULL))
  1995. break;
  1996. }
  1997. if (mBestMethodDef == NULL)
  1998. {
  1999. // FAILED, but select the first method which will fire an actual error on param type matching
  2000. mBestMethodDef = mBackupMethodDef;
  2001. }
  2002. if (((mBestMethodDef == NULL) && (!target) && (mAllowImplicitThis)) ||
  2003. (forceOuterCheck))
  2004. {
  2005. // No explicit target - maybe this was a static call in the outer type?
  2006. auto outerType = mModule->GetOuterType(typeInstance);
  2007. if (outerType != NULL)
  2008. CheckOuterTypeStaticMethods(outerType, isFailurePass);
  2009. }
  2010. if (mAutoFlushAmbiguityErrors)
  2011. FlushAmbiguityError();
  2012. return mBestMethodDef != prevBesstMethodDef;
  2013. }
  2014. void BfMethodMatcher::TryDevirtualizeCall(BfTypedValue target, BfTypedValue* origTarget, BfTypedValue* staticResult)
  2015. {
  2016. if ((mBestMethodDef == NULL) || (target.mType == NULL))
  2017. return;
  2018. if ((mModule->mCompiler->IsAutocomplete()) || (mModule->mContext->mResolvingVarField))
  2019. return;
  2020. if (mModule->mBfIRBuilder->mIgnoreWrites)
  2021. return;
  2022. if (mBestMethodTypeInstance->IsInterface())
  2023. {
  2024. mModule->PopulateType(mBestMethodTypeInstance, BfPopulateType_DataAndMethods);
  2025. auto activeTypeDef = mModule->GetActiveTypeDef();
  2026. // Statically map this call
  2027. auto checkType = target.mType;
  2028. if (checkType->IsPointer())
  2029. checkType = ((BfPointerType*)checkType)->mElementType;
  2030. if (checkType->IsWrappableType())
  2031. checkType = mModule->GetWrappedStructType(checkType);
  2032. if ((checkType != NULL) && (checkType->IsTypeInstance()) && (!checkType->IsInterface()))
  2033. {
  2034. BfTypeInterfaceEntry* bestIFaceEntry = NULL;
  2035. auto checkTypeInst = checkType->ToTypeInstance();
  2036. if (mBestMethodTypeInstance->mTypeDef == mModule->mCompiler->mIHashableTypeDef)
  2037. {
  2038. if ((origTarget != NULL) && (origTarget->mType->IsPointer()) && (staticResult != NULL))
  2039. {
  2040. BfTypedValue ptrVal = mModule->LoadValue(*origTarget);
  2041. *staticResult = BfTypedValue(mModule->mBfIRBuilder->CreatePtrToInt(ptrVal.mValue, BfTypeCode_IntPtr), mModule->GetPrimitiveType(BfTypeCode_IntPtr));
  2042. return;
  2043. }
  2044. }
  2045. while (checkTypeInst != NULL)
  2046. {
  2047. mModule->PopulateType(checkTypeInst, BfPopulateType_DataAndMethods);
  2048. for (auto&& iface : checkTypeInst->mInterfaces)
  2049. {
  2050. //TODO: Why did we have this check? This caused Dictionary to not be able to devirtualize
  2051. // calls to TKey GetHashCode when TKey was from a user's project...
  2052. /*if (!checkTypeInst->IsTypeMemberAccessible(iface.mDeclaringType, activeTypeDef))
  2053. continue;*/
  2054. if (iface.mInterfaceType == mBestMethodTypeInstance)
  2055. {
  2056. if (bestIFaceEntry == NULL)
  2057. {
  2058. bestIFaceEntry = &iface;
  2059. continue;
  2060. }
  2061. bool isBetter;
  2062. bool isWorse;
  2063. mModule->CompareDeclTypes(iface.mDeclaringType, bestIFaceEntry->mDeclaringType, isBetter, isWorse);
  2064. if (isBetter == isWorse)
  2065. {
  2066. // Failed
  2067. }
  2068. else
  2069. {
  2070. if (isBetter)
  2071. bestIFaceEntry = &iface;
  2072. }
  2073. }
  2074. }
  2075. if (bestIFaceEntry != NULL)
  2076. break;
  2077. checkTypeInst = checkTypeInst->mBaseType;
  2078. if ((checkTypeInst == NULL) && (checkType->HasWrappedRepresentation()))
  2079. {
  2080. auto underlyingType = checkType->GetUnderlyingType();
  2081. if ((underlyingType != NULL) && (underlyingType->IsWrappableType()))
  2082. checkTypeInst = mModule->GetWrappedStructType(underlyingType);
  2083. }
  2084. }
  2085. if (bestIFaceEntry != NULL)
  2086. {
  2087. auto ifaceMethodEntry = checkTypeInst->mInterfaceMethodTable[bestIFaceEntry->mStartInterfaceTableIdx + mBestMethodDef->mIdx];
  2088. BfMethodInstance* bestMethodInstance = ifaceMethodEntry.mMethodRef;
  2089. if (bestMethodInstance != NULL)
  2090. {
  2091. bool isMissingArg = false;
  2092. for (auto genericArg : mBestMethodGenericArguments)
  2093. {
  2094. if (genericArg == NULL)
  2095. isMissingArg = true;
  2096. }
  2097. if (!isMissingArg)
  2098. {
  2099. // Assert error state?
  2100. mBestMethodTypeInstance = ifaceMethodEntry.mMethodRef.mTypeInstance;
  2101. mBestMethodDef = bestMethodInstance->mMethodDef;
  2102. mBestMethodInstance = mModule->GetMethodInstance(mBestMethodTypeInstance, bestMethodInstance->mMethodDef, mBestMethodGenericArguments,
  2103. bestMethodInstance->mIsForeignMethodDef ? BfGetMethodInstanceFlag_ForeignMethodDef : BfGetMethodInstanceFlag_None,
  2104. bestMethodInstance->GetForeignType());
  2105. }
  2106. }
  2107. else
  2108. {
  2109. // Failed
  2110. mFakeConcreteTarget = true;
  2111. }
  2112. }
  2113. }
  2114. }
  2115. if ((target.mType->IsValueType()) && (mBestMethodTypeInstance->IsObject()) && (mBestMethodDef->mIsVirtual))
  2116. {
  2117. auto structType = target.mType->ToTypeInstance();
  2118. auto virtualMethodInstance = mModule->GetMethodInstance(mBestMethodTypeInstance, mBestMethodDef, BfTypeVector());
  2119. BF_ASSERT(virtualMethodInstance.mMethodInstance->mVirtualTableIdx != -1);
  2120. BfTypeInstance* boxedType;
  2121. if (structType->HasOverrideMethods())
  2122. {
  2123. // We don't actually need this boxed type, so just resolve it unreified
  2124. auto useModule = mModule->mContext->mUnreifiedModule;
  2125. boxedType = useModule->CreateBoxedType(target.mType);
  2126. useModule->PopulateType(boxedType, BfPopulateType_DataAndMethods);
  2127. useModule->AddDependency(boxedType, mModule->mCurTypeInstance, BfDependencyMap::DependencyFlag_WeakReference);
  2128. }
  2129. else
  2130. {
  2131. boxedType = mModule->mContext->mBfObjectType;
  2132. }
  2133. auto methodRef = boxedType->mVirtualMethodTable[virtualMethodInstance.mMethodInstance->mVirtualTableIdx];
  2134. if (methodRef.mImplementingMethod.mTypeInstance->IsBoxed())
  2135. {
  2136. auto useModule = mModule->mContext->mUnreifiedModule;
  2137. auto boxedMethodInstance = useModule->ReferenceExternalMethodInstance(methodRef.mImplementingMethod);
  2138. BfBoxedType* vBoxedType = (BfBoxedType*)methodRef.mImplementingMethod.mTypeInstance;
  2139. mBestMethodTypeInstance = vBoxedType->mElementType->ToTypeInstance();
  2140. mBestMethodInstance = mModule->GetMethodInstance(mBestMethodTypeInstance, boxedMethodInstance.mMethodInstance->mMethodDef, BfTypeVector());
  2141. mBestMethodDef = mBestMethodInstance.mMethodInstance->mMethodDef;
  2142. }
  2143. else
  2144. {
  2145. mBestMethodTypeInstance = methodRef.mImplementingMethod.mTypeInstance;
  2146. mBestMethodInstance = mModule->ReferenceExternalMethodInstance(methodRef.mImplementingMethod);
  2147. mBestMethodDef = mBestMethodInstance.mMethodInstance->mMethodDef;
  2148. }
  2149. mBypassVirtual = true;
  2150. }
  2151. }
  2152. bool BfMethodMatcher::HasVarGenerics()
  2153. {
  2154. for (auto genericArg : mBestMethodGenericArguments)
  2155. if (genericArg->IsVar())
  2156. return true;
  2157. for (auto genericArg : mExplicitMethodGenericArguments)
  2158. if (genericArg->IsVar())
  2159. return true;
  2160. return false;
  2161. }
  2162. void BfMethodMatcher::CheckOuterTypeStaticMethods(BfTypeInstance* typeInstance, bool isFailurePass)
  2163. {
  2164. bool allowPrivate = true;
  2165. bool allowProtected = true;
  2166. auto curTypeInst = typeInstance;
  2167. auto curTypeDef = typeInstance->mTypeDef;
  2168. while (true)
  2169. {
  2170. curTypeDef->PopulateMemberSets();
  2171. BfMethodDef* nextMethodDef = NULL;
  2172. BfMemberSetEntry* entry;
  2173. if (curTypeDef->mMethodSet.TryGetWith(mMethodName, &entry))
  2174. nextMethodDef = (BfMethodDef*)entry->mMemberDef;
  2175. while (nextMethodDef != NULL)
  2176. {
  2177. auto checkMethod = nextMethodDef;
  2178. nextMethodDef = nextMethodDef->mNextWithSameName;
  2179. // These can only be invoked when the target itself is the interface
  2180. if (checkMethod->mExplicitInterface != NULL)
  2181. continue;
  2182. if ((checkMethod->mMethodType != mMethodType) || (!checkMethod->mIsStatic))
  2183. continue;
  2184. if (checkMethod->mName != mMethodName)
  2185. continue;
  2186. if ((!isFailurePass) && (!mModule->CheckProtection(checkMethod->mProtection, NULL, allowProtected, allowPrivate)))
  2187. continue;
  2188. CheckMethod(typeInstance, curTypeInst, checkMethod, isFailurePass);
  2189. }
  2190. if (mBestMethodDef != NULL)
  2191. return;
  2192. auto baseType = curTypeInst->mBaseType;
  2193. if (baseType == NULL)
  2194. break;
  2195. curTypeDef = baseType->mTypeDef;
  2196. curTypeInst = baseType;
  2197. allowPrivate = false;
  2198. if ((isFailurePass) && (mBackupMethodDef != NULL))
  2199. break;
  2200. }
  2201. if (mBestMethodDef == NULL)
  2202. {
  2203. // FAILED, but select the first method which will fire an actual error on param type matching
  2204. mBestMethodDef = mBackupMethodDef;
  2205. }
  2206. if (mBestMethodDef == NULL)
  2207. {
  2208. // No explicit target - maybe this was a static call in the outer type?
  2209. auto outerType = mModule->GetOuterType(typeInstance);
  2210. if (outerType != NULL)
  2211. CheckOuterTypeStaticMethods(outerType, isFailurePass);
  2212. }
  2213. }
  2214. //////////////////////////////////////////////////////////////////////////
  2215. void BfResolvedArgs::HandleFixits(BfModule* module)
  2216. {
  2217. auto compiler = module->mCompiler;
  2218. if ((!compiler->IsAutocomplete()) || (compiler->mResolvePassData->mResolveType != BfResolveType_GetFixits))
  2219. return;
  2220. SetAndRestoreValue<bool> ignoreErrors(module->mIgnoreErrors, true);
  2221. for (int argIdx = 0; argIdx < (int)mResolvedArgs.size(); argIdx++)
  2222. {
  2223. auto& resolvedArg = mResolvedArgs[argIdx];
  2224. auto expr = BfNodeDynCast<BfExpression>(resolvedArg.mExpression);
  2225. if (expr != NULL)
  2226. {
  2227. module->CreateValueFromExpression(expr, resolvedArg.mExpectedType);
  2228. }
  2229. }
  2230. }
  2231. //////////////////////////////////////////////////////////////////////////
  2232. BfExprEvaluator::BfExprEvaluator(BfModule* module)
  2233. {
  2234. mBfEvalExprFlags = BfEvalExprFlags_None;
  2235. mModule = module;
  2236. mPropDef = NULL;
  2237. mPropSrc = NULL;
  2238. mPropGetMethodFlags = BfGetMethodInstanceFlag_None;
  2239. mPropCheckedKind = BfCheckedKind_NotSet;
  2240. mUsedAsStatement = false;
  2241. mPropDefBypassVirtual = false;
  2242. mExpectingType = NULL;
  2243. mFunctionBindResult = NULL;
  2244. mExplicitCast = false;
  2245. mDeferCallRef = NULL;
  2246. mDeferScopeAlloc = NULL;
  2247. mPrefixedAttributeState = NULL;
  2248. mResolveGenericParam = true;
  2249. mNoBind = false;
  2250. mResultLocalVar = NULL;
  2251. mResultFieldInstance = NULL;
  2252. mResultLocalVarField = 0;
  2253. mResultLocalVarFieldCount = 0;
  2254. mResultLocalVarRefNode = NULL;
  2255. mIsVolatileReference = false;
  2256. mIsHeapReference = false;
  2257. mResultIsTempComposite = false;
  2258. mAllowReadOnlyReference = false;
  2259. mInsidePendingNullable = false;
  2260. mReceivingValue = NULL;
  2261. }
  2262. BfExprEvaluator::~BfExprEvaluator()
  2263. {
  2264. }
  2265. BfAutoComplete* BfExprEvaluator::GetAutoComplete()
  2266. {
  2267. if (mModule->mCompiler->mResolvePassData == NULL)
  2268. return NULL;
  2269. if ((mBfEvalExprFlags & BfEvalExprFlags_NoAutoComplete) != 0)
  2270. return NULL;
  2271. // For local methods- only process autocomplete on capture phase
  2272. if ((mModule->mCurMethodState != NULL) && (mModule->mCurMethodState->mClosureState != NULL) && (!mModule->mCurMethodState->mClosureState->mCapturing))
  2273. return NULL;
  2274. // if ((mModule->mCurMethodInstance != NULL) && (mModule->mCurMethodInstance->mMethodDef->mIsLocalMethod))
  2275. // return NULL;
  2276. return mModule->mCompiler->mResolvePassData->mAutoComplete;
  2277. }
  2278. BfType* BfExprEvaluator::BindGenericType(BfAstNode* node, BfType* bindType)
  2279. {
  2280. if ((mModule->mCurMethodState == NULL) || (mModule->mCurMethodInstance == NULL) || (bindType == NULL))
  2281. return bindType;
  2282. if ((mModule->mCurMethodState->mClosureState != NULL) && (mModule->mCurMethodState->mClosureState->mCapturing))
  2283. return bindType;
  2284. BF_ASSERT(!mModule->mCurMethodInstance->mIsUnspecializedVariation);
  2285. auto parser = node->GetSourceData()->ToParserData();
  2286. if (parser == NULL)
  2287. return bindType;
  2288. int64 nodeId = ((int64)parser->mDataId << 32) + node->GetSrcStart();
  2289. auto genericTypeBindings = mModule->mCurMethodState->GetRootMethodState()->mGenericTypeBindings;
  2290. if (mModule->mCurMethodInstance->mIsUnspecialized)
  2291. {
  2292. if (!bindType->IsGenericParam())
  2293. return bindType;
  2294. (*genericTypeBindings)[nodeId] = bindType;
  2295. return bindType;
  2296. }
  2297. else
  2298. {
  2299. if (genericTypeBindings == NULL)
  2300. return bindType;
  2301. BfType** typePtr = NULL;
  2302. if (genericTypeBindings->TryGetValue(nodeId, &typePtr))
  2303. return *typePtr;
  2304. return bindType;
  2305. }
  2306. }
  2307. BfType * BfExprEvaluator::ResolveTypeRef(BfTypeReference* typeRef, BfPopulateType populateType, BfResolveTypeRefFlags resolveFlags)
  2308. {
  2309. if (mExpectingType != NULL)
  2310. {
  2311. if (auto namedTypeRef = BfNodeDynCastExact<BfNamedTypeReference>(typeRef))
  2312. {
  2313. if (namedTypeRef->ToString() == "ExpectedType")
  2314. {
  2315. return mModule->ResolveTypeResult(typeRef, mExpectingType, populateType, resolveFlags);
  2316. }
  2317. }
  2318. }
  2319. return mModule->ResolveTypeRef(typeRef, populateType, resolveFlags);
  2320. }
  2321. void BfExprEvaluator::ResolveGenericType()
  2322. {
  2323. if (mResult)
  2324. {
  2325. if (mModule->IsUnboundGeneric(mResult.mType))
  2326. mResult.mType = mModule->GetPrimitiveType(BfTypeCode_Var);
  2327. //mResult.mType = mModule->ResolveGenericType(mResult.mType, true);
  2328. }
  2329. }
  2330. void BfExprEvaluator::Evaluate(BfAstNode* astNode, bool propogateNullConditional, bool ignoreNullConditional, bool allowSplat)
  2331. {
  2332. BP_ZONE("BfExprEvaluator::Evaluate");
  2333. // ParenthesizedExpression breaks null conditional chain
  2334. if (astNode->IsExact<BfParenthesizedExpression>())
  2335. propogateNullConditional = false;
  2336. BfPendingNullConditional* pendingNullCond = NULL;
  2337. if (mModule->mCurMethodState != NULL)
  2338. {
  2339. pendingNullCond = mModule->mCurMethodState->mPendingNullConditional;
  2340. if (!propogateNullConditional)
  2341. mModule->mCurMethodState->mPendingNullConditional = NULL;
  2342. }
  2343. mInsidePendingNullable = pendingNullCond != NULL;
  2344. astNode->Accept(this);
  2345. GetResult();
  2346. if ((mResultIsTempComposite) && (mResult.IsAddr()))
  2347. mResult.mKind = BfTypedValueKind_TempAddr;
  2348. if ((!allowSplat) && (mResult.IsSplat()))
  2349. mResult = mModule->AggregateSplat(mResult);
  2350. if ((mBfEvalExprFlags & BfEvalExprFlags_AllowIntUnknown) == 0)
  2351. mModule->FixIntUnknown(mResult);
  2352. if ((!propogateNullConditional) && (mModule->mCurMethodState != NULL))
  2353. {
  2354. if (mModule->mCurMethodState->mPendingNullConditional != NULL)
  2355. mResult = mModule->FlushNullConditional(mResult, ignoreNullConditional);
  2356. mModule->mCurMethodState->mPendingNullConditional = pendingNullCond;
  2357. }
  2358. }
  2359. void BfExprEvaluator::Visit(BfErrorNode* errorNode)
  2360. {
  2361. mModule->Fail("Invalid token", errorNode);
  2362. auto autoComplete = GetAutoComplete();
  2363. if (autoComplete != NULL)
  2364. {
  2365. if (auto tokenNode = BfNodeDynCast<BfTokenNode>(errorNode->mRefNode))
  2366. return;
  2367. autoComplete->CheckIdentifier(errorNode->mRefNode, true);
  2368. }
  2369. }
  2370. void BfExprEvaluator::Visit(BfTypeReference* typeRef)
  2371. {
  2372. mResult.mType = ResolveTypeRef(typeRef, BfPopulateType_Declaration);
  2373. }
  2374. void BfExprEvaluator::Visit(BfAttributedExpression* attribExpr)
  2375. {
  2376. BfAttributeState attributeState;
  2377. attributeState.mSrc = attribExpr->mAttributes;
  2378. attributeState.mTarget = (BfAttributeTargets)(BfAttributeTargets_Invocation | BfAttributeTargets_MemberAccess);
  2379. if (auto block = BfNodeDynCast<BfBlock>(attribExpr->mExpression))
  2380. attributeState.mTarget = BfAttributeTargets_Block;
  2381. attributeState.mCustomAttributes = mModule->GetCustomAttributes(attribExpr->mAttributes, attributeState.mTarget);
  2382. SetAndRestoreValue<BfAttributeState*> prevAttributeState(mModule->mAttributeState, &attributeState);
  2383. if (auto ignoreErrorsAttrib = attributeState.mCustomAttributes->Get(mModule->mCompiler->mIgnoreErrorsAttributeTypeDef))
  2384. {
  2385. SetAndRestoreValue<bool> ignoreErrors(mModule->mIgnoreErrors, true);
  2386. if (!ignoreErrorsAttrib->mCtorArgs.IsEmpty())
  2387. {
  2388. auto constant = mModule->mCurTypeInstance->mConstHolder->GetConstant(ignoreErrorsAttrib->mCtorArgs[0]);
  2389. if (constant->mBool)
  2390. attributeState.mFlags = BfAttributeState::Flag_StopOnError;
  2391. }
  2392. VisitChild(attribExpr->mExpression);
  2393. attributeState.mUsed = true;
  2394. if ((!mResult) ||
  2395. ((mResult) && (mResult.mType->IsVar())))
  2396. {
  2397. if (!mResult)
  2398. mModule->Fail("Expression did not result in a value", attribExpr->mExpression);
  2399. // Make empty or 'var' resolve as 'false' because var is only valid if we threw errors
  2400. mResult = mModule->GetDefaultTypedValue(mModule->GetPrimitiveType(BfTypeCode_Boolean));
  2401. }
  2402. }
  2403. else
  2404. {
  2405. VisitChild(attribExpr->mExpression);
  2406. }
  2407. mModule->FinishAttributeState(&attributeState);
  2408. }
  2409. void BfExprEvaluator::Visit(BfBlock* blockExpr)
  2410. {
  2411. if (mModule->mCurMethodState == NULL)
  2412. {
  2413. mModule->Fail("Illegal use of block expression", blockExpr);
  2414. return;
  2415. }
  2416. auto autoComplete = GetAutoComplete();
  2417. if ((autoComplete != NULL) && (autoComplete->mMethodMatchInfo != NULL) && (autoComplete->IsAutocompleteNode(blockExpr)))
  2418. {
  2419. // Don't show outer method match info when our cursor is inside a block (being passed as a parameter)
  2420. autoComplete->RemoveMethodMatchInfo();
  2421. }
  2422. if (blockExpr->mChildArr.IsEmpty())
  2423. {
  2424. mModule->Fail("An empty block cannot be used as an expression", blockExpr);
  2425. return;
  2426. }
  2427. bool lastWasResultExpr = false;
  2428. if (auto lastExpr = BfNodeDynCast<BfExpressionStatement>(blockExpr->mChildArr.GetLast()))
  2429. {
  2430. if (!lastExpr->IsMissingSemicolon())
  2431. mModule->Fail("Expression blocks must end in an expression which is missing its terminating semicolon", lastExpr->mTrailingSemicolon);
  2432. }
  2433. else if (auto lastExpr = BfNodeDynCast<BfExpression>(blockExpr->mChildArr.GetLast()))
  2434. {
  2435. // Expression
  2436. }
  2437. else
  2438. {
  2439. mModule->Fail("Expression blocks must end with an expression", blockExpr);
  2440. }
  2441. mModule->VisitEmbeddedStatement(blockExpr, this);
  2442. }
  2443. bool BfExprEvaluator::CheckVariableDeclaration(BfAstNode* checkNode, bool requireSimpleIfExpr, bool exprMustBeTrue, bool silentFail)
  2444. {
  2445. BfAstNode* checkChild = checkNode;
  2446. bool childWasAndRHS = false;
  2447. bool foundIf = false;
  2448. auto parentNodeEntry = mModule->mParentNodeEntry;
  2449. if (parentNodeEntry != NULL)
  2450. {
  2451. if (BfNodeIsA<BfInvocationExpression>(parentNodeEntry->mNode))
  2452. {
  2453. checkChild = parentNodeEntry->mNode;
  2454. parentNodeEntry = parentNodeEntry->mPrev;
  2455. }
  2456. }
  2457. auto _Fail = [&](const StringImpl& errorStr, BfAstNode* node)
  2458. {
  2459. if (!silentFail)
  2460. {
  2461. auto error = mModule->Fail(errorStr, node);
  2462. if ((error != NULL) && (node != checkNode))
  2463. {
  2464. mModule->mCompiler->mPassInstance->MoreInfo("See variable declaration", checkNode);
  2465. }
  2466. }
  2467. return false;
  2468. };
  2469. while (parentNodeEntry != NULL)
  2470. {
  2471. BfAstNode* checkParent = parentNodeEntry->mNode;
  2472. if (auto binOpExpr = BfNodeDynCastExact<BfBinaryOperatorExpression>(checkParent))
  2473. {
  2474. if (binOpExpr->mOp == BfBinaryOp_ConditionalAnd)
  2475. {
  2476. // This is always okay
  2477. childWasAndRHS = (binOpExpr->mRight != NULL) && (binOpExpr->mRight->Contains(checkChild));
  2478. }
  2479. else if ((binOpExpr->mOp == BfBinaryOp_ConditionalOr) && (!exprMustBeTrue))
  2480. {
  2481. if ((binOpExpr->mRight != NULL) && (binOpExpr->mRight->Contains(checkChild)))
  2482. {
  2483. return _Fail("Conditional short-circuiting may skip variable initialization", binOpExpr->mOpToken);
  2484. }
  2485. }
  2486. else
  2487. {
  2488. if (exprMustBeTrue)
  2489. {
  2490. return _Fail("Operator cannot be used with variable initialization", binOpExpr->mOpToken);
  2491. }
  2492. }
  2493. }
  2494. else if (auto parenExpr = BfNodeDynCast<BfParenthesizedExpression>(checkParent))
  2495. {
  2496. // This is okay
  2497. }
  2498. else if (auto unaryOp = BfNodeDynCast<BfUnaryOperatorExpression>(checkParent))
  2499. {
  2500. if (exprMustBeTrue)
  2501. {
  2502. return _Fail("Operator cannot be used with variable initialization", unaryOp->mOpToken);
  2503. return false;
  2504. }
  2505. if (childWasAndRHS)
  2506. {
  2507. return _Fail("Operator may allow conditional short-circuiting to skip variable initialization", unaryOp->mOpToken);
  2508. }
  2509. }
  2510. else if (auto ifStmt = BfNodeDynCast<BfIfStatement>(checkParent))
  2511. {
  2512. // Done
  2513. foundIf = true;
  2514. break;
  2515. }
  2516. else
  2517. {
  2518. if (requireSimpleIfExpr)
  2519. {
  2520. return _Fail("Variable declaration expression can only be contained in simple 'if' expressions", checkNode);
  2521. }
  2522. break;
  2523. }
  2524. checkChild = parentNodeEntry->mNode;
  2525. parentNodeEntry = parentNodeEntry->mPrev;
  2526. }
  2527. return foundIf;
  2528. }
  2529. bool BfExprEvaluator::HasVariableDeclaration(BfAstNode* checkNode)
  2530. {
  2531. BfVarDeclChecker checker;
  2532. checker.VisitChild(checkNode);
  2533. return checker.mHasVarDecl;
  2534. }
  2535. void BfExprEvaluator::Visit(BfVariableDeclaration* varDecl)
  2536. {
  2537. mModule->UpdateExprSrcPos(varDecl);
  2538. if ((mModule->mCurMethodState == NULL) || (!mModule->mCurMethodState->mCurScope->mAllowVariableDeclarations))
  2539. {
  2540. mModule->Fail("Variable declarations are not allowed in this context", varDecl);
  2541. if (varDecl->mInitializer != NULL)
  2542. {
  2543. VisitChild(varDecl->mInitializer);
  2544. }
  2545. return;
  2546. }
  2547. CheckVariableDeclaration(varDecl, true, false, false);
  2548. if (varDecl->mInitializer == NULL)
  2549. {
  2550. mModule->Fail("Variable declarations used as expressions must have an initializer", varDecl);
  2551. }
  2552. BfTupleExpression* tupleVariableDeclaration = BfNodeDynCast<BfTupleExpression>(varDecl->mNameNode);
  2553. if (tupleVariableDeclaration != NULL)
  2554. {
  2555. mModule->Fail("Tuple variable declarations cannot be used as expressions", varDecl);
  2556. mModule->HandleTupleVariableDeclaration(varDecl);
  2557. }
  2558. else
  2559. mModule->HandleVariableDeclaration(varDecl, this);
  2560. }
  2561. void BfExprEvaluator::Visit(BfCaseExpression* caseExpr)
  2562. {
  2563. if (caseExpr->mEqualsNode != NULL)
  2564. {
  2565. mModule->Warn(0, "Deprecated case syntax", caseExpr->mEqualsNode);
  2566. }
  2567. BfTypedValue caseValAddr;
  2568. if (caseExpr->mValueExpression != NULL)
  2569. caseValAddr = mModule->CreateValueFromExpression(caseExpr->mValueExpression);
  2570. if ((caseValAddr.mType != NULL) && (caseValAddr.mType->IsPointer()))
  2571. {
  2572. caseValAddr = mModule->LoadValue(caseValAddr);
  2573. caseValAddr = BfTypedValue(caseValAddr.mValue, caseValAddr.mType->GetUnderlyingType(), true);
  2574. }
  2575. if (caseValAddr.mType != NULL)
  2576. mModule->mBfIRBuilder->PopulateType(caseValAddr.mType);
  2577. if ((mModule->mCurMethodState != NULL) && (mModule->mCurMethodState->mDeferredLocalAssignData != NULL))
  2578. mModule->mCurMethodState->mDeferredLocalAssignData->BreakExtendChain();
  2579. if (auto bindExpr = BfNodeDynCast<BfEnumCaseBindExpression>(caseExpr->mCaseExpression))
  2580. {
  2581. if (caseValAddr)
  2582. {
  2583. BfTypedValue enumTagVal;
  2584. if (caseValAddr.mType->IsPayloadEnum())
  2585. {
  2586. int dscrDataIdx;
  2587. auto dscrType = caseValAddr.mType->ToTypeInstance()->GetDiscriminatorType(&dscrDataIdx);
  2588. enumTagVal = BfTypedValue(mModule->ExtractValue(caseValAddr, dscrDataIdx), dscrType);
  2589. }
  2590. else
  2591. enumTagVal = mModule->GetDefaultTypedValue(mModule->GetPrimitiveType(BfTypeCode_Int32));
  2592. mResult = mModule->HandleCaseBind(caseValAddr, enumTagVal, bindExpr);
  2593. return;
  2594. }
  2595. }
  2596. bool isPayloadEnum = (caseValAddr.mType != NULL) && (caseValAddr.mType->IsPayloadEnum());
  2597. auto tupleExpr = BfNodeDynCast<BfTupleExpression>(caseExpr->mCaseExpression);
  2598. if ((caseValAddr) &&
  2599. ((isPayloadEnum) || (tupleExpr != NULL)))
  2600. {
  2601. bool hasVariable = false;
  2602. bool hasOut = false;
  2603. bool clearOutOnMismatch = false;
  2604. if (auto invocateExpr = BfNodeDynCast<BfInvocationExpression>(caseExpr->mCaseExpression))
  2605. {
  2606. for (auto arg : invocateExpr->mArguments)
  2607. {
  2608. if (auto varDecl = BfNodeDynCast<BfVariableDeclaration>(arg))
  2609. {
  2610. hasVariable = true;
  2611. }
  2612. else if (auto unaryOpExpr = BfNodeDynCast<BfUnaryOperatorExpression>(arg))
  2613. {
  2614. if (unaryOpExpr->mOpToken->mToken == BfToken_Out)
  2615. {
  2616. hasOut = true;
  2617. }
  2618. }
  2619. }
  2620. }
  2621. if (hasVariable)
  2622. {
  2623. CheckVariableDeclaration(caseExpr, false, true, false);
  2624. }
  2625. // We can avoid clearing on mismatch if we can be sure we ONLY enter the true block on a match.
  2626. // An example of requiring clearing is: if ((result case .Ok(out val)) || (force))
  2627. if (hasOut)
  2628. clearOutOnMismatch = !CheckVariableDeclaration(caseExpr, true, true, true);
  2629. bool hadConditional = false;
  2630. if (isPayloadEnum)
  2631. {
  2632. int dscrDataIdx;
  2633. auto dscrType = caseValAddr.mType->ToTypeInstance()->GetDiscriminatorType(&dscrDataIdx);
  2634. auto enumTagVal = mModule->LoadValue(mModule->ExtractValue(caseValAddr, NULL, 2));
  2635. int uncondTagId = -1;
  2636. mResult = mModule->TryCaseEnumMatch(caseValAddr, enumTagVal, caseExpr->mCaseExpression, NULL, NULL, NULL, uncondTagId, hadConditional, clearOutOnMismatch);
  2637. }
  2638. else
  2639. {
  2640. mResult = mModule->TryCaseTupleMatch(caseValAddr, tupleExpr, NULL, NULL, NULL, hadConditional, clearOutOnMismatch);
  2641. }
  2642. if (mResult)
  2643. return;
  2644. }
  2645. if ((caseValAddr) && (caseValAddr.mType->IsVar()))
  2646. {
  2647. auto invocationExpr = BfNodeDynCast<BfInvocationExpression>(caseExpr->mCaseExpression);
  2648. if (invocationExpr != NULL)
  2649. {
  2650. for (auto expr : invocationExpr->mArguments)
  2651. {
  2652. if (expr == NULL)
  2653. continue;
  2654. if (auto varDecl = BfNodeDynCast<BfVariableDeclaration>(expr))
  2655. {
  2656. auto localVar = mModule->HandleVariableDeclaration(varDecl, BfTypedValue());
  2657. if (localVar != NULL)
  2658. localVar->mReadFromId = 0;
  2659. }
  2660. }
  2661. }
  2662. auto boolType = mModule->GetPrimitiveType(BfTypeCode_Boolean);
  2663. mResult = mModule->GetDefaultTypedValue(boolType);
  2664. return;
  2665. }
  2666. auto boolType = mModule->GetPrimitiveType(BfTypeCode_Boolean);
  2667. BfTypedValue caseMatch;
  2668. if (caseExpr->mCaseExpression != NULL)
  2669. caseMatch = mModule->CreateValueFromExpression(caseExpr->mCaseExpression, caseValAddr.mType, BfEvalExprFlags_AllowEnumId);
  2670. if ((!caseMatch) || (!caseValAddr))
  2671. {
  2672. mResult = mModule->GetDefaultTypedValue(boolType);
  2673. return;
  2674. }
  2675. if (caseValAddr.mType == caseMatch.mType)
  2676. {
  2677. if (((caseValAddr.mType->IsEnum()) && (caseValAddr.mType->IsStruct())) &&
  2678. ((caseMatch) && (caseMatch.mType->IsPayloadEnum()) && (caseMatch.mValue.IsConst())))
  2679. {
  2680. BfTypedValue enumTagVal = mModule->LoadValue(mModule->ExtractValue(caseValAddr, NULL, 2));
  2681. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateCmpEQ(enumTagVal.mValue, caseMatch.mValue), boolType);
  2682. return;
  2683. }
  2684. }
  2685. else
  2686. {
  2687. // We need to get rid of the int-const for the 'scalar match'. We get a full payload enum value so we can
  2688. // possibly use it in a user-defined comparison operator
  2689. if ((caseMatch.mType->IsStruct()) && (caseMatch.mValue.IsConst()))
  2690. {
  2691. // Is it possible this could throw an error twice? Hope not.
  2692. caseMatch = mModule->CreateValueFromExpression(caseExpr->mCaseExpression, NULL);
  2693. }
  2694. }
  2695. PerformBinaryOperation(caseExpr->mCaseExpression, caseExpr->mValueExpression, BfBinaryOp_Equality, caseExpr->mEqualsNode, BfBinOpFlag_None, caseValAddr, caseMatch);
  2696. }
  2697. void BfExprEvaluator::Visit(BfTypedValueExpression* typedValueExpr)
  2698. {
  2699. mResult = typedValueExpr->mTypedValue;
  2700. }
  2701. static bool IsCharType(BfTypeCode typeCode)
  2702. {
  2703. switch (typeCode)
  2704. {
  2705. case BfTypeCode_Char8:
  2706. case BfTypeCode_Char16:
  2707. case BfTypeCode_Char32:
  2708. return true;
  2709. default:
  2710. return false;
  2711. }
  2712. }
  2713. void BfExprEvaluator::GetLiteral(BfAstNode* refNode, const BfVariant& variant)
  2714. {
  2715. switch (variant.mTypeCode)
  2716. {
  2717. case BfTypeCode_NullPtr:
  2718. {
  2719. auto nullType = mModule->ResolveTypeDef(mModule->mSystem->mTypeNullPtr);
  2720. /*mResult = BfTypedValue(ConstantPointerNull::get((PointerType*) nullType->mIRType), nullType);*/
  2721. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConstNull(), nullType);
  2722. }
  2723. break;
  2724. case BfTypeCode_CharPtr:
  2725. {
  2726. if ((mExpectingType != NULL) && (mExpectingType->IsSizedArray()))
  2727. {
  2728. auto sizedArray = (BfSizedArrayType*)mExpectingType;
  2729. if (sizedArray->mElementType == mModule->GetPrimitiveType(BfTypeCode_Char8))
  2730. {
  2731. if (variant.mString->GetLength() > sizedArray->mElementCount)
  2732. {
  2733. mModule->Fail(StrFormat("String literal is too long to fit into '%s'", mModule->TypeToString(sizedArray).c_str()), refNode);
  2734. }
  2735. Array<BfIRValue> charValues;
  2736. for (int i = 0; i < (int)BF_MIN(variant.mString->GetLength(), sizedArray->mElementCount); i++)
  2737. {
  2738. char c = (*variant.mString)[i];
  2739. charValues.Add(mModule->mBfIRBuilder->CreateConst(BfTypeCode_Char8, (int)(uint8)c));
  2740. }
  2741. if (sizedArray->mElementCount > charValues.size())
  2742. charValues.Add(mModule->mBfIRBuilder->CreateConst(BfTypeCode_Char8, 0));
  2743. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConstArray(mModule->mBfIRBuilder->MapType(sizedArray), charValues), sizedArray);
  2744. return;
  2745. }
  2746. }
  2747. if ((mExpectingType == NULL) || (!mExpectingType->IsPointer()))
  2748. {
  2749. mResult = BfTypedValue(mModule->GetStringObjectValue(*variant.mString),
  2750. mModule->ResolveTypeDef(mModule->mCompiler->mStringTypeDef));
  2751. }
  2752. else
  2753. {
  2754. auto charType = mModule->GetPrimitiveType(BfTypeCode_Char8);
  2755. auto charPtrType = mModule->CreatePointerType(charType);
  2756. mResult = BfTypedValue(mModule->GetStringCharPtr(*variant.mString),
  2757. charPtrType);
  2758. }
  2759. }
  2760. break;
  2761. case BfTypeCode_Boolean:
  2762. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConst(variant.mTypeCode, variant.mUInt64), mModule->GetPrimitiveType(variant.mTypeCode));
  2763. break;
  2764. case BfTypeCode_Char8:
  2765. case BfTypeCode_Char16:
  2766. case BfTypeCode_Char32:
  2767. case BfTypeCode_Int8:
  2768. case BfTypeCode_UInt8:
  2769. case BfTypeCode_Int16:
  2770. case BfTypeCode_UInt16:
  2771. case BfTypeCode_Int32:
  2772. case BfTypeCode_UInt32:
  2773. case BfTypeCode_Int64:
  2774. case BfTypeCode_UInt64:
  2775. case BfTypeCode_IntPtr:
  2776. case BfTypeCode_UIntPtr:
  2777. case BfTypeCode_IntUnknown:
  2778. case BfTypeCode_UIntUnknown:
  2779. if ((mExpectingType != NULL) && (mExpectingType->IsIntegral()) && (mExpectingType->IsChar() == IsCharType(variant.mTypeCode)))
  2780. {
  2781. auto primType = (BfPrimitiveType*)mExpectingType;
  2782. if (mModule->mSystem->DoesLiteralFit(primType->mTypeDef->mTypeCode, variant.mInt64))
  2783. {
  2784. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConst(primType->mTypeDef->mTypeCode, variant.mUInt64), mExpectingType);
  2785. break;
  2786. }
  2787. }
  2788. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConst(variant.mTypeCode, variant.mUInt64), mModule->GetPrimitiveType(variant.mTypeCode));
  2789. break;
  2790. case BfTypeCode_Float:
  2791. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConst(variant.mTypeCode, variant.mSingle), mModule->GetPrimitiveType(variant.mTypeCode));
  2792. break;
  2793. case BfTypeCode_Double:
  2794. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConst(variant.mTypeCode, variant.mDouble), mModule->GetPrimitiveType(variant.mTypeCode));
  2795. break;
  2796. default:
  2797. mModule->Fail("Invalid literal", refNode);
  2798. break;
  2799. }
  2800. }
  2801. void BfExprEvaluator::Visit(BfLiteralExpression* literalExpr)
  2802. {
  2803. switch (literalExpr->mValue.mWarnType)
  2804. {
  2805. case BfWarning_BF4201_Only7Hex:
  2806. mModule->Warn(BfWarning_BF4201_Only7Hex, "Only 7 hex digits specified. Add a leading zero to clarify intention.", literalExpr);
  2807. break;
  2808. case BfWarning_BF4202_TooManyHexForInt:
  2809. 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);
  2810. break;
  2811. }
  2812. GetLiteral(literalExpr, literalExpr->mValue);
  2813. }
  2814. void BfExprEvaluator::Visit(BfStringInterpolationExpression* stringInterpolationExpression)
  2815. {
  2816. if ((mBfEvalExprFlags & BfEvalExprFlags_StringInterpolateFormat) != 0)
  2817. {
  2818. BfVariant variant;
  2819. variant.mTypeCode = BfTypeCode_CharPtr;
  2820. variant.mString = stringInterpolationExpression->mString;
  2821. GetLiteral(stringInterpolationExpression, variant);
  2822. return;
  2823. }
  2824. if (stringInterpolationExpression->mAllocNode != NULL)
  2825. {
  2826. auto stringType = mModule->ResolveTypeDef(mModule->mCompiler->mStringTypeDef)->ToTypeInstance();
  2827. BfTokenNode* newToken = NULL;
  2828. BfAllocTarget allocTarget = ResolveAllocTarget(stringInterpolationExpression->mAllocNode, newToken);
  2829. CreateObject(NULL, stringInterpolationExpression->mAllocNode, stringType);
  2830. BfTypedValue newString = mResult;
  2831. BF_ASSERT(newString);
  2832. SizedArray<BfExpression*, 2> argExprs;
  2833. argExprs.Add(stringInterpolationExpression);
  2834. BfSizedArray<BfExpression*> sizedArgExprs(argExprs);
  2835. BfResolvedArgs argValues(&sizedArgExprs);
  2836. ResolveArgValues(argValues, BfResolveArgFlag_InsideStringInterpolationAlloc);
  2837. MatchMethod(stringInterpolationExpression, NULL, newString, false, false, "AppendF", argValues, NULL);
  2838. mResult = newString;
  2839. return;
  2840. }
  2841. mModule->Fail("Invalid use of string interpolation expression. Consider adding an allocation specifier such as 'scope'.", stringInterpolationExpression);
  2842. for (auto block : stringInterpolationExpression->mExpressions)
  2843. {
  2844. VisitChild(block);
  2845. }
  2846. }
  2847. BfTypedValue BfExprEvaluator::LoadLocal(BfLocalVariable* varDecl, bool allowRef)
  2848. {
  2849. if (!mModule->mIsInsideAutoComplete)
  2850. varDecl->mReadFromId = mModule->mCurMethodState->GetRootMethodState()->mCurAccessId++;
  2851. // The Beef backend prefers readonly addrs since that reduces register pressure, whereas
  2852. // LLVM prefers values to avoid memory loads. This only applies to primitive types...
  2853. bool preferValue = (varDecl->mResolvedType->IsPrimitiveType()) && (!mModule->IsTargetingBeefBackend());
  2854. BfTypedValue localResult;
  2855. if (varDecl->mIsThis)
  2856. {
  2857. return mModule->GetThis();
  2858. }
  2859. else if (varDecl->mConstValue)
  2860. {
  2861. localResult = BfTypedValue(varDecl->mConstValue, varDecl->mResolvedType, false);
  2862. }
  2863. else if (varDecl->mIsSplat)
  2864. {
  2865. if ((!preferValue) && (varDecl->mAddr))
  2866. localResult = BfTypedValue(varDecl->mAddr, varDecl->mResolvedType, BfTypedValueKind_SplatHead);
  2867. else if (!varDecl->mResolvedType->IsValuelessType())
  2868. localResult = BfTypedValue(varDecl->mValue, varDecl->mResolvedType, BfTypedValueKind_SplatHead);
  2869. else if ((varDecl->mResolvedType->IsRef()) && (!allowRef))
  2870. {
  2871. BF_ASSERT(varDecl->mResolvedType->IsValuelessType());
  2872. localResult = BfTypedValue(varDecl->mValue, varDecl->mResolvedType->GetUnderlyingType());
  2873. }
  2874. else
  2875. localResult = BfTypedValue(varDecl->mValue, varDecl->mResolvedType);
  2876. //BF_ASSERT(varDecl->mValue.IsArg());
  2877. }
  2878. else if ((varDecl->mValue) && ((varDecl->mIsReadOnly && preferValue) || (!varDecl->mAddr)))
  2879. {
  2880. if ((varDecl->mResolvedType->IsRef()) && (!allowRef))
  2881. {
  2882. BfRefType* refType = (BfRefType*)varDecl->mResolvedType;
  2883. BfType* innerType = refType->mElementType;
  2884. if (innerType->IsGenericParam())
  2885. {
  2886. if (refType->mRefKind == BfRefType::RefKind_Mut)
  2887. {
  2888. localResult = BfTypedValue(varDecl->mValue, innerType, BfTypedValueKind_MutableValue);
  2889. return localResult;
  2890. }
  2891. else
  2892. {
  2893. localResult = BfTypedValue(varDecl->mValue, innerType, BfTypedValueKind_Addr);
  2894. return localResult;
  2895. }
  2896. }
  2897. localResult = BfTypedValue(varDecl->mValue, innerType, BfTypedValueKind_Addr);
  2898. }
  2899. else
  2900. {
  2901. BfTypedValueKind kind;
  2902. if ((varDecl->mResolvedType->IsComposite()) && (varDecl->IsParam()) && (mModule->mCurMethodState->mMixinState == NULL))
  2903. kind = varDecl->mIsReadOnly ? BfTypedValueKind_ReadOnlyAddr : BfTypedValueKind_Addr;
  2904. else
  2905. kind = BfTypedValueKind_Value;
  2906. localResult = BfTypedValue(varDecl->mValue, varDecl->mResolvedType, kind);
  2907. }
  2908. }
  2909. else if (varDecl->mAddr)
  2910. {
  2911. if ((varDecl->mResolvedType->IsRef()) && (!allowRef))
  2912. {
  2913. BfRefType* refType = (BfRefType*)varDecl->mResolvedType;
  2914. BfType* innerType = refType->mElementType;
  2915. if (innerType->IsValuelessType())
  2916. {
  2917. if (refType->mRefKind == BfRefType::RefKind_Mut)
  2918. return BfTypedValue(mModule->mBfIRBuilder->GetFakeVal(), innerType, BfTypedValueKind_MutableValue);
  2919. return BfTypedValue(mModule->mBfIRBuilder->GetFakeVal(), innerType, varDecl->mIsReadOnly ? BfTypedValueKind_ReadOnlyAddr : BfTypedValueKind_Addr);
  2920. }
  2921. if (refType->mRefKind == BfRefType::RefKind_Mut)
  2922. {
  2923. if (innerType->IsGenericParam())
  2924. {
  2925. localResult = BfTypedValue(mModule->mBfIRBuilder->CreateAlignedLoad(varDecl->mAddr, varDecl->mResolvedType->mAlign), innerType, BfTypedValueKind_MutableValue);
  2926. return localResult;
  2927. }
  2928. }
  2929. localResult = BfTypedValue(mModule->mBfIRBuilder->CreateAlignedLoad(varDecl->mAddr, varDecl->mResolvedType->mAlign), innerType, varDecl->mIsReadOnly ? BfTypedValueKind_ReadOnlyAddr : BfTypedValueKind_Addr);
  2930. }
  2931. else if (varDecl->mHasLocalStructBacking)
  2932. {
  2933. // varDecl->mAddr is a "struct**"
  2934. localResult = BfTypedValue(mModule->mBfIRBuilder->CreateAlignedLoad(varDecl->mAddr, varDecl->mResolvedType->mAlign), varDecl->mResolvedType, varDecl->mIsReadOnly ? BfTypedValueKind_ReadOnlyAddr : BfTypedValueKind_Addr);
  2935. }
  2936. else
  2937. localResult = BfTypedValue(varDecl->mAddr, varDecl->mResolvedType, varDecl->mIsReadOnly ? BfTypedValueKind_ReadOnlyAddr : BfTypedValueKind_Addr);
  2938. }
  2939. else if (varDecl->mResolvedType->IsValuelessType())
  2940. {
  2941. if ((varDecl->mResolvedType->IsRef()) && (!allowRef))
  2942. {
  2943. BfRefType* refType = (BfRefType*)varDecl->mResolvedType;
  2944. BfType* innerType = refType->mElementType;
  2945. localResult = BfTypedValue(mModule->mBfIRBuilder->GetFakeVal(), innerType, true);
  2946. return localResult;
  2947. }
  2948. localResult = BfTypedValue(mModule->mBfIRBuilder->GetFakeVal(), varDecl->mResolvedType, true);
  2949. }
  2950. else if (varDecl->mCompositeCount >= 0)
  2951. {
  2952. localResult = BfTypedValue(BfIRValue(), mModule->GetPrimitiveType(BfTypeCode_None));
  2953. }
  2954. else
  2955. {
  2956. BF_ASSERT((mModule->mCurMethodState->mClosureState != NULL) || (mModule->mBfIRBuilder->mIgnoreWrites));
  2957. // Just temporary
  2958. auto varType = varDecl->mResolvedType;
  2959. auto allocType = varType;
  2960. if (varType->IsRef())
  2961. {
  2962. BfRefType* refType = (BfRefType*)varType;
  2963. allocType = refType->mElementType;
  2964. }
  2965. auto declType = varDecl->mResolvedType;
  2966. if (declType->IsRef())
  2967. {
  2968. BfRefType* refType = (BfRefType*)declType;
  2969. declType = refType->mElementType;
  2970. }
  2971. mModule->PopulateType(allocType);
  2972. varDecl->mAddr = mModule->mBfIRBuilder->CreateAlloca(mModule->mBfIRBuilder->MapType(allocType));
  2973. localResult = BfTypedValue(varDecl->mAddr, declType, true);
  2974. return localResult;
  2975. }
  2976. if ((varDecl->mIsThis) && (localResult.mKind == BfTypedValueKind_Value))
  2977. localResult.mKind = BfTypedValueKind_ThisValue;
  2978. return localResult;
  2979. }
  2980. BfTypedValue BfExprEvaluator::LookupIdentifier(BfAstNode* refNode, const StringImpl& findName, bool ignoreInitialError, bool* hadError)
  2981. {
  2982. auto identifierNode = BfNodeDynCast<BfIdentifierNode>(refNode);
  2983. if (mModule->mCurMethodState != NULL)
  2984. {
  2985. auto rootMethodState = mModule->mCurMethodState->GetRootMethodState();
  2986. auto checkMethodState = mModule->mCurMethodState;
  2987. bool isMixinOuterVariablePass = false;
  2988. while (checkMethodState != NULL)
  2989. {
  2990. BP_ZONE("LookupIdentifier:LocalVar");
  2991. BfTypeInstance* closureTypeInst = NULL;
  2992. if ((checkMethodState->mClosureState != NULL) && (checkMethodState->mClosureState->mClosureType != NULL) && (!checkMethodState->mClosureState->mCapturing))
  2993. {
  2994. closureTypeInst = mModule->mCurMethodState->mClosureState->mClosureType;
  2995. }
  2996. int varSkipCount = 0;
  2997. StringT<128> wantName;
  2998. wantName.Reference(findName);
  2999. if (findName.StartsWith('@'))
  3000. {
  3001. wantName = findName;
  3002. while (wantName.StartsWith("@"))
  3003. {
  3004. varSkipCount++;
  3005. wantName.Remove(0);
  3006. }
  3007. }
  3008. if (wantName.IsEmpty())
  3009. {
  3010. mModule->Fail("Shadowed variable name expected after '@'", refNode);
  3011. }
  3012. BfLocalVarEntry* entry;
  3013. if (checkMethodState->mLocalVarSet.TryGetWith<StringImpl&>(wantName, &entry))
  3014. {
  3015. auto varDecl = entry->mLocalVar;
  3016. while ((varSkipCount > 0) && (varDecl != NULL))
  3017. {
  3018. varDecl = varDecl->mShadowedLocal;
  3019. varSkipCount--;
  3020. }
  3021. if ((varDecl != NULL) && (varDecl->mNotCaptured))
  3022. {
  3023. mModule->Fail("Local variable is not captured", refNode);
  3024. }
  3025. if ((varSkipCount == 0) && (varDecl != NULL))
  3026. {
  3027. if ((closureTypeInst != NULL) && (wantName == "this"))
  3028. break;
  3029. if ((varDecl->mCompositeCount >= 0) && ((mBfEvalExprFlags & BfEvalExprFlags_AllowParamsExpr) == 0))
  3030. {
  3031. mModule->Fail("Invalid use of 'params' parameter", refNode);
  3032. }
  3033. if (varDecl->mResolvedType->IsVoid())
  3034. {
  3035. if ((varDecl->mIsReadOnly) && (varDecl->mParamIdx == -2) && (varDecl->mParamFailed))
  3036. {
  3037. BF_ASSERT(mModule->mCurMethodInstance->mMethodDef->mMethodType == BfMethodType_CtorCalcAppend);
  3038. 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);
  3039. }
  3040. }
  3041. BfTypedValue localResult = LoadLocal(varDecl);
  3042. auto autoComplete = GetAutoComplete();
  3043. if (identifierNode != NULL)
  3044. {
  3045. if (autoComplete != NULL)
  3046. autoComplete->CheckLocalRef(identifierNode, varDecl);
  3047. if (((mModule->mCurMethodState->mClosureState == NULL) || (mModule->mCurMethodState->mClosureState->mCapturing)) &&
  3048. (mModule->mCompiler->mResolvePassData != NULL) && (mModule->mCurMethodInstance != NULL) && (!mModule->mCurMethodState->IsTemporary()))
  3049. mModule->mCompiler->mResolvePassData->HandleLocalReference(identifierNode, varDecl->mNameNode, mModule->mCurTypeInstance->mTypeDef, rootMethodState->mMethodInstance->mMethodDef, varDecl->mLocalVarId);
  3050. }
  3051. if (!isMixinOuterVariablePass)
  3052. {
  3053. mResultLocalVar = varDecl;
  3054. mResultFieldInstance = NULL;
  3055. mResultLocalVarRefNode = identifierNode;
  3056. }
  3057. return localResult;
  3058. }
  3059. }
  3060. // Check for the captured locals. It's important we do it here so we get local-first precedence still
  3061. if (closureTypeInst != NULL)
  3062. {
  3063. int varSkipCount = 0;
  3064. StringT<128> wantName;
  3065. wantName.Reference(findName);
  3066. closureTypeInst->mTypeDef->PopulateMemberSets();
  3067. BfMemberSetEntry* memberSetEntry = NULL;
  3068. if (closureTypeInst->mTypeDef->mFieldSet.TryGetWith((StringImpl&)wantName, &memberSetEntry))
  3069. {
  3070. auto fieldDef = (BfFieldDef*)memberSetEntry->mMemberDef;
  3071. while ((varSkipCount > 0) && (fieldDef != NULL))
  3072. {
  3073. fieldDef = fieldDef->mNextWithSameName;
  3074. varSkipCount--;
  3075. }
  3076. auto& field = closureTypeInst->mFieldInstances[fieldDef->mIdx];
  3077. if (!field.mResolvedType->IsValuelessType())
  3078. {
  3079. if (mModule->mCurMethodState->mClosureState->mCapturing)
  3080. {
  3081. mModule->mCurMethodState->mClosureState->mReferencedOuterClosureMembers.Add(&field);
  3082. return mModule->GetDefaultTypedValue(field.mResolvedType);
  3083. }
  3084. auto localVar = mModule->mCurMethodState->mLocals[0];
  3085. auto thisValue = localVar->mValue;
  3086. mModule->mBfIRBuilder->PopulateType(localVar->mResolvedType);
  3087. BfTypedValue result = BfTypedValue(mModule->mBfIRBuilder->CreateInBoundsGEP(thisValue, 0, field.mDataIdx), field.mResolvedType, true);
  3088. if (field.mResolvedType->IsRef())
  3089. {
  3090. auto refType = (BfRefType*)field.mResolvedType;
  3091. auto underlyingType = refType->GetUnderlyingType();
  3092. result = BfTypedValue(mModule->mBfIRBuilder->CreateLoad(result.mValue), underlyingType, true);
  3093. }
  3094. else if (fieldDef->mIsReadOnly)
  3095. result = mModule->LoadValue(result);
  3096. mResultLocalVar = localVar;
  3097. mResultFieldInstance = &field;
  3098. mResultLocalVarField = -(field.mMergedDataIdx + 1);
  3099. return result;
  3100. }
  3101. }
  3102. }
  3103. if ((checkMethodState->mClosureState != NULL) && (checkMethodState->mClosureState->mCapturing) /*&& (checkMethodState->mClosureState->mIsLocalMethod)*/)
  3104. {
  3105. checkMethodState = checkMethodState->mPrevMethodState;
  3106. continue;
  3107. }
  3108. // Allow local mixin to see outside variables during its processing -- since we don't actually "capture" those into params
  3109. bool isLocalMixinProcessing = false;
  3110. if ((checkMethodState->mClosureState != NULL) && (!checkMethodState->mClosureState->mCapturing) && (closureTypeInst == NULL) &&
  3111. (mModule->mCurMethodInstance->mMethodDef->mMethodType == BfMethodType_Mixin))
  3112. isLocalMixinProcessing = true;
  3113. if (!isLocalMixinProcessing)
  3114. break;
  3115. isMixinOuterVariablePass = true;
  3116. checkMethodState = checkMethodState->mPrevMethodState;
  3117. }
  3118. }
  3119. if ((mModule->mCurMethodInstance == NULL) && (mModule->mCurTypeInstance != NULL) && (mModule->mCurTypeInstance->IsEnum()))
  3120. {
  3121. if (findName == "_")
  3122. {
  3123. BfFieldDef* resolvingFieldDef = NULL;
  3124. auto checkTypeState = mModule->mContext->mCurTypeState;
  3125. while (checkTypeState != NULL)
  3126. {
  3127. if (checkTypeState->mCurFieldDef != NULL)
  3128. {
  3129. if (checkTypeState->mTypeInstance == mModule->mCurTypeInstance)
  3130. resolvingFieldDef = checkTypeState->mCurFieldDef;
  3131. }
  3132. checkTypeState = checkTypeState->mPrevState;
  3133. }
  3134. if ((resolvingFieldDef != NULL) && (resolvingFieldDef->mIdx > 0))
  3135. {
  3136. auto enumType = mModule->mCurTypeInstance;
  3137. if (!enumType->mFieldInstances.IsEmpty())
  3138. {
  3139. auto fieldInstance = &mModule->mCurTypeInstance->mFieldInstances[resolvingFieldDef->mIdx - 1];
  3140. if ((fieldInstance->mConstIdx != -1) &&
  3141. (fieldInstance->mResolvedType == mModule->mCurTypeInstance))
  3142. {
  3143. auto foreignConst = enumType->mConstHolder->GetConstantById(fieldInstance->mConstIdx);
  3144. auto retVal = mModule->ConstantToCurrent(foreignConst, enumType->mConstHolder, enumType);
  3145. return BfTypedValue(retVal, enumType);
  3146. }
  3147. }
  3148. }
  3149. }
  3150. }
  3151. BfTypedValue thisValue = mModule->GetThis();
  3152. bool forcedIFaceLookup = false;
  3153. if ((mModule->mCurMethodInstance != NULL) && (mModule->mCurMethodInstance->mIsForeignMethodDef))
  3154. {
  3155. thisValue.mType = mModule->mCurMethodInstance->GetForeignType();
  3156. forcedIFaceLookup = true;
  3157. }
  3158. if (thisValue)
  3159. {
  3160. if (findName == "this")
  3161. return thisValue;
  3162. if (findName == "base")
  3163. {
  3164. auto baseValue = thisValue;
  3165. if (baseValue.IsThis())
  3166. baseValue.ToBase();
  3167. if (mModule->GetActiveTypeDef()->mTypeCode != BfTypeCode_Extension)
  3168. {
  3169. MakeBaseConcrete(baseValue);
  3170. }
  3171. return baseValue;
  3172. }
  3173. if (!mModule->mCurMethodState->HasNonStaticMixin())
  3174. {
  3175. mResultLocalVar = mModule->GetThisVariable();
  3176. mResultFieldInstance = NULL;
  3177. mResultLocalVarRefNode = identifierNode;
  3178. }
  3179. }
  3180. if (!thisValue.HasType())
  3181. {
  3182. thisValue = BfTypedValue(mModule->mCurTypeInstance);
  3183. }
  3184. BfTypedValue result;
  3185. if (thisValue.HasType())
  3186. {
  3187. result = LookupField(identifierNode, thisValue, findName, BfLookupFieldFlag_IsImplicitThis);
  3188. if (mResultFieldInstance == NULL)
  3189. {
  3190. mResultLocalVar = NULL;
  3191. mResultLocalVarRefNode = NULL;
  3192. }
  3193. }
  3194. if (mPropDef != NULL)
  3195. {
  3196. if (forcedIFaceLookup)
  3197. {
  3198. if (mPropTarget == thisValue)
  3199. {
  3200. mPropDefBypassVirtual = true;
  3201. mOrigPropTarget = mModule->GetThis();
  3202. }
  3203. }
  3204. }
  3205. if ((!result) && (mPropDef == NULL))
  3206. {
  3207. if (mModule->mContext->mCurTypeState != NULL)
  3208. {
  3209. // This is not necessarily true since we changed ConstResolver
  3210. //BF_ASSERT(mModule->mCurTypeInstance == mModule->mContext->mCurTypeState->mTypeInstance);
  3211. BfGlobalLookup globalLookup;
  3212. globalLookup.mKind = BfGlobalLookup::Kind_Field;
  3213. globalLookup.mName = findName;
  3214. mModule->PopulateGlobalContainersList(globalLookup);
  3215. for (auto& globalContainer : mModule->mContext->mCurTypeState->mGlobalContainers)
  3216. {
  3217. if (globalContainer.mTypeInst == NULL)
  3218. continue;
  3219. thisValue = BfTypedValue(globalContainer.mTypeInst);
  3220. result = LookupField(identifierNode, thisValue, findName);
  3221. if ((result) || (mPropDef != NULL))
  3222. return result;
  3223. }
  3224. }
  3225. auto staticSearch = mModule->GetStaticSearch();
  3226. if (staticSearch != NULL)
  3227. {
  3228. for (auto typeInst : staticSearch->mStaticTypes)
  3229. {
  3230. thisValue = BfTypedValue(typeInst);
  3231. result = LookupField(identifierNode, thisValue, findName);
  3232. if ((result) || (mPropDef != NULL))
  3233. return result;
  3234. }
  3235. }
  3236. }
  3237. if ((!result) && (identifierNode != NULL))
  3238. result = mModule->TryLookupGenericConstVaue(identifierNode, mExpectingType);
  3239. return result;
  3240. }
  3241. BfTypedValue BfExprEvaluator::LookupIdentifier(BfIdentifierNode* identifierNode, bool ignoreInitialError, bool* hadError)
  3242. {
  3243. auto qualifiedNameNode = BfNodeDynCast<BfQualifiedNameNode>(identifierNode);
  3244. if (qualifiedNameNode != NULL)
  3245. {
  3246. LookupQualifiedName(qualifiedNameNode, ignoreInitialError, hadError);
  3247. auto qualifiedResult = mResult;
  3248. mResult = BfTypedValue();
  3249. return qualifiedResult;
  3250. }
  3251. StringT<128> identifierStr;
  3252. identifierNode->ToString(identifierStr);
  3253. return LookupIdentifier(identifierNode, identifierStr, ignoreInitialError, hadError);
  3254. }
  3255. void BfExprEvaluator::Visit(BfIdentifierNode* identifierNode)
  3256. {
  3257. auto autoComplete = GetAutoComplete();
  3258. if (autoComplete != NULL)
  3259. autoComplete->CheckIdentifier(identifierNode, true);
  3260. mResult = LookupIdentifier(identifierNode);
  3261. if ((!mResult) && (mPropDef == NULL))
  3262. {
  3263. mModule->CheckTypeRefFixit(identifierNode);
  3264. if ((autoComplete != NULL) && (autoComplete->CheckFixit(identifierNode)))
  3265. {
  3266. if (mModule->mCurMethodInstance != NULL)
  3267. {
  3268. BfType* fieldType = mExpectingType;
  3269. if (fieldType == NULL)
  3270. fieldType = mModule->mContext->mBfObjectType;
  3271. autoComplete->FixitAddMember(mModule->mCurTypeInstance, fieldType, identifierNode->ToString(), true, mModule->mCurTypeInstance);
  3272. if (!mModule->mCurMethodInstance->mMethodDef->mIsStatic)
  3273. autoComplete->FixitAddMember(mModule->mCurTypeInstance, fieldType, identifierNode->ToString(), false, mModule->mCurTypeInstance);
  3274. for (auto typeDef : mModule->mSystem->mTypeDefs)
  3275. {
  3276. if (!typeDef->mIsCombinedPartial)
  3277. continue;
  3278. if (!typeDef->IsGlobalsContainer())
  3279. continue;
  3280. typeDef->PopulateMemberSets();
  3281. String findName = identifierNode->ToString();
  3282. BfMemberSetEntry* memberSetEntry;
  3283. if ((typeDef->mMethodSet.TryGetWith(findName, &memberSetEntry)) ||
  3284. (typeDef->mFieldSet.TryGetWith(findName, &memberSetEntry)) ||
  3285. (typeDef->mPropertySet.TryGetWith(findName, &memberSetEntry)))
  3286. {
  3287. if (mModule->GetActiveTypeDef()->mProject->ContainsReference(typeDef->mProject))
  3288. autoComplete->FixitAddNamespace(identifierNode, typeDef->mNamespace.ToString());
  3289. }
  3290. }
  3291. }
  3292. }
  3293. if ((mBfEvalExprFlags & BfEvalExprFlags_NoLookupError) == 0)
  3294. mModule->Fail("Identifier not found", identifierNode);
  3295. }
  3296. }
  3297. void BfExprEvaluator::Visit(BfAttributedIdentifierNode* attrIdentifierNode)
  3298. {
  3299. if ((mModule->mAttributeState != NULL))
  3300. {
  3301. mModule->mAttributeState->mCustomAttributes = mModule->GetCustomAttributes(attrIdentifierNode->mAttributes, mModule->mAttributeState->mTarget);
  3302. VisitChild(attrIdentifierNode->mIdentifier);
  3303. }
  3304. else
  3305. {
  3306. BfAttributeState attributeState;
  3307. attributeState.mTarget = (BfAttributeTargets)(BfAttributeTargets_MemberAccess);
  3308. SetAndRestoreValue<BfAttributeState*> prevAttributeState(mModule->mAttributeState, &attributeState);
  3309. mModule->mAttributeState->mCustomAttributes = mModule->GetCustomAttributes(attrIdentifierNode->mAttributes, mModule->mAttributeState->mTarget);
  3310. VisitChild(attrIdentifierNode->mIdentifier);
  3311. }
  3312. }
  3313. static int gPropIdx = 0;
  3314. void BfExprEvaluator::FixitAddMember(BfTypeInstance* typeInst, BfType* fieldType, const StringImpl& fieldName, bool isStatic)
  3315. {
  3316. if (fieldType == NULL)
  3317. {
  3318. fieldType = mExpectingType;
  3319. }
  3320. if (fieldType != NULL)
  3321. {
  3322. if (fieldType->IsRef())
  3323. fieldType = fieldType->GetUnderlyingType();
  3324. }
  3325. mModule->mCompiler->mResolvePassData->mAutoComplete->FixitAddMember(typeInst, fieldType, fieldName, isStatic, mModule->mCurTypeInstance);
  3326. }
  3327. BfTypedValue BfExprEvaluator::LookupField(BfAstNode* targetSrc, BfTypedValue target, const StringImpl& fieldName, BfLookupFieldFlags flags)
  3328. {
  3329. if ((target.mType != NULL && (target.mType->IsGenericParam())))
  3330. {
  3331. auto genericParamInst = mModule->GetGenericParamInstance((BfGenericParamType*)target.mType);
  3332. if (target.mValue)
  3333. {
  3334. for (auto iface : genericParamInst->mInterfaceConstraints)
  3335. {
  3336. auto result = LookupField(targetSrc, BfTypedValue(target.mValue, iface), fieldName, flags);
  3337. if ((result) || (mPropDef != NULL))
  3338. {
  3339. return result;
  3340. }
  3341. }
  3342. }
  3343. if (mModule->mCurMethodInstance->mIsUnspecialized)
  3344. {
  3345. if (genericParamInst->mTypeConstraint != NULL)
  3346. target.mType = genericParamInst->mTypeConstraint;
  3347. else
  3348. target.mType = mModule->mContext->mBfObjectType;
  3349. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_Var) != 0)
  3350. {
  3351. target.mType = mModule->GetPrimitiveType(BfTypeCode_Var);
  3352. }
  3353. }
  3354. else
  3355. {
  3356. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_Var) != 0)
  3357. {
  3358. //target.mType = mModule->ResolveGenericType(mResult.mType);
  3359. }
  3360. else if (genericParamInst->mTypeConstraint != NULL)
  3361. {
  3362. target = mModule->Cast(targetSrc, target, genericParamInst->mTypeConstraint);
  3363. BF_ASSERT(target);
  3364. }
  3365. else
  3366. {
  3367. // This shouldn't occur - this would infer that we are accessing a member of Object or something...
  3368. //target.mType = mModule->ResolveGenericType(mResult.mType);
  3369. }
  3370. }
  3371. }
  3372. if ((target.mType != NULL) && (target.mType->IsVar()))
  3373. return BfTypedValue(mModule->GetDefaultValue(target.mType), target.mType, true);
  3374. BfTypeInstance* startCheckType = mModule->mCurTypeInstance;
  3375. mPropDef = NULL;
  3376. mPropDefBypassVirtual = false;
  3377. if (target)
  3378. {
  3379. if ((!target.mType->IsValueType()) && (target.IsAddr()))
  3380. target = mModule->LoadValue(target);
  3381. if (target.mType->IsPrimitiveType())
  3382. {
  3383. auto primType = (BfPrimitiveType*)target.mType;
  3384. startCheckType = mModule->GetPrimitiveStructType(primType->mTypeDef->mTypeCode);
  3385. }
  3386. else
  3387. {
  3388. startCheckType = target.mType->ToTypeInstance();
  3389. if ((startCheckType == NULL) && (target.mType->IsPointer()))
  3390. startCheckType = ((BfPointerType*) target.mType)->mElementType->ToTypeInstance();
  3391. }
  3392. //BF_ASSERT(startCheckType != NULL);
  3393. }
  3394. else if (target.mType != NULL)
  3395. {
  3396. startCheckType = target.mType->ToTypeInstance();
  3397. }
  3398. if ((startCheckType != NULL) && (startCheckType->mBaseType == NULL))
  3399. {
  3400. if (startCheckType->mDefineState == BfTypeDefineState_ResolvingBaseType)
  3401. {
  3402. // Fixes cases where we have something like 'Base[Value]' as a base typeref
  3403. return BfTypedValue();
  3404. }
  3405. mModule->PopulateType(startCheckType, BfPopulateType_BaseType);
  3406. }
  3407. String findName;
  3408. int varSkipCount = 0;
  3409. if (fieldName.StartsWith('@'))
  3410. {
  3411. findName = fieldName;
  3412. while (findName.StartsWith('@'))
  3413. {
  3414. findName.Remove(0);
  3415. varSkipCount++;
  3416. }
  3417. }
  3418. else
  3419. findName.Reference(fieldName);
  3420. auto activeTypeDef = mModule->GetActiveTypeDef();
  3421. for (int pass = 0; pass < 2; pass++)
  3422. {
  3423. auto curCheckType = startCheckType;
  3424. bool isFailurePass = pass == 1;
  3425. bool isBaseLookup = false;
  3426. while (curCheckType != NULL)
  3427. {
  3428. curCheckType->mTypeDef->PopulateMemberSets();
  3429. BfFieldDef* nextField = NULL;
  3430. BfMemberSetEntry* entry;
  3431. if (curCheckType->mTypeDef->mFieldSet.TryGetWith(findName, &entry))
  3432. nextField = (BfFieldDef*)entry->mMemberDef;
  3433. while ((varSkipCount > 0) && (nextField != NULL))
  3434. {
  3435. nextField = nextField->mNextWithSameName;
  3436. }
  3437. BfProtectionCheckFlags protectionCheckFlags = BfProtectionCheckFlag_None;
  3438. if (target)
  3439. {
  3440. if ((flags & (BfLookupFieldFlag_IsImplicitThis | BfLookupFieldFlag_BaseLookup)) != 0)
  3441. {
  3442. // Not an "instance lookup"
  3443. }
  3444. else
  3445. {
  3446. protectionCheckFlags = (BfProtectionCheckFlags)(protectionCheckFlags | BfProtectionCheckFlag_InstanceLookup);
  3447. }
  3448. }
  3449. BfFieldDef* matchedField = NULL;
  3450. while (nextField != NULL)
  3451. {
  3452. if ((flags & BfLookupFieldFlag_BindOnly) != 0)
  3453. break;
  3454. auto field = nextField;
  3455. nextField = nextField->mNextWithSameName;
  3456. if (((flags & BfLookupFieldFlag_IgnoreProtection) == 0) && (!isFailurePass) &&
  3457. (!mModule->CheckProtection(protectionCheckFlags, curCheckType, field->mDeclaringType->mProject, field->mProtection, startCheckType)))
  3458. {
  3459. continue;
  3460. }
  3461. bool isResolvingFields = curCheckType->mResolvingConstField || curCheckType->mResolvingVarField;
  3462. if (curCheckType->mFieldInstances.IsEmpty())
  3463. {
  3464. mModule->PopulateType(curCheckType, BfPopulateType_Data);
  3465. }
  3466. BF_ASSERT(field->mIdx < (int)curCheckType->mFieldInstances.size());
  3467. auto fieldInstance = &curCheckType->mFieldInstances[field->mIdx];
  3468. if (!fieldInstance->mFieldIncluded)
  3469. continue;
  3470. if (curCheckType->IsUnspecializedType())
  3471. {
  3472. // The check for non-unspecialized types is already handled in mFieldIncluded
  3473. if (!curCheckType->IsTypeMemberIncluded(field->mDeclaringType, activeTypeDef, mModule))
  3474. continue;
  3475. }
  3476. if (!curCheckType->IsTypeMemberAccessible(field->mDeclaringType, activeTypeDef))
  3477. continue;
  3478. if (matchedField != NULL)
  3479. {
  3480. auto error = mModule->Fail(StrFormat("Ambiguous reference to field '%s.%s'", mModule->TypeToString(curCheckType).c_str(), fieldName.c_str()), targetSrc);
  3481. if (error != NULL)
  3482. {
  3483. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("See field declaration in project '%s'", matchedField->mDeclaringType->mProject->mName.c_str()), matchedField->mFieldDeclaration);
  3484. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("See field declaration in project '%s'", field->mDeclaringType->mProject->mName.c_str()), field->mFieldDeclaration);
  3485. break;
  3486. }
  3487. }
  3488. matchedField = field;
  3489. }
  3490. if (matchedField != NULL)
  3491. {
  3492. auto field = matchedField;
  3493. auto fieldInstance = &curCheckType->mFieldInstances[field->mIdx];
  3494. bool isResolvingFields = curCheckType->mResolvingConstField || curCheckType->mResolvingVarField;
  3495. if (field->mIsVolatile)
  3496. mIsVolatileReference = true;
  3497. if (isFailurePass)
  3498. {
  3499. mModule->Fail(StrFormat("'%s.%s' is inaccessible due to its protection level", mModule->TypeToString(curCheckType).c_str(), field->mName.c_str()), targetSrc);
  3500. }
  3501. auto resolvePassData = mModule->mCompiler->mResolvePassData;
  3502. if ((resolvePassData != NULL) && (resolvePassData->mGetSymbolReferenceKind == BfGetSymbolReferenceKind_Field))
  3503. {
  3504. resolvePassData->HandleFieldReference(targetSrc, curCheckType->mTypeDef, field);
  3505. }
  3506. if ((!curCheckType->mTypeFailed) && (!isResolvingFields) && (curCheckType->IsIncomplete()))
  3507. {
  3508. if ((fieldInstance->mResolvedType == NULL) ||
  3509. (!field->mIsStatic))
  3510. mModule->PopulateType(curCheckType, BfPopulateType_Data);
  3511. }
  3512. if (fieldInstance->mResolvedType == NULL)
  3513. {
  3514. BF_ASSERT((curCheckType->mTypeFailed) || (isResolvingFields));
  3515. return BfTypedValue();
  3516. }
  3517. if (fieldInstance->mFieldIdx == -1)
  3518. {
  3519. mModule->AssertErrorState();
  3520. return BfTypedValue();
  3521. }
  3522. mResultFieldInstance = fieldInstance;
  3523. // Are we accessing a 'var' field that has not yet been resolved?
  3524. if (fieldInstance->mResolvedType->IsVar())
  3525. {
  3526. // This can happen if we have one var field referencing another var field
  3527. fieldInstance->mResolvedType = mModule->ResolveVarFieldType(curCheckType, fieldInstance, field);
  3528. if (fieldInstance->mResolvedType == NULL)
  3529. return BfTypedValue();
  3530. }
  3531. auto resolvedFieldType = fieldInstance->mResolvedType;
  3532. if (fieldInstance->mIsEnumPayloadCase)
  3533. {
  3534. resolvedFieldType = curCheckType;
  3535. }
  3536. mModule->PopulateType(resolvedFieldType, BfPopulateType_Data);
  3537. mModule->AddDependency(curCheckType, mModule->mCurTypeInstance, BfDependencyMap::DependencyFlag_ReadFields);
  3538. auto autoComplete = GetAutoComplete();
  3539. if (autoComplete != NULL)
  3540. {
  3541. autoComplete->CheckFieldRef(BfNodeDynCast<BfIdentifierNode>(targetSrc), fieldInstance);
  3542. if ((autoComplete->mResolveType == BfResolveType_GetResultString) && (autoComplete->IsAutocompleteNode(targetSrc)))
  3543. {
  3544. autoComplete->mResultString = ":";
  3545. autoComplete->mResultString += mModule->TypeToString(fieldInstance->mResolvedType);
  3546. autoComplete->mResultString += " ";
  3547. autoComplete->mResultString += mModule->TypeToString(curCheckType);
  3548. autoComplete->mResultString += ".";
  3549. autoComplete->mResultString += field->mName;
  3550. if (fieldInstance->mConstIdx != -1)
  3551. {
  3552. String constStr = autoComplete->ConstantToString(curCheckType->mConstHolder, BfIRValue(BfIRValueFlags_Const, fieldInstance->mConstIdx));
  3553. if (!constStr.IsEmpty())
  3554. {
  3555. autoComplete->mResultString += " = ";
  3556. if (constStr.StartsWith(':'))
  3557. autoComplete->mResultString.Append(StringView(constStr, 1, constStr.mLength - 1));
  3558. else
  3559. autoComplete->mResultString += constStr;
  3560. }
  3561. }
  3562. auto fieldDecl = fieldInstance->GetFieldDef()->mFieldDeclaration;
  3563. if ((fieldDecl != NULL) && (fieldDecl->mDocumentation != NULL))
  3564. {
  3565. String docString;
  3566. fieldDecl->mDocumentation->GetDocString(docString);
  3567. autoComplete->mResultString += "\x03";
  3568. autoComplete->mResultString += docString;
  3569. }
  3570. }
  3571. }
  3572. if (field->mIsStatic)
  3573. {
  3574. if ((target) && ((flags & BfLookupFieldFlag_IsImplicitThis) == 0) && (!curCheckType->mTypeDef->IsGlobalsContainer()))
  3575. {
  3576. //CS0176: Member 'Program.sVal' cannot be accessed with an instance reference; qualify it with a type name instead
  3577. mModule->Fail(StrFormat("Member '%s.%s' cannot be accessed with an instance reference; qualify it with a type name instead",
  3578. mModule->TypeToString(curCheckType).c_str(), field->mName.c_str()), targetSrc);
  3579. }
  3580. // Target must be an implicit 'this', or an error (accessing a static with a non-static target).
  3581. // Not actually needed in either case since this is a static lookup.
  3582. mResultLocalVar = NULL;
  3583. }
  3584. bool isConst = false;
  3585. if (field->mIsConst)
  3586. {
  3587. isConst = true;
  3588. auto fieldDef = fieldInstance->GetFieldDef();
  3589. if ((resolvedFieldType->IsPointer()) && (fieldDef->mIsExtern))
  3590. isConst = false;
  3591. }
  3592. if (resolvedFieldType->IsValuelessType())
  3593. {
  3594. return BfTypedValue(BfIRValue::sValueless, resolvedFieldType, true);
  3595. }
  3596. if (isConst)
  3597. {
  3598. if (fieldInstance->mIsEnumPayloadCase)
  3599. {
  3600. auto dscrType = curCheckType->GetDiscriminatorType();
  3601. mModule->mBfIRBuilder->PopulateType(curCheckType);
  3602. int tagIdx = -fieldInstance->mDataIdx - 1;
  3603. if ((mBfEvalExprFlags & BfEvalExprFlags_AllowEnumId) != 0)
  3604. {
  3605. return BfTypedValue(mModule->mBfIRBuilder->CreateConst(dscrType->mTypeDef->mTypeCode, tagIdx), fieldInstance->mOwner);
  3606. }
  3607. mModule->PopulateType(fieldInstance->mOwner, BfPopulateType_Data);
  3608. // auto agg = mModule->mBfIRBuilder->CreateUndefValue(mModule->mBfIRBuilder->MapType(fieldInstance->mOwner));
  3609. // agg = mModule->mBfIRBuilder->CreateInsertValue(agg, mModule->mBfIRBuilder->CreateConst(dscrType->mTypeDef->mTypeCode, tagIdx), 2);
  3610. //
  3611. // if (fieldInstance->mResolvedType->mSize != 0)
  3612. // {
  3613. // mModule->FailAfter("Enum case parameters expected", targetSrc);
  3614. // }
  3615. //
  3616. // return BfTypedValue(agg, fieldInstance->mOwner);
  3617. auto agg = mModule->CreateAlloca(fieldInstance->mOwner);
  3618. auto gep = mModule->mBfIRBuilder->CreateInBoundsGEP(agg, 0, 2);
  3619. mModule->mBfIRBuilder->CreateStore(mModule->mBfIRBuilder->CreateConst(dscrType->mTypeDef->mTypeCode, tagIdx), gep);
  3620. if (fieldInstance->mResolvedType->mSize != 0)
  3621. {
  3622. mModule->FailAfter("Enum case parameters expected", targetSrc);
  3623. }
  3624. return BfTypedValue(agg, fieldInstance->mOwner, true);
  3625. }
  3626. if (fieldInstance->mConstIdx == -1)
  3627. {
  3628. curCheckType->mModule->ResolveConstField(curCheckType, fieldInstance, field);
  3629. if (fieldInstance->mConstIdx == -1)
  3630. return BfTypedValue(mModule->GetDefaultValue(resolvedFieldType), resolvedFieldType);
  3631. }
  3632. BF_ASSERT(fieldInstance->mConstIdx != -1);
  3633. auto foreignConst = curCheckType->mConstHolder->GetConstantById(fieldInstance->mConstIdx);
  3634. auto retVal = mModule->ConstantToCurrent(foreignConst, curCheckType->mConstHolder, resolvedFieldType);
  3635. return BfTypedValue(retVal, resolvedFieldType);
  3636. }
  3637. else if (field->mIsStatic)
  3638. {
  3639. mModule->CheckStaticAccess(curCheckType);
  3640. auto retVal = mModule->ReferenceStaticField(fieldInstance);
  3641. bool isStaticCtor = (mModule->mCurMethodInstance != NULL) && (mModule->mCurMethodInstance->mMethodDef->mMethodType == BfMethodType_Ctor) &&
  3642. (mModule->mCurMethodInstance->mMethodDef->mIsStatic);
  3643. if ((field->mIsReadOnly) && (!isStaticCtor))
  3644. {
  3645. if (retVal.IsAddr())
  3646. retVal.mKind = BfTypedValueKind_ReadOnlyAddr;
  3647. }
  3648. else
  3649. mIsHeapReference = true;
  3650. return retVal;
  3651. }
  3652. else if (!target)
  3653. {
  3654. if ((flags & BfLookupFieldFlag_CheckingOuter) != 0)
  3655. 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()),
  3656. targetSrc);
  3657. else if ((mModule->mCurMethodInstance != NULL) && (mModule->mCurMethodInstance->mMethodDef->mMethodType == BfMethodType_CtorCalcAppend))
  3658. mModule->Fail(StrFormat("Cannot reference field '%s' before append allocations", field->mName.c_str()), targetSrc);
  3659. else
  3660. mModule->Fail(StrFormat("Cannot reference non-static field '%s' from a static method", field->mName.c_str()), targetSrc);
  3661. return mModule->GetDefaultTypedValue(resolvedFieldType, false, BfDefaultValueKind_Addr);
  3662. }
  3663. if ((mResultLocalVar != NULL) && (fieldInstance->mMergedDataIdx != -1))
  3664. {
  3665. fieldInstance->GetDataRange(mResultLocalVarField, mResultLocalVarFieldCount);
  3666. mResultLocalVarRefNode = targetSrc;
  3667. }
  3668. if ((curCheckType->IsIncomplete()) && (!curCheckType->mNeedsMethodProcessing))
  3669. {
  3670. BF_ASSERT(curCheckType->mTypeFailed || (mModule->mCurMethodState == NULL) || (mModule->mCurMethodState->mTempKind != BfMethodState::TempKind_None) || (mModule->mCompiler->IsAutocomplete()));
  3671. return mModule->GetDefaultTypedValue(resolvedFieldType);
  3672. }
  3673. bool isTemporary = target.IsTempAddr();
  3674. bool wantsLoadValue = false;
  3675. bool wantsReadOnly = false;
  3676. if ((field->mIsReadOnly) && (mModule->mCurMethodInstance != NULL) && ((mModule->mCurMethodInstance->mMethodDef->mMethodType != BfMethodType_Ctor) || (!target.IsThis())))
  3677. wantsReadOnly = true;
  3678. bool isComposite = target.mType->IsComposite();
  3679. if ((isComposite) && (!target.mType->IsTypedPrimitive()) && (!target.IsAddr()))
  3680. isTemporary = true;
  3681. if ((isComposite) && (!target.IsAddr()))
  3682. wantsLoadValue = true;
  3683. if ((target.mType->IsWrappableType()) && (!target.mType->IsPointer()))
  3684. {
  3685. BfTypeInstance* primStructType = mModule->GetWrappedStructType(target.mType);
  3686. BfIRValue allocaInst = mModule->CreateAlloca(primStructType, true, "tmpStruct");
  3687. BfIRValue elementAddr = mModule->mBfIRBuilder->CreateInBoundsGEP(allocaInst, 0, 1);
  3688. mModule->mBfIRBuilder->CreateStore(target.mValue, elementAddr);
  3689. target = BfTypedValue(allocaInst, primStructType, true);
  3690. }
  3691. BfTypedValue targetValue;
  3692. if ((isBaseLookup) && (!target.IsSplat()))
  3693. {
  3694. if ((!isComposite) || (target.IsAddr()))
  3695. targetValue = BfTypedValue(mModule->mBfIRBuilder->CreateBitCast(target.mValue, mModule->mBfIRBuilder->MapTypeInstPtr(curCheckType)), curCheckType);
  3696. else
  3697. {
  3698. BfIRValue curVal = target.mValue;
  3699. auto baseCheckType = target.mType->ToTypeInstance();
  3700. while (baseCheckType != curCheckType)
  3701. {
  3702. curVal = mModule->mBfIRBuilder->CreateExtractValue(curVal, 0);
  3703. baseCheckType = baseCheckType->mBaseType;
  3704. }
  3705. targetValue = BfTypedValue(curVal, curCheckType);
  3706. }
  3707. }
  3708. else
  3709. targetValue = target;
  3710. bool doAccessCheck = true;
  3711. if ((mModule->mAttributeState != NULL) && (mModule->mAttributeState->mCustomAttributes != NULL) && (mModule->mAttributeState->mCustomAttributes->Contains(mModule->mCompiler->mDisableObjectAccessChecksAttributeTypeDef)))
  3712. doAccessCheck = false;
  3713. if (target.IsThis())
  3714. {
  3715. if (!mModule->mCurMethodState->mMayNeedThisAccessCheck)
  3716. doAccessCheck = false;
  3717. }
  3718. if (doAccessCheck)
  3719. mModule->EmitObjectAccessCheck(target);
  3720. if (fieldInstance->mDataIdx < 0)
  3721. {
  3722. BF_ASSERT(curCheckType->mTypeFailed);
  3723. return mModule->GetDefaultTypedValue(resolvedFieldType);
  3724. }
  3725. BfTypedValue retVal;
  3726. if (target.IsSplat())
  3727. {
  3728. retVal = mModule->ExtractValue(targetValue, fieldInstance, fieldInstance->mDataIdx);
  3729. }
  3730. else if ((target.mType->IsStruct()) && (!target.IsAddr()))
  3731. {
  3732. mModule->mBfIRBuilder->PopulateType(targetValue.mType);
  3733. retVal = BfTypedValue(mModule->mBfIRBuilder->CreateExtractValue(targetValue.mValue, fieldInstance->mDataIdx/*, field->mName*/),
  3734. resolvedFieldType);
  3735. }
  3736. else
  3737. {
  3738. mModule->mBfIRBuilder->PopulateType(curCheckType);
  3739. if ((targetValue.IsAddr()) && (!curCheckType->IsValueType()))
  3740. targetValue = mModule->LoadValue(targetValue);
  3741. retVal = BfTypedValue(mModule->mBfIRBuilder->CreateInBoundsGEP(targetValue.mValue, 0, fieldInstance->mDataIdx/*, field->mName*/),
  3742. resolvedFieldType, target.IsReadOnly() ? BfTypedValueKind_ReadOnlyAddr : BfTypedValueKind_Addr);
  3743. }
  3744. if (!retVal.IsSplat())
  3745. {
  3746. if (curCheckType->mIsUnion)
  3747. {
  3748. BfIRType llvmPtrType = mModule->mBfIRBuilder->GetPointerTo(mModule->mBfIRBuilder->MapType(resolvedFieldType));
  3749. retVal.mValue = mModule->mBfIRBuilder->CreateBitCast(retVal.mValue, llvmPtrType);
  3750. }
  3751. }
  3752. if (wantsLoadValue)
  3753. retVal = mModule->LoadValue(retVal, NULL, mIsVolatileReference);
  3754. else
  3755. {
  3756. if ((wantsReadOnly) && (retVal.IsAddr())&& (!retVal.IsReadOnly()))
  3757. retVal.mKind = BfTypedValueKind_ReadOnlyAddr;
  3758. mIsHeapReference = true;
  3759. }
  3760. if (isTemporary)
  3761. {
  3762. if (retVal.IsAddr())
  3763. retVal.mKind = BfTypedValueKind_TempAddr;
  3764. }
  3765. return retVal;
  3766. }
  3767. BfPropertyDef* nextProp = NULL;
  3768. if (curCheckType->mTypeDef->mPropertySet.TryGetWith(fieldName, &entry))
  3769. nextProp = (BfPropertyDef*)entry->mMemberDef;
  3770. if (nextProp != NULL)
  3771. {
  3772. BfCheckedKind checkedKind = BfCheckedKind_NotSet;
  3773. bool isInlined = false;
  3774. if ((mModule->mAttributeState != NULL) && (mModule->mAttributeState->mCustomAttributes != NULL))
  3775. {
  3776. if (mModule->mAttributeState->mCustomAttributes->Contains(mModule->mCompiler->mInlineAttributeTypeDef))
  3777. {
  3778. isInlined = true;
  3779. mModule->mAttributeState->mUsed = true;
  3780. }
  3781. if (mModule->mAttributeState->mCustomAttributes->Contains(mModule->mCompiler->mCheckedAttributeTypeDef))
  3782. {
  3783. checkedKind = BfCheckedKind_Checked;
  3784. mModule->mAttributeState->mUsed = true;
  3785. }
  3786. if (mModule->mAttributeState->mCustomAttributes->Contains(mModule->mCompiler->mUncheckedAttributeTypeDef))
  3787. {
  3788. checkedKind = BfCheckedKind_Unchecked;
  3789. mModule->mAttributeState->mUsed = true;
  3790. }
  3791. }
  3792. BfPropertyDef* matchedProp = NULL;
  3793. while (nextProp != NULL)
  3794. {
  3795. auto prop = nextProp;
  3796. nextProp = nextProp->mNextWithSameName;
  3797. if ((!isFailurePass) && (!mModule->CheckProtection(protectionCheckFlags, curCheckType, prop->mDeclaringType->mProject, prop->mProtection, startCheckType)))
  3798. {
  3799. continue;
  3800. }
  3801. if (!prop->mMethods.IsEmpty())
  3802. {
  3803. BfMethodDef* checkMethod = prop->mMethods[0];;
  3804. // Properties with explicit interfaces or marked as overrides can only be called indirectly
  3805. if ((checkMethod->mExplicitInterface != NULL) || (checkMethod->mIsOverride))
  3806. continue;
  3807. }
  3808. if ((!target.IsStatic()) || (prop->mIsStatic))
  3809. {
  3810. if ((!curCheckType->IsTypeMemberIncluded(prop->mDeclaringType, activeTypeDef, mModule)) ||
  3811. (!curCheckType->IsTypeMemberAccessible(prop->mDeclaringType, activeTypeDef)))
  3812. continue;
  3813. if (matchedProp != NULL)
  3814. {
  3815. auto error = mModule->Fail(StrFormat("Ambiguous reference to property '%s.%s'", mModule->TypeToString(curCheckType).c_str(), fieldName.c_str()), targetSrc);
  3816. if (error != NULL)
  3817. {
  3818. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("See property declaration in project '%s'", matchedProp->mDeclaringType->mProject->mName.c_str()), matchedProp->mFieldDeclaration);
  3819. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("See property declaration in project '%s'", prop->mDeclaringType->mProject->mName.c_str()), prop->mFieldDeclaration);
  3820. break;
  3821. }
  3822. }
  3823. matchedProp = prop;
  3824. }
  3825. }
  3826. if (matchedProp != NULL)
  3827. {
  3828. auto prop = matchedProp;
  3829. gPropIdx++;
  3830. mModule->SetElementType(targetSrc, BfSourceElementType_Method);
  3831. mPropSrc = targetSrc;
  3832. mPropDef = prop;
  3833. mPropCheckedKind = checkedKind;
  3834. if (isInlined)
  3835. mPropGetMethodFlags = (BfGetMethodInstanceFlags)(mPropGetMethodFlags | BfGetMethodInstanceFlag_ForceInline);
  3836. if ((mModule->mAttributeState != NULL) && (mModule->mAttributeState->mCustomAttributes != NULL))
  3837. {
  3838. if (mModule->mAttributeState->mCustomAttributes->Contains(mModule->mCompiler->mFriendAttributeTypeDef))
  3839. {
  3840. mPropGetMethodFlags = (BfGetMethodInstanceFlags)(mPropGetMethodFlags | BfGetMethodInstanceFlag_Friend);
  3841. mModule->mAttributeState->mUsed = true;
  3842. }
  3843. if (mModule->mAttributeState->mCustomAttributes->Contains(mModule->mCompiler->mDisableObjectAccessChecksAttributeTypeDef))
  3844. {
  3845. mPropGetMethodFlags = (BfGetMethodInstanceFlags)(mPropGetMethodFlags | BfGetMethodInstanceFlag_DisableObjectAccessChecks);
  3846. mModule->mAttributeState->mUsed = true;
  3847. }
  3848. }
  3849. if (mPropDef->mIsStatic)
  3850. {
  3851. if ((target) && ((flags & BfLookupFieldFlag_IsImplicitThis) == 0) && (!curCheckType->mTypeDef->IsGlobalsContainer()))
  3852. {
  3853. //CS0176: Member 'Program.sVal' cannot be accessed with an instance reference; qualify it with a type name instead
  3854. mModule->Fail(StrFormat("Property '%s.%s' cannot be accessed with an instance reference; qualify it with a type name instead",
  3855. mModule->TypeToString(curCheckType).c_str(), mPropDef->mName.c_str()), targetSrc);
  3856. }
  3857. }
  3858. if (prop->mIsStatic)
  3859. mPropTarget = BfTypedValue(curCheckType);
  3860. else if (isBaseLookup)
  3861. {
  3862. mPropTarget = mModule->Cast(targetSrc, target, curCheckType);
  3863. BF_ASSERT(mPropTarget);
  3864. }
  3865. else
  3866. mPropTarget = target;
  3867. if (mPropTarget.mType->IsStructPtr())
  3868. {
  3869. mPropTarget = mModule->LoadValue(mPropTarget);
  3870. mPropTarget = BfTypedValue(mPropTarget.mValue, mPropTarget.mType->GetUnderlyingType(), mPropTarget.IsReadOnly() ? BfTypedValueKind_ReadOnlyAddr : BfTypedValueKind_Addr);
  3871. }
  3872. mOrigPropTarget = mPropTarget;
  3873. auto autoComplete = GetAutoComplete();
  3874. auto resolvePassData = mModule->mCompiler->mResolvePassData;
  3875. if (((autoComplete != NULL) && (autoComplete->mIsGetDefinition)) ||
  3876. ((resolvePassData != NULL) && (resolvePassData->mGetSymbolReferenceKind == BfGetSymbolReferenceKind_Property)))
  3877. {
  3878. BfPropertyDef* basePropDef = mPropDef;
  3879. BfTypeInstance* baseTypeInst = curCheckType;
  3880. mModule->GetBasePropertyDef(basePropDef, baseTypeInst);
  3881. resolvePassData->HandlePropertyReference(targetSrc, baseTypeInst->mTypeDef, basePropDef);
  3882. if ((autoComplete != NULL) && (autoComplete->IsAutocompleteNode(targetSrc)))
  3883. {
  3884. if (autoComplete->mIsGetDefinition)
  3885. autoComplete->SetDefinitionLocation(basePropDef->GetRefNode(), true);
  3886. autoComplete->mDefProp = basePropDef;
  3887. autoComplete->mDefType = baseTypeInst->mTypeDef;
  3888. }
  3889. }
  3890. if ((autoComplete != NULL) && (autoComplete->mResolveType == BfResolveType_GetResultString) && (autoComplete->IsAutocompleteNode(targetSrc)))
  3891. {
  3892. BfPropertyDef* basePropDef = mPropDef;
  3893. BfTypeInstance* baseTypeInst = curCheckType;
  3894. mModule->GetBasePropertyDef(basePropDef, baseTypeInst);
  3895. autoComplete->mResultString = ":";
  3896. autoComplete->mResultString += mModule->TypeToString(baseTypeInst);
  3897. autoComplete->mResultString += ".";
  3898. autoComplete->mResultString += basePropDef->mName;
  3899. }
  3900. // Check for direct auto-property access
  3901. if (startCheckType == mModule->mCurTypeInstance)
  3902. {
  3903. if (auto propertyDeclaration = BfNodeDynCast<BfPropertyDeclaration>(mPropDef->mFieldDeclaration))
  3904. {
  3905. if ((curCheckType->mTypeDef->HasAutoProperty(propertyDeclaration)) && (propertyDeclaration->mVirtualSpecifier == NULL))
  3906. {
  3907. bool hasSetter = GetPropertyMethodDef(mPropDef, BfMethodType_PropertySetter, BfCheckedKind_NotSet, mPropTarget) != NULL;
  3908. auto autoFieldName = curCheckType->mTypeDef->GetAutoPropertyName(propertyDeclaration);
  3909. auto result = LookupField(targetSrc, target, autoFieldName, BfLookupFieldFlag_IgnoreProtection);
  3910. if (result)
  3911. {
  3912. if (!hasSetter)
  3913. {
  3914. if (((mModule->mCurMethodInstance->mMethodDef->mMethodType == BfMethodType_Ctor)) &&
  3915. (startCheckType == mModule->mCurTypeInstance))
  3916. {
  3917. // Allow writing inside ctor
  3918. }
  3919. else
  3920. result.MakeReadOnly();
  3921. }
  3922. mPropDef = NULL;
  3923. mPropSrc = NULL;
  3924. mOrigPropTarget = NULL;
  3925. return result;
  3926. }
  3927. }
  3928. }
  3929. }
  3930. SetAndRestoreValue<BfTypedValue> prevResult(mResult, target);
  3931. CheckResultForReading(mResult);
  3932. return BfTypedValue();
  3933. }
  3934. }
  3935. isBaseLookup = true;
  3936. curCheckType = curCheckType->mBaseType;
  3937. }
  3938. }
  3939. auto outerTypeDef = mModule->GetOuterType(startCheckType);
  3940. if (outerTypeDef != NULL)
  3941. {
  3942. // Check statics in outer type
  3943. return LookupField(targetSrc, BfTypedValue(outerTypeDef), fieldName, BfLookupFieldFlag_CheckingOuter);
  3944. }
  3945. return BfTypedValue();
  3946. }
  3947. void BfExprEvaluator::ResolveArgValues(BfResolvedArgs& resolvedArgs, BfResolveArgFlags flags)
  3948. {
  3949. static int idx = 0;
  3950. idx++;
  3951. int curIdx = idx;
  3952. if (resolvedArgs.mArguments == NULL)
  3953. return;
  3954. int argCount = (int)resolvedArgs.mArguments->size();
  3955. if ((resolvedArgs.mCommas != NULL) && (resolvedArgs.mCommas->size() != 0) && (resolvedArgs.mCommas->size() >= resolvedArgs.mArguments->size()))
  3956. {
  3957. //mModule->FailAfter("Expression expected", resolvedArgs.mCommas->back());
  3958. argCount++;
  3959. }
  3960. BfAutoComplete* autoComplete = GetAutoComplete();
  3961. bool hadIgnoredFixits = false;
  3962. if (autoComplete != NULL)
  3963. {
  3964. hadIgnoredFixits = autoComplete->mIgnoreFixits;
  3965. if (flags & BfResolveArgFlag_DeferFixits)
  3966. autoComplete->mIgnoreFixits = true;
  3967. }
  3968. int deferredArgIdx = 0;
  3969. SizedArray<BfExpression*, 8> deferredArgs;
  3970. int argIdx = 0;
  3971. //for (int argIdx = 0; argIdx < argCount ; argIdx++)
  3972. while (true)
  3973. {
  3974. //printf("Args: %p %p %d\n", resolvedArgs.mArguments, resolvedArgs.mArguments->mVals, resolvedArgs.mArguments->mSize);
  3975. BfExpression* argExpr = NULL;
  3976. bool isDeferredArg = false;
  3977. int curArgIdx = -1;
  3978. if (deferredArgIdx < deferredArgs.size())
  3979. {
  3980. argExpr = deferredArgs[deferredArgIdx++];
  3981. isDeferredArg = true;
  3982. }
  3983. else if (argIdx >= argCount)
  3984. {
  3985. break;
  3986. }
  3987. else
  3988. {
  3989. curArgIdx = argIdx++;
  3990. if (curArgIdx < resolvedArgs.mArguments->size())
  3991. argExpr = (*resolvedArgs.mArguments)[curArgIdx];
  3992. }
  3993. if (argExpr == NULL)
  3994. {
  3995. if (curArgIdx == 0)
  3996. {
  3997. if (resolvedArgs.mOpenToken != NULL)
  3998. mModule->FailAfter("Expression expected", resolvedArgs.mOpenToken);
  3999. }
  4000. else if (resolvedArgs.mCommas != NULL)
  4001. mModule->FailAfter("Expression expected", (*resolvedArgs.mCommas)[curArgIdx - 1]);
  4002. }
  4003. if (auto typedValueExpr = BfNodeDynCast<BfTypedValueExpression>(argExpr))
  4004. {
  4005. BfResolvedArg resolvedArg;
  4006. resolvedArg.mTypedValue = typedValueExpr->mTypedValue;
  4007. resolvedArg.mExpression = typedValueExpr->mRefNode;
  4008. resolvedArgs.mResolvedArgs.push_back(resolvedArg);
  4009. continue;
  4010. }
  4011. BfResolvedArg resolvedArg;
  4012. if (isDeferredArg)
  4013. resolvedArg.mArgFlags = (BfArgFlags)(resolvedArg.mArgFlags | BfArgFlag_StringInterpolateArg);
  4014. BfExprEvaluator exprEvaluator(mModule);
  4015. exprEvaluator.mResolveGenericParam = (flags & BfResolveArgFlag_AllowUnresolvedTypes) == 0;
  4016. exprEvaluator.mBfEvalExprFlags = (BfEvalExprFlags)(exprEvaluator.mBfEvalExprFlags | BfEvalExprFlags_AllowRefExpr | BfEvalExprFlags_AllowOutExpr);
  4017. bool handled = false;
  4018. bool evaluated = false;
  4019. if (auto interpolateExpr = BfNodeDynCastExact<BfStringInterpolationExpression>(argExpr))
  4020. {
  4021. if ((interpolateExpr->mAllocNode == NULL) || ((flags & BfResolveArgFlag_InsideStringInterpolationAlloc) != 0))
  4022. {
  4023. resolvedArg.mArgFlags = (BfArgFlags)(resolvedArg.mArgFlags | BfArgFlag_StringInterpolateFormat);
  4024. for (auto innerExpr : interpolateExpr->mExpressions)
  4025. deferredArgs.Add(innerExpr);
  4026. }
  4027. }
  4028. bool deferParamEval = false;
  4029. if ((flags & BfResolveArgFlag_DeferParamEval) != 0)
  4030. {
  4031. if (argExpr != NULL)
  4032. {
  4033. BfDeferEvalChecker deferEvalChecker;
  4034. argExpr->Accept(&deferEvalChecker);
  4035. deferParamEval = deferEvalChecker.mNeedsDeferEval;
  4036. }
  4037. }
  4038. if (deferParamEval)
  4039. {
  4040. resolvedArg.mArgFlags = (BfArgFlags)(resolvedArg.mArgFlags | BfArgFlag_DeferredEval);
  4041. handled = true;
  4042. }
  4043. else if (auto delegateBindExpression = BfNodeDynCast<BfDelegateBindExpression>(argExpr))
  4044. {
  4045. resolvedArg.mArgFlags = (BfArgFlags)(resolvedArg.mArgFlags | BfArgFlag_DelegateBindAttempt);
  4046. handled = true;
  4047. }
  4048. else if (auto lambdaBindExpression = BfNodeDynCast<BfLambdaBindExpression>(argExpr))
  4049. {
  4050. resolvedArg.mArgFlags = (BfArgFlags)(resolvedArg.mArgFlags | BfArgFlag_LambdaBindAttempt);
  4051. handled = true;
  4052. }
  4053. else if (auto memberRef = BfNodeDynCast<BfMemberReferenceExpression>(argExpr))
  4054. {
  4055. if (memberRef->mTarget == NULL)
  4056. {
  4057. resolvedArg.mArgFlags = (BfArgFlags)(resolvedArg.mArgFlags | BfArgFlag_UnqualifiedDotAttempt);
  4058. handled = true;
  4059. }
  4060. }
  4061. else if (auto invokeExpr = BfNodeDynCast<BfInvocationExpression>(argExpr))
  4062. {
  4063. if (auto memberRef = BfNodeDynCast<BfMemberReferenceExpression>(invokeExpr->mTarget))
  4064. {
  4065. if (memberRef->mTarget == NULL)
  4066. {
  4067. resolvedArg.mArgFlags = (BfArgFlags)(resolvedArg.mArgFlags | BfArgFlag_UnqualifiedDotAttempt);
  4068. handled = true;
  4069. }
  4070. }
  4071. }
  4072. else if (auto defaultExpr = BfNodeDynCast<BfDefaultExpression>(argExpr))
  4073. {
  4074. if (defaultExpr->mTypeRef == NULL)
  4075. {
  4076. resolvedArg.mArgFlags = (BfArgFlags)(resolvedArg.mArgFlags | BfArgFlag_UntypedDefault);
  4077. handled = true;
  4078. }
  4079. }
  4080. else if (auto varDeclExpr = BfNodeDynCast<BfVariableDeclaration>(argExpr))
  4081. {
  4082. resolvedArg.mArgFlags = (BfArgFlags)(resolvedArg.mArgFlags | BfArgFlag_VariableDeclaration);
  4083. handled = true;
  4084. }
  4085. else if (auto unaryExpr = BfNodeDynCast<BfUnaryOperatorExpression>(argExpr))
  4086. {
  4087. if (unaryExpr->mOp == BfUnaryOp_Params)
  4088. {
  4089. resolvedArg.mArgFlags = (BfArgFlags)(resolvedArg.mArgFlags | BfArgFlag_ParamsExpr);
  4090. }
  4091. }
  4092. else if (auto uninitExpr = BfNodeDynCast<BfUninitializedExpression>(argExpr))
  4093. {
  4094. resolvedArg.mArgFlags = (BfArgFlags)(resolvedArg.mArgFlags | BfArgFlag_UninitializedExpr);
  4095. handled = true;
  4096. }
  4097. /*else if (auto castExpr = BfNodeDynCast<BfCastExpression>(argExpr))
  4098. {
  4099. if (auto namedTypeRef = BfNodeDynCastExact<BfNamedTypeReference>(castExpr->mTypeRef))
  4100. {
  4101. if (namedTypeRef->ToString() == "ExpectedType")
  4102. {
  4103. resolvedArg.mArgFlags = (BfArgFlags)(resolvedArg.mArgFlags | BfArgFlag_ExpectedTypeCast);
  4104. handled = true;
  4105. }
  4106. }
  4107. }*/
  4108. if ((argExpr != NULL) && (!handled))
  4109. {
  4110. bool deferParamValues = (flags & BfResolveArgFlag_DeferParamValues) != 0;
  4111. SetAndRestoreValue<bool> ignoreWrites(mModule->mBfIRBuilder->mIgnoreWrites, mModule->mBfIRBuilder->mIgnoreWrites || deferParamValues);
  4112. auto prevInsertBlock = mModule->mBfIRBuilder->GetInsertBlock();
  4113. if (deferParamValues)
  4114. resolvedArg.mArgFlags = (BfArgFlags)(resolvedArg.mArgFlags | BfArgFlag_DeferredValue);
  4115. if (!evaluated)
  4116. {
  4117. exprEvaluator.mBfEvalExprFlags = (BfEvalExprFlags)(exprEvaluator.mBfEvalExprFlags | BfEvalExprFlags_AllowParamsExpr);
  4118. if ((resolvedArg.mArgFlags & BfArgFlag_StringInterpolateFormat) != 0)
  4119. exprEvaluator.mBfEvalExprFlags = (BfEvalExprFlags)(exprEvaluator.mBfEvalExprFlags | BfEvalExprFlags_StringInterpolateFormat);
  4120. exprEvaluator.Evaluate(argExpr, false, false, true);
  4121. }
  4122. if ((mModule->mCurMethodState != NULL) && (exprEvaluator.mResultLocalVar != NULL) && (exprEvaluator.mResultLocalVarRefNode != NULL))
  4123. {
  4124. auto localVar = exprEvaluator.mResultLocalVar;
  4125. int fieldIdx = mResultLocalVarField - 1;
  4126. auto methodState = mModule->mCurMethodState->GetMethodStateForLocal(localVar);
  4127. if (localVar->mCompositeCount >= 0)
  4128. {
  4129. if ((resolvedArg.mArgFlags & BfArgFlag_ParamsExpr) == 0)
  4130. mModule->Warn(0, "'params' token expected", argExpr);
  4131. for (int compositeIdx = 0; compositeIdx < localVar->mCompositeCount; compositeIdx++)
  4132. {
  4133. BfResolvedArg compositeResolvedArg;
  4134. auto compositeLocalVar = methodState->mLocals[localVar->mLocalVarIdx + compositeIdx + 1];
  4135. auto argValue = exprEvaluator.LoadLocal(compositeLocalVar, true);
  4136. if (argValue)
  4137. {
  4138. if (!argValue.mType->IsStruct())
  4139. argValue = mModule->LoadValue(argValue, NULL, exprEvaluator.mIsVolatileReference);
  4140. }
  4141. resolvedArg.mTypedValue = argValue;
  4142. resolvedArg.mExpression = argExpr;
  4143. resolvedArg.mArgFlags = (BfArgFlags)(resolvedArg.mArgFlags | BfArgFlag_FromParamComposite);
  4144. resolvedArgs.mResolvedArgs.push_back(resolvedArg);
  4145. }
  4146. continue;
  4147. }
  4148. }
  4149. exprEvaluator.CheckResultForReading(exprEvaluator.mResult);
  4150. auto argValue = exprEvaluator.mResult;
  4151. if (argValue)
  4152. {
  4153. //resolvedArg.mResolvedType = mModule->ResolveGenericType(argValue.mType);
  4154. resolvedArg.mResolvedType = argValue.mType;
  4155. if (resolvedArg.mResolvedType->IsRef())
  4156. argValue.mKind = BfTypedValueKind_Value;
  4157. else if ((!resolvedArg.mResolvedType->IsStruct()) && (!resolvedArg.mResolvedType->IsSizedArray()) && (!resolvedArg.mResolvedType->IsValuelessType()))
  4158. argValue = mModule->LoadValue(argValue, NULL, exprEvaluator.mIsVolatileReference);
  4159. }
  4160. resolvedArg.mTypedValue = argValue;
  4161. if (deferParamValues)
  4162. mModule->mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  4163. }
  4164. resolvedArg.mExpression = argExpr;
  4165. resolvedArgs.mResolvedArgs.push_back(resolvedArg);
  4166. }
  4167. if (autoComplete != NULL)
  4168. autoComplete->mIgnoreFixits = hadIgnoredFixits;
  4169. }
  4170. void BfExprEvaluator::PerformCallChecks(BfMethodInstance* methodInstance, BfAstNode* targetSrc)
  4171. {
  4172. BfCustomAttributes* customAttributes = methodInstance->GetCustomAttributes();
  4173. if (customAttributes != NULL)
  4174. mModule->CheckErrorAttributes(methodInstance->GetOwner(), methodInstance, customAttributes, targetSrc);
  4175. }
  4176. BfTypedValue BfExprEvaluator::CreateCall(BfAstNode* targetSrc, BfMethodInstance* methodInstance, BfIRValue func, bool bypassVirtual, SizedArrayImpl<BfIRValue>& irArgs, BfTypedValue* sret, bool isTailCall)
  4177. {
  4178. // static int sCallIdx = 0;
  4179. // if (!mModule->mCompiler->mIsResolveOnly)
  4180. // sCallIdx++;
  4181. // int callIdx = sCallIdx;
  4182. // if (callIdx == 0x000000E8)
  4183. // {
  4184. // NOP;
  4185. // }
  4186. auto methodDef = methodInstance->mMethodDef;
  4187. BfIRValue funcCallInst = func;
  4188. auto importCallKind = methodInstance->GetImportCallKind();
  4189. if ((funcCallInst) && (importCallKind != BfImportCallKind_None))
  4190. {
  4191. if ((funcCallInst.IsFake()) && (!mModule->mBfIRBuilder->mIgnoreWrites))
  4192. {
  4193. mModule->mFuncReferences.TryGetValue(methodInstance, &funcCallInst);
  4194. }
  4195. if ((importCallKind == BfImportCallKind_GlobalVar) &&
  4196. (methodInstance->mHotMethod == NULL) &&
  4197. (mModule->mCompiler->IsHotCompile()))
  4198. {
  4199. // This may actually be a BfImportCallKind_GlobalVar_Hot, so check it...
  4200. mModule->CheckHotMethod(methodInstance, "");
  4201. importCallKind = methodInstance->GetImportCallKind();
  4202. }
  4203. if (importCallKind == BfImportCallKind_GlobalVar_Hot)
  4204. {
  4205. //TODO: Check against NULL for calling BfLoadSharedLibraries
  4206. auto checkVal = mModule->mBfIRBuilder->CreateLoad(funcCallInst);
  4207. BfIRBlock nullBlock = mModule->mBfIRBuilder->CreateBlock("importNull");
  4208. BfIRBlock doneBlock = mModule->mBfIRBuilder->CreateBlock("importLoad");
  4209. auto condVal = mModule->mBfIRBuilder->CreateIsNull(checkVal);
  4210. mModule->mBfIRBuilder->CreateCondBr(condVal, nullBlock, doneBlock);
  4211. mModule->mBfIRBuilder->AddBlock(nullBlock);
  4212. mModule->mBfIRBuilder->SetInsertPoint(nullBlock);
  4213. auto loadSharedLibsFunc = mModule->GetBuiltInFunc(BfBuiltInFuncType_LoadSharedLibraries);
  4214. mModule->mBfIRBuilder->CreateCall(loadSharedLibsFunc, SizedArray<BfIRValue, 0>());
  4215. mModule->mBfIRBuilder->CreateBr(doneBlock);
  4216. mModule->mBfIRBuilder->AddBlock(doneBlock);
  4217. mModule->mBfIRBuilder->SetInsertPoint(doneBlock);
  4218. funcCallInst = mModule->mBfIRBuilder->CreateLoad(funcCallInst);
  4219. }
  4220. else
  4221. {
  4222. funcCallInst = mModule->mBfIRBuilder->CreateLoad(funcCallInst);
  4223. }
  4224. }
  4225. if ((methodInstance->GetOwner()->mTypeDef == mModule->mCompiler->mDeferredCallTypeDef) &&
  4226. (methodInstance->mMethodDef->mName == "Cancel"))
  4227. {
  4228. if (mModule->mCurMethodState != NULL)
  4229. mModule->mCurMethodState->mCancelledDeferredCall = true;
  4230. }
  4231. if (methodDef->mIsNoReturn)
  4232. {
  4233. mModule->mCurMethodState->SetHadReturn(true);
  4234. mModule->mCurMethodState->mLeftBlockUncond = true;
  4235. }
  4236. if (mModule->mCurTypeInstance != NULL)
  4237. {
  4238. bool isVirtual = (methodInstance->mVirtualTableIdx != -1) && (!bypassVirtual);
  4239. mModule->AddDependency(methodInstance->mMethodInstanceGroup->mOwner, mModule->mCurTypeInstance, isVirtual ? BfDependencyMap::DependencyFlag_VirtualCall : BfDependencyMap::DependencyFlag_Calls);
  4240. mModule->AddCallDependency(methodInstance, bypassVirtual);
  4241. }
  4242. if (methodInstance->GetOwner()->IsUnspecializedType())
  4243. {
  4244. BF_ASSERT((!methodInstance->mIRFunction) || (methodInstance == mModule->mCurMethodInstance));
  4245. }
  4246. if (mFunctionBindResult != NULL)
  4247. {
  4248. BF_ASSERT(mFunctionBindResult->mMethodInstance == NULL);
  4249. mFunctionBindResult->mMethodInstance = methodInstance;
  4250. for (auto arg : irArgs)
  4251. mFunctionBindResult->mIRArgs.push_back(arg);
  4252. }
  4253. BfType* origReturnType = methodInstance->mReturnType;
  4254. /*if (origReturnType->IsSelf())
  4255. {
  4256. origReturnType = methodInstance->GetOwner();
  4257. BF_ASSERT(origReturnType->IsInterface());
  4258. }*/
  4259. BfType* returnType = origReturnType;
  4260. BfTypedValue sretVal;
  4261. auto _GetDefaultReturnValue = [&]()
  4262. {
  4263. if (returnType->IsRef())
  4264. {
  4265. auto result = mModule->GetDefaultTypedValue(returnType->GetUnderlyingType(), true, BfDefaultValueKind_Addr);
  4266. if (methodDef->mIsReadOnly)
  4267. result.mKind = BfTypedValueKind_ReadOnlyAddr;
  4268. return result;
  4269. }
  4270. else
  4271. {
  4272. auto val = mModule->GetDefaultTypedValue(returnType, true, (methodInstance->GetStructRetIdx() != -1) ? BfDefaultValueKind_Addr : BfDefaultValueKind_Value);
  4273. if (val.mKind == BfTypedValueKind_Addr)
  4274. val.mKind = BfTypedValueKind_RestrictedTempAddr;
  4275. return val;
  4276. }
  4277. };
  4278. mModule->PopulateType(origReturnType, BfPopulateType_Data);
  4279. if (methodInstance->GetStructRetIdx() != -1)
  4280. {
  4281. // We need to ensure that mReceivingValue has the correct type, otherwise it's possible that a conversion operator needs to be applied
  4282. // This happens for returning Result<T>'s with a 'T' value
  4283. if ((sret == NULL) && (mReceivingValue != NULL) && (mReceivingValue->mType == returnType))
  4284. {
  4285. sretVal = *mReceivingValue;
  4286. sret = &sretVal;
  4287. auto ptrType = mModule->CreatePointerType(returnType);
  4288. if (returnType != sret->mType)
  4289. {
  4290. sret->mValue = mModule->mBfIRBuilder->CreateBitCast(sret->mValue, mModule->mBfIRBuilder->MapType(ptrType));
  4291. sret->mType = returnType;
  4292. }
  4293. mReceivingValue = NULL;
  4294. }
  4295. if (sret == NULL)
  4296. {
  4297. sretVal = BfTypedValue(mModule->CreateAlloca(returnType), returnType, BfTypedValueKind_RestrictedTempAddr);
  4298. sret = &sretVal;
  4299. }
  4300. }
  4301. else
  4302. {
  4303. BF_ASSERT(sret == NULL);
  4304. }
  4305. if ((mModule->mCurMethodState != NULL) && (mModule->mCurMethodState->mClosureState != NULL) && (mModule->mCurMethodState->mClosureState->mCapturing))
  4306. {
  4307. return _GetDefaultReturnValue();
  4308. }
  4309. BF_ASSERT(!methodInstance->mDisallowCalling);
  4310. if ((mModule->mCompiler->mResolvePassData != NULL) && (mModule->mCompiler->mResolvePassData->mAutoComplete != NULL))
  4311. {
  4312. // In an autocomplete pass we may have stale method references that need to be resolved
  4313. // in the full classify pass, and in the full classify pass while just refreshing internals, we
  4314. // may have NULL funcs temporarily. We simply skip generating the method call here.
  4315. if (methodInstance->mVirtualTableIdx == -1)
  4316. {
  4317. if (methodInstance->GetOwner()->IsInterface())
  4318. {
  4319. // We're attempting to directly invoke a non-virtual interface method, if we're return an interface then
  4320. // it is a concrete interface
  4321. if (returnType->IsInterface())
  4322. returnType = mModule->CreateConcreteInterfaceType(returnType->ToTypeInstance());
  4323. }
  4324. }
  4325. BfTypedValue result;
  4326. if (sret != NULL)
  4327. result = *sret;
  4328. else
  4329. result = _GetDefaultReturnValue();
  4330. return result;
  4331. }
  4332. if (mModule->mCompiler->mCEMachine != NULL)
  4333. {
  4334. if (mModule->mIsConstModule)
  4335. {
  4336. mModule->mCompiler->mCEMachine->QueueMethod(methodInstance, func);
  4337. }
  4338. else if ((mBfEvalExprFlags & BfEvalExprFlags_ConstExpr) != 0)
  4339. {
  4340. auto constRet = mModule->mCompiler->mCEMachine->Call(targetSrc, mModule, methodInstance, irArgs, CeEvalFlags_None);
  4341. if (constRet)
  4342. return constRet;
  4343. }
  4344. }
  4345. if (((!func) && (methodInstance->mIsUnspecialized)) || (mModule->mBfIRBuilder->mIgnoreWrites))
  4346. {
  4347. // We don't actually submit method calls for unspecialized methods
  4348. // - this includes all methods in unspecialized types
  4349. return _GetDefaultReturnValue();
  4350. }
  4351. if (methodInstance->mVirtualTableIdx != -1)
  4352. {
  4353. if ((!bypassVirtual) && (mDeferCallRef == NULL))
  4354. {
  4355. if ((methodDef->mIsOverride) && (mModule->mCurMethodInstance->mIsReified))
  4356. {
  4357. // Ensure that declaring method gets referenced
  4358. auto typeInstance = methodInstance->GetOwner();
  4359. auto& vEntry = typeInstance->mVirtualMethodTable[methodInstance->mVirtualTableIdx];
  4360. BfMethodInstance* declaringMethodInstance = vEntry.mDeclaringMethod;
  4361. if ((declaringMethodInstance->mMethodInstanceGroup->mOnDemandKind < BfMethodOnDemandKind_InWorkList) || (!declaringMethodInstance->mIsReified))
  4362. mModule->GetMethodInstance(declaringMethodInstance);
  4363. }
  4364. auto funcType = mModule->mBfIRBuilder->MapMethod(methodInstance);
  4365. auto funcPtrType1 = mModule->mBfIRBuilder->GetPointerTo(funcType);
  4366. auto funcPtrType2 = mModule->mBfIRBuilder->GetPointerTo(funcPtrType1);
  4367. auto funcPtrType3 = mModule->mBfIRBuilder->GetPointerTo(funcPtrType2);
  4368. auto funcPtrType4 = mModule->mBfIRBuilder->GetPointerTo(funcPtrType3);
  4369. if (methodInstance->mMethodInstanceGroup->mOwner->IsInterface())
  4370. {
  4371. if (mModule->mIsConstModule)
  4372. {
  4373. funcCallInst = mModule->mBfIRBuilder->ConstEval_GetInterfaceFunc(irArgs[0], methodInstance->mMethodInstanceGroup->mOwner->mTypeId, methodInstance->mVirtualTableIdx, funcPtrType1);
  4374. }
  4375. else
  4376. {
  4377. // IFace dispatch
  4378. auto ifaceTypeInst = methodInstance->mMethodInstanceGroup->mOwner;
  4379. BfIRValue slotOfs = mModule->GetInterfaceSlotNum(methodInstance->mMethodInstanceGroup->mOwner);
  4380. auto vDataPtrPtr = mModule->mBfIRBuilder->CreateBitCast(irArgs[0], funcPtrType4);
  4381. auto vDataPtr = mModule->FixClassVData(mModule->mBfIRBuilder->CreateLoad(vDataPtrPtr/*, "vtable"*/));
  4382. auto ifacePtrPtr = mModule->mBfIRBuilder->CreateInBoundsGEP(vDataPtr, slotOfs/*, "iface"*/);
  4383. auto ifacePtr = mModule->mBfIRBuilder->CreateLoad(ifacePtrPtr);
  4384. auto funcPtr = mModule->mBfIRBuilder->CreateInBoundsGEP(ifacePtr, methodInstance->mVirtualTableIdx/*, "vfn"*/);
  4385. funcCallInst = mModule->mBfIRBuilder->CreateLoad(funcPtr);
  4386. }
  4387. }
  4388. else if (mModule->mIsConstModule)
  4389. {
  4390. funcCallInst = mModule->mBfIRBuilder->ConstEval_GetVirtualFunc(irArgs[0], methodInstance->mVirtualTableIdx, funcPtrType1);
  4391. }
  4392. else
  4393. {
  4394. mModule->HadSlotCountDependency();
  4395. // Virtual dispatch
  4396. // int vDataIdx = 0;
  4397. // vDataIdx += 1 + methodInstance->GetOwner()->GetDynCastVDataCount() + mModule->mCompiler->mMaxInterfaceSlots;
  4398. BfIRValue vDataPtr;
  4399. BfIRValue vDataIdx;
  4400. if ((mModule->mCompiler->mOptions.mHasVDataExtender) && (mModule->mCompiler->IsHotCompile()))
  4401. {
  4402. auto typeInst = methodInstance->mMethodInstanceGroup->mOwner;
  4403. int extMethodIdx = (methodInstance->mVirtualTableIdx - typeInst->GetImplBaseVTableSize()) - typeInst->GetOrigSelfVTableSize();
  4404. if (extMethodIdx >= 0)
  4405. {
  4406. BF_ASSERT(mModule->mCompiler->IsHotCompile());
  4407. // We have grown outside our original virtual table, Load the new vdataPtr from the mHasVDataExtender
  4408. // vDataPtr = obj.vtable.extension.entry[curVersion]
  4409. BfIRValue vDataPtrPtr = mModule->mBfIRBuilder->CreateBitCast(irArgs[0], funcPtrType4);
  4410. vDataPtr = mModule->FixClassVData(mModule->mBfIRBuilder->CreateLoad(vDataPtrPtr));
  4411. // The offset of the vExt is one past the base vtable. When a base class extends its virtual table, an entry
  4412. // for that new method is inserted in mVirtualMethodTable (thus increasing the index relative to GetBaseVTableSize()),
  4413. // but the actual written vtable position doesn't change, hence offsetting from GetOrigBaseVTableSize()
  4414. #ifdef _DEBUG
  4415. int vExtIdx = typeInst->GetImplBaseVTableSize();
  4416. BF_ASSERT(typeInst->mVirtualMethodTable[vExtIdx].mDeclaringMethod.mMethodNum == -1); // A type entry with a -1 mMethodNum means it's a vtable ext slot
  4417. #endif
  4418. int vExtOfs = typeInst->GetOrigImplBaseVTableSize();
  4419. vDataIdx = mModule->mBfIRBuilder->CreateConst(BfTypeCode_Int32, 1 + mModule->mCompiler->GetDynCastVDataCount() + mModule->mCompiler->mMaxInterfaceSlots);
  4420. vDataIdx = mModule->mBfIRBuilder->CreateAdd(vDataIdx, mModule->mBfIRBuilder->CreateConst(BfTypeCode_Int32, vExtOfs));
  4421. BfIRValue extendPtr = mModule->mBfIRBuilder->CreateInBoundsGEP(vDataPtr, vDataIdx);
  4422. vDataPtr = mModule->mBfIRBuilder->CreateLoad(extendPtr);
  4423. vDataIdx = mModule->mBfIRBuilder->CreateConst(BfTypeCode_Int32, extMethodIdx);
  4424. }
  4425. else
  4426. {
  4427. // Map this new virtual index back to the original index
  4428. //vDataIdx += (methodInstance->mVirtualTableIdx - typeInst->GetBaseVTableSize()) + typeInst->GetOrigBaseVTableSize();
  4429. //vDataIdx = mModule->mBfIRBuilder->CreateConst(BfTypeCode_Int32, 1 + methodInstance->GetOwner()->GetDynCastVDataCount() + mModule->mCompiler->mMaxInterfaceSlots);
  4430. vDataIdx = mModule->mBfIRBuilder->GetConfigConst(BfIRConfigConst_VirtualMethodOfs, BfTypeCode_Int32);
  4431. vDataIdx = mModule->mBfIRBuilder->CreateAdd(vDataIdx, mModule->mBfIRBuilder->CreateConst(BfTypeCode_Int32,
  4432. (methodInstance->mVirtualTableIdx - typeInst->GetImplBaseVTableSize()) + typeInst->GetOrigImplBaseVTableSize()));
  4433. }
  4434. }
  4435. else
  4436. {
  4437. //vDataIdx += methodInstance->mVirtualTableIdx;
  4438. //vDataIdx = mModule->mBfIRBuilder->CreateConst(BfTypeCode_Int32, 1 + methodInstance->GetOwner()->GetDynCastVDataCount() + mModule->mCompiler->mMaxInterfaceSlots);
  4439. vDataIdx = mModule->mBfIRBuilder->GetConfigConst(BfIRConfigConst_VirtualMethodOfs, BfTypeCode_Int32);
  4440. vDataIdx = mModule->mBfIRBuilder->CreateAdd(vDataIdx, mModule->mBfIRBuilder->CreateConst(BfTypeCode_Int32, methodInstance->mVirtualTableIdx));
  4441. }
  4442. if (!vDataPtr)
  4443. {
  4444. BfIRValue vDataPtrPtr = mModule->mBfIRBuilder->CreateBitCast(irArgs[0], funcPtrType3);
  4445. vDataPtr = mModule->FixClassVData(mModule->mBfIRBuilder->CreateLoad(vDataPtrPtr/*, "vtable"*/));
  4446. }
  4447. auto funcPtr = mModule->mBfIRBuilder->CreateInBoundsGEP(vDataPtr, vDataIdx/*, "vfn"*/);
  4448. funcCallInst = mModule->mBfIRBuilder->CreateLoad(funcPtr);
  4449. }
  4450. }
  4451. }
  4452. else // non-virtual
  4453. {
  4454. if (methodInstance->GetOwner()->IsInterface())
  4455. {
  4456. // We're attempting to directly invoke a non-virtual interface method, this will happen during the unspecialized pass
  4457. // OR if we had an error and didn't find an implementing member in the actual target
  4458. if (!mModule->mCurMethodInstance->mIsUnspecialized)
  4459. mModule->AssertErrorState();
  4460. if (returnType->IsInterface())
  4461. returnType = mModule->CreateConcreteInterfaceType(returnType->ToTypeInstance());
  4462. return _GetDefaultReturnValue();
  4463. }
  4464. }
  4465. if (mFunctionBindResult != NULL)
  4466. {
  4467. mFunctionBindResult->mFunc = funcCallInst;
  4468. if (irArgs.size() != 0)
  4469. {
  4470. auto targetType = methodInstance->mMethodInstanceGroup->mOwner;
  4471. if ((targetType->IsValueType()) && (targetType->IsSplattable()) && (!methodDef->HasNoThisSplat()))
  4472. mFunctionBindResult->mTarget = BfTypedValue(irArgs[0], targetType, BfTypedValueKind_SplatHead);
  4473. else
  4474. mFunctionBindResult->mTarget = BfTypedValue(irArgs[0], targetType, targetType->IsComposite() ? BfTypedValueKind_Addr : BfTypedValueKind_Value);
  4475. }
  4476. else
  4477. {
  4478. mFunctionBindResult->mTarget = BfTypedValue();
  4479. }
  4480. return BfTypedValue();
  4481. }
  4482. if (methodInstance->mReturnType == NULL)
  4483. {
  4484. mModule->AssertErrorState();
  4485. return BfTypedValue();
  4486. }
  4487. if ((mModule->mCurMethodInstance != NULL) && (mModule->mCurMethodInstance->mIsUnspecialized))
  4488. {
  4489. // Don't actually do the call - our target may be a generic param
  4490. return _GetDefaultReturnValue();
  4491. }
  4492. if (mDeferCallRef != NULL)
  4493. {
  4494. mModule->AddDeferredCall(BfModuleMethodInstance(methodInstance, func), irArgs, mDeferScopeAlloc, mDeferCallRef);
  4495. //return _GetDefaultReturnValue();
  4496. return mModule->GetFakeTypedValue(returnType);
  4497. }
  4498. if (!funcCallInst)
  4499. {
  4500. if ((mModule->HasCompiledOutput()) || (mModule->mCompiler->mOptions.mExtraResolveChecks))
  4501. {
  4502. // This can happen either from an error, or from the resolver while doing Internals_Changed processing
  4503. mModule->AssertErrorState();
  4504. }
  4505. //return mModule->GetDefaultTypedValue(returnType,/*, true*/false, returnType->IsComposite());
  4506. return _GetDefaultReturnValue();
  4507. }
  4508. bool hasResult = !methodInstance->mReturnType->IsValuelessType();
  4509. BfIRValue firstArg;
  4510. if (irArgs.size() != 0)
  4511. firstArg = irArgs[0];
  4512. auto methodInstOwner = methodInstance->GetOwner();
  4513. auto expectCallingConvention = mModule->GetIRCallingConvention(methodInstance);
  4514. if ((methodInstOwner->IsFunction()) && (methodInstance->GetParamCount() > 0) && (methodInstance->GetParamName(0) == "this"))
  4515. {
  4516. auto paramType = methodInstance->GetParamType(0);
  4517. if (!paramType->IsValueType())
  4518. expectCallingConvention = BfIRCallingConv_ThisCall;
  4519. }
  4520. if ((methodInstance->mAlwaysInline) && (mModule->mCompiler->mOptions.mEmitLineInfo))
  4521. {
  4522. // Emit a NOP so we always have a "step over" point
  4523. mModule->EmitEnsureInstructionAt();
  4524. }
  4525. if (returnType->IsComposite())
  4526. mModule->mBfIRBuilder->PopulateType(returnType);
  4527. BfIRValue callInst;
  4528. int callIRArgCount = (int)irArgs.size();
  4529. if (sret != NULL)
  4530. {
  4531. SizedArray<BfIRValue, 8> sretIRArgs;
  4532. int sretIdx = methodInstance->GetStructRetIdx();
  4533. int inIdx = 0;
  4534. for (int outIdx = 0; outIdx < irArgs.size() + 1; outIdx++)
  4535. {
  4536. if (outIdx == sretIdx)
  4537. {
  4538. sretIRArgs.Add(sret->mValue);
  4539. continue;
  4540. }
  4541. sretIRArgs.Add(irArgs[inIdx++]);
  4542. }
  4543. callInst = mModule->mBfIRBuilder->CreateCall(funcCallInst, sretIRArgs);
  4544. callIRArgCount++;
  4545. }
  4546. else
  4547. {
  4548. callInst = mModule->mBfIRBuilder->CreateCall(funcCallInst, irArgs);
  4549. if ((hasResult) && (!methodDef->mName.IsEmpty()) && (!methodInstance->mIsIntrinsic))
  4550. mModule->mBfIRBuilder->SetName(callInst, methodDef->mName);
  4551. }
  4552. if ((expectCallingConvention != BfIRCallingConv_CDecl) && (!methodInstance->mIsIntrinsic))
  4553. mModule->mBfIRBuilder->SetCallCallingConv(callInst, expectCallingConvention);
  4554. if ((methodDef->mIsNoReturn) && (!methodInstance->mIsIntrinsic))
  4555. mModule->mBfIRBuilder->Call_AddAttribute(callInst, -1, BfIRAttribute_NoReturn);
  4556. bool hadAttrs = false;
  4557. int paramIdx = 0;
  4558. bool doingThis = !methodDef->mIsStatic;
  4559. int argIdx = 0;
  4560. if (methodDef->mHasExplicitThis)
  4561. paramIdx++;
  4562. int paramCount = methodInstance->GetParamCount();
  4563. for ( ; argIdx < callIRArgCount ; )
  4564. {
  4565. if (methodInstance->mIsIntrinsic)
  4566. break;
  4567. if (argIdx == methodInstance->GetStructRetIdx())
  4568. {
  4569. mModule->mBfIRBuilder->Call_AddAttribute(callInst, argIdx + 1, BfIRAttribute_StructRet);
  4570. argIdx++;
  4571. continue;
  4572. }
  4573. auto _HandleParamType = [&] (BfType* paramType)
  4574. {
  4575. if (paramType->IsStruct())
  4576. {
  4577. if ((!doingThis) || (!methodDef->mIsMutating && methodInstance->AllowsSplatting()))
  4578. {
  4579. BfTypeCode loweredTypeCode = BfTypeCode_None;
  4580. BfTypeCode loweredTypeCode2 = BfTypeCode_None;
  4581. if (paramType->GetLoweredType(BfTypeUsage_Parameter, &loweredTypeCode, &loweredTypeCode2))
  4582. {
  4583. argIdx++;
  4584. if (loweredTypeCode2 != BfTypeCode_None)
  4585. argIdx++;
  4586. return; // Lowering never requires attributes
  4587. }
  4588. }
  4589. }
  4590. int addDeref = -1;
  4591. if (paramType->IsRef())
  4592. {
  4593. auto refType = (BfRefType*)paramType;
  4594. auto elementType = refType->mElementType;
  4595. mModule->PopulateType(elementType, BfPopulateType_Data);
  4596. addDeref = elementType->mSize;
  4597. if ((addDeref <= 0) && (!elementType->IsValuelessType()))
  4598. mModule->AssertErrorState();
  4599. }
  4600. if ((paramType->IsComposite()) && (!paramType->IsTypedPrimitive()))
  4601. {
  4602. if (mModule->mCompiler->mOptions.mAllowStructByVal)
  4603. {
  4604. //byval
  4605. }
  4606. else
  4607. {
  4608. mModule->PopulateType(paramType, BfPopulateType_Data);
  4609. auto typeInst = paramType->ToTypeInstance();
  4610. if ((typeInst != NULL) && (typeInst->mIsCRepr) && (typeInst->IsSplattable()))
  4611. {
  4612. // We're splatting
  4613. }
  4614. else
  4615. {
  4616. if (doingThis)
  4617. {
  4618. mModule->mBfIRBuilder->Call_AddAttribute(callInst, argIdx + 1, BfIRAttribute_NoCapture);
  4619. addDeref = paramType->mSize;
  4620. }
  4621. else if (methodInstance->WantsStructsAttribByVal())
  4622. {
  4623. mModule->mBfIRBuilder->Call_AddAttribute(callInst, argIdx + 1, BfIRAttribute_ByVal, mModule->mSystem->mPtrSize);
  4624. }
  4625. }
  4626. }
  4627. }
  4628. else if (paramType->IsPrimitiveType())
  4629. {
  4630. auto primType = (BfPrimitiveType*)paramType;
  4631. if ((primType->mTypeDef->mTypeCode == BfTypeCode_Boolean) && (!methodInstance->mIsIntrinsic))
  4632. mModule->mBfIRBuilder->Call_AddAttribute(callInst, argIdx + 1, BfIRAttribute_ZExt);
  4633. }
  4634. if (addDeref >= 0)
  4635. {
  4636. mModule->mBfIRBuilder->Call_AddAttribute(callInst, argIdx + 1, BfIRAttribute_Dereferencable, addDeref);
  4637. }
  4638. argIdx++;
  4639. };
  4640. BfType* paramType = NULL;
  4641. if (doingThis)
  4642. {
  4643. int thisIdx = methodInstance->GetThisIdx();
  4644. paramType = methodInstance->GetThisType();
  4645. if (paramType->IsValuelessType())
  4646. {
  4647. doingThis = false;
  4648. continue;
  4649. }
  4650. bool isSplatted = methodInstance->GetParamIsSplat(thisIdx); // (resolvedTypeRef->IsSplattable()) && (!methodDef->mIsMutating);
  4651. if (isSplatted)
  4652. {
  4653. BfTypeUtils::SplatIterate(_HandleParamType, paramType);
  4654. doingThis = false;
  4655. continue;
  4656. }
  4657. else
  4658. _HandleParamType(paramType);
  4659. }
  4660. else
  4661. {
  4662. if (paramIdx >= methodInstance->GetParamCount())
  4663. break;
  4664. paramType = methodInstance->GetParamType(paramIdx);
  4665. BfTypeCode loweredTypeCode = BfTypeCode_None;
  4666. BfTypeCode loweredTypeCode2 = BfTypeCode_None;
  4667. if (paramType->GetLoweredType(BfTypeUsage_Parameter, &loweredTypeCode, &loweredTypeCode2))
  4668. {
  4669. argIdx++;
  4670. paramIdx++;
  4671. if (loweredTypeCode2 != BfTypeCode_None)
  4672. argIdx++;
  4673. continue;
  4674. }
  4675. if ((paramType->IsValuelessType()) && (!paramType->IsMethodRef()))
  4676. {
  4677. paramIdx++;
  4678. continue;
  4679. }
  4680. if (methodInstance->GetParamIsSplat(paramIdx))
  4681. {
  4682. BfTypeUtils::SplatIterate(_HandleParamType, paramType);
  4683. paramIdx++;
  4684. continue;
  4685. }
  4686. else
  4687. _HandleParamType(methodInstance->GetParamType(paramIdx));
  4688. }
  4689. if (doingThis)
  4690. doingThis = false;
  4691. else
  4692. paramIdx++;
  4693. //argIdx++;
  4694. }
  4695. if (isTailCall)
  4696. mModule->mBfIRBuilder->SetTailCall(callInst);
  4697. if (methodDef->mIsNoReturn)
  4698. {
  4699. mModule->mBfIRBuilder->CreateUnreachable();
  4700. // For debuggability when looking back at stack trace
  4701. //mModule->ExtendLocalLifetimes(0);
  4702. if (mModule->IsTargetingBeefBackend())
  4703. {
  4704. auto checkScope = mModule->mCurMethodState->mCurScope;
  4705. while (checkScope != NULL)
  4706. {
  4707. mModule->EmitLifetimeEnds(checkScope);
  4708. checkScope = checkScope->mPrevScope;
  4709. }
  4710. // This 'fake' branch extends lifetimes of outer variable scopes
  4711. if (mModule->mCurMethodState->mIRExitBlock)
  4712. mModule->mBfIRBuilder->CreateBr_Fake(mModule->mCurMethodState->mIRExitBlock);
  4713. }
  4714. }
  4715. else
  4716. {
  4717. if (mModule->mCurMethodState != NULL)
  4718. mModule->mCurMethodState->mMayNeedThisAccessCheck = true;
  4719. }
  4720. BfTypedValue result;
  4721. if (sret != NULL)
  4722. result = *sret;
  4723. else if (hasResult)
  4724. {
  4725. BfTypeCode loweredRetType = BfTypeCode_None;
  4726. BfTypeCode loweredRetType2 = BfTypeCode_None;
  4727. if (methodInstance->GetLoweredReturnType(&loweredRetType, &loweredRetType2))
  4728. {
  4729. auto retVal = mModule->CreateAlloca(methodInstance->mReturnType);
  4730. BfIRType loweredIRType = mModule->GetIRLoweredType(loweredRetType, loweredRetType2);
  4731. loweredIRType = mModule->mBfIRBuilder->GetPointerTo(loweredIRType);
  4732. auto castedRetVal = mModule->mBfIRBuilder->CreateBitCast(retVal, loweredIRType);
  4733. mModule->mBfIRBuilder->CreateStore(callInst, castedRetVal);
  4734. result = BfTypedValue(retVal, methodInstance->mReturnType, BfTypedValueKind_RestrictedTempAddr);
  4735. }
  4736. else
  4737. result = BfTypedValue(callInst, methodInstance->mReturnType);
  4738. }
  4739. else
  4740. result = mModule->GetFakeTypedValue(methodInstance->mReturnType);
  4741. if (result.mType->IsRef())
  4742. {
  4743. result = mModule->RemoveRef(result);
  4744. if (methodDef->mIsReadOnly)
  4745. {
  4746. if (result.mKind == BfTypedValueKind_Addr)
  4747. result.mKind = BfTypedValueKind_ReadOnlyAddr;
  4748. }
  4749. }
  4750. return result;
  4751. }
  4752. BfTypedValue BfExprEvaluator::CreateCall(BfMethodMatcher* methodMatcher, BfTypedValue target)
  4753. {
  4754. auto& moduleMethodInstance = methodMatcher->mBestMethodInstance;
  4755. if (!moduleMethodInstance)
  4756. moduleMethodInstance = GetSelectedMethod(methodMatcher->mTargetSrc, methodMatcher->mBestMethodTypeInstance, methodMatcher->mBestMethodDef, *methodMatcher);
  4757. if (moduleMethodInstance.mMethodInstance == NULL)
  4758. return BfTypedValue();
  4759. if ((target) && (target.mType != moduleMethodInstance.mMethodInstance->GetOwner()))
  4760. {
  4761. auto castedTarget = mModule->Cast(methodMatcher->mTargetSrc, target, moduleMethodInstance.mMethodInstance->GetOwner());
  4762. BF_ASSERT(castedTarget);
  4763. target = castedTarget;
  4764. }
  4765. return CreateCall(methodMatcher->mTargetSrc, target, BfTypedValue(), methodMatcher->mBestMethodDef, moduleMethodInstance, false, methodMatcher->mArguments);
  4766. }
  4767. void BfExprEvaluator::MakeBaseConcrete(BfTypedValue& typedValue)
  4768. {
  4769. if (typedValue.IsBase())
  4770. {
  4771. auto baseType = mModule->mCurTypeInstance->mBaseType;
  4772. if (baseType == NULL)
  4773. baseType = mModule->mContext->mBfObjectType;
  4774. mModule->PopulateType(baseType, BfPopulateType_Data);
  4775. typedValue = mModule->Cast(NULL, typedValue, baseType, BfCastFlags_Explicit);
  4776. }
  4777. }
  4778. void BfExprEvaluator::SplatArgs(BfTypedValue value, SizedArrayImpl<BfIRValue>& irArgs)
  4779. {
  4780. if (value.IsSplat())
  4781. {
  4782. int componentIdx = 0;
  4783. BfTypeUtils::SplatIterate([&](BfType* checkType) { irArgs.push_back(mModule->ExtractSplatValue(value, componentIdx++, checkType)); }, value.mType);
  4784. return;
  4785. }
  4786. mModule->mBfIRBuilder->PopulateType(value.mType);
  4787. std::function<void(BfTypedValue)> checkTypeLambda = [&](BfTypedValue curValue)
  4788. {
  4789. BfType* checkType = curValue.mType;
  4790. if (checkType->IsStruct())
  4791. {
  4792. auto checkTypeInstance = checkType->ToTypeInstance();
  4793. if ((checkTypeInstance->mBaseType != NULL) && (!checkTypeInstance->mBaseType->IsValuelessType()))
  4794. {
  4795. BfTypedValue baseValue;
  4796. if (curValue.IsAddr())
  4797. baseValue = BfTypedValue((!curValue.mValue) ? BfIRValue() : mModule->mBfIRBuilder->CreateInBoundsGEP(curValue.mValue, 0, 0), checkTypeInstance->mBaseType, true);
  4798. else
  4799. baseValue = BfTypedValue((!curValue.mValue) ? BfIRValue() : mModule->mBfIRBuilder->CreateExtractValue(curValue.mValue, 0), checkTypeInstance->mBaseType);
  4800. checkTypeLambda(baseValue);
  4801. }
  4802. if (checkTypeInstance->mIsUnion)
  4803. {
  4804. auto unionInnerType = checkTypeInstance->GetUnionInnerType();
  4805. if (!unionInnerType->IsValuelessType())
  4806. {
  4807. BfTypedValue unionValue = mModule->ExtractValue(curValue, NULL, 1);
  4808. checkTypeLambda(unionValue);
  4809. }
  4810. if (checkTypeInstance->IsEnum())
  4811. {
  4812. BfTypedValue dscrValue = mModule->ExtractValue(curValue, NULL, 2);
  4813. checkTypeLambda(dscrValue);
  4814. }
  4815. }
  4816. else
  4817. {
  4818. for (int fieldIdx = 0; fieldIdx < (int)checkTypeInstance->mFieldInstances.size(); fieldIdx++)
  4819. {
  4820. auto fieldInstance = (BfFieldInstance*)&checkTypeInstance->mFieldInstances[fieldIdx];
  4821. if (fieldInstance->mDataIdx >= 0)
  4822. {
  4823. BfTypedValue fieldValue = mModule->ExtractValue(curValue, fieldInstance, fieldInstance->mDataIdx);
  4824. checkTypeLambda(fieldValue);
  4825. }
  4826. }
  4827. }
  4828. }
  4829. else if (checkType->IsMethodRef())
  4830. {
  4831. BF_ASSERT(curValue.IsAddr());
  4832. BfMethodRefType* methodRefType = (BfMethodRefType*)checkType;
  4833. for (int dataIdx = 0; dataIdx < methodRefType->GetCaptureDataCount(); dataIdx++)
  4834. {
  4835. auto checkType = methodRefType->GetCaptureType(dataIdx);
  4836. if (methodRefType->WantsDataPassedAsSplat(dataIdx))
  4837. {
  4838. BF_ASSERT(dataIdx == 0);
  4839. auto ptrType = mModule->CreatePointerType(checkType);
  4840. auto elemPtr = mModule->mBfIRBuilder->CreateBitCast(curValue.mValue, mModule->mBfIRBuilder->MapType(ptrType));
  4841. checkTypeLambda(BfTypedValue(elemPtr, checkType, BfTypedValueKind_Addr));
  4842. //BfTypedValue fieldValue = mModule->ExtractValue(curValue, fieldInstance, fieldInstance->mDataIdx);
  4843. //checkTypeLambda(fieldValue);
  4844. }
  4845. else
  4846. {
  4847. auto elemVal = mModule->mBfIRBuilder->CreateInBoundsGEP(curValue.mValue, 0, dataIdx);
  4848. if (!checkType->IsComposite())
  4849. elemVal = mModule->mBfIRBuilder->CreateLoad(elemVal);
  4850. irArgs.Add(elemVal);
  4851. //irArgs.Add(mModule->ExtractValue(curValue, dataIdx));
  4852. }
  4853. }
  4854. }
  4855. else if (!checkType->IsValuelessType())
  4856. {
  4857. auto loadedVal = mModule->LoadValue(curValue);
  4858. irArgs.push_back(loadedVal.mValue);
  4859. }
  4860. };
  4861. checkTypeLambda(value);
  4862. }
  4863. void BfExprEvaluator::PushArg(BfTypedValue argVal, SizedArrayImpl<BfIRValue>& irArgs, bool disableSplat, bool disableLowering, bool isIntrinsic)
  4864. {
  4865. MakeBaseConcrete(argVal);
  4866. if (argVal.mType->IsVar())
  4867. {
  4868. argVal = mModule->GetDefaultTypedValue(mModule->mContext->mBfObjectType);
  4869. }
  4870. if (argVal.mType->IsValuelessType())
  4871. return;
  4872. bool wantSplat = false;
  4873. if ((argVal.mType->IsSplattable()) && (!disableSplat))
  4874. {
  4875. disableLowering = true;
  4876. auto argTypeInstance = argVal.mType->ToTypeInstance();
  4877. if ((!disableSplat) && (int)irArgs.size() + argVal.mType->GetSplatCount() <= mModule->mCompiler->mOptions.mMaxSplatRegs)
  4878. wantSplat = true;
  4879. }
  4880. if (wantSplat)
  4881. {
  4882. SplatArgs(argVal, irArgs);
  4883. }
  4884. else
  4885. {
  4886. if (argVal.mType->IsComposite())
  4887. {
  4888. if (isIntrinsic)
  4889. {
  4890. // We can handle composites either by value or not
  4891. }
  4892. else
  4893. argVal = mModule->MakeAddressable(argVal);
  4894. if ((!disableLowering) && (!isIntrinsic))
  4895. {
  4896. BfTypeCode loweredTypeCode = BfTypeCode_None;
  4897. BfTypeCode loweredTypeCode2 = BfTypeCode_None;
  4898. if (argVal.mType->GetLoweredType(BfTypeUsage_Parameter, &loweredTypeCode, &loweredTypeCode2))
  4899. {
  4900. auto primType = mModule->mBfIRBuilder->GetPrimitiveType(loweredTypeCode);
  4901. auto ptrType = mModule->mBfIRBuilder->GetPointerTo(primType);
  4902. BfIRValue primPtrVal = mModule->mBfIRBuilder->CreateBitCast(argVal.mValue, ptrType);
  4903. auto primVal = mModule->mBfIRBuilder->CreateLoad(primPtrVal);
  4904. irArgs.push_back(primVal);
  4905. if (loweredTypeCode2 != BfTypeCode_None)
  4906. {
  4907. auto primType2 = mModule->mBfIRBuilder->GetPrimitiveType(loweredTypeCode2);
  4908. auto ptrType2 = mModule->mBfIRBuilder->GetPointerTo(primType2);
  4909. BfIRValue primPtrVal2;
  4910. if (mModule->mBfIRBuilder->GetSize(loweredTypeCode) < mModule->mBfIRBuilder->GetSize(loweredTypeCode2))
  4911. primPtrVal2 = mModule->mBfIRBuilder->CreateInBoundsGEP(mModule->mBfIRBuilder->CreateBitCast(primPtrVal, ptrType2), 1);
  4912. else
  4913. primPtrVal2 = mModule->mBfIRBuilder->CreateBitCast(mModule->mBfIRBuilder->CreateInBoundsGEP(primPtrVal, 1), ptrType2);
  4914. auto primVal2 = mModule->mBfIRBuilder->CreateLoad(primPtrVal2);
  4915. irArgs.push_back(primVal2);
  4916. }
  4917. return;
  4918. }
  4919. }
  4920. }
  4921. else
  4922. argVal = mModule->LoadValue(argVal);
  4923. irArgs.push_back(argVal.mValue);
  4924. }
  4925. }
  4926. void BfExprEvaluator::PushThis(BfAstNode* targetSrc, BfTypedValue argVal, BfMethodInstance* methodInstance, SizedArrayImpl<BfIRValue>& irArgs, bool skipMutCheck)
  4927. {
  4928. MakeBaseConcrete(argVal);
  4929. auto methodDef = methodInstance->mMethodDef;
  4930. if (methodInstance->IsSkipCall())
  4931. return;
  4932. if (!argVal)
  4933. {
  4934. //BF_ASSERT(mFunctionBindResult != NULL);
  4935. return;
  4936. }
  4937. if (methodDef->mIsMutating)
  4938. {
  4939. bool checkMut = false;
  4940. if (argVal.mType->IsGenericParam())
  4941. {
  4942. // For capturing mutability
  4943. if (mResultLocalVar != NULL)
  4944. mResultLocalVar->mWrittenToId = mModule->mCurMethodState->GetRootMethodState()->mCurAccessId++;
  4945. }
  4946. if (((argVal.mType->IsComposite()) || (argVal.mType->IsTypedPrimitive())))
  4947. {
  4948. if ((argVal.IsReadOnly()) || (!argVal.IsAddr()))
  4949. {
  4950. if (!skipMutCheck)
  4951. {
  4952. String err = StrFormat("call mutating method '%s' on", mModule->MethodToString(methodInstance).c_str());
  4953. CheckModifyResult(argVal, targetSrc, err.c_str());
  4954. }
  4955. if (argVal.IsSplat())
  4956. {
  4957. argVal = mModule->AggregateSplat(argVal);
  4958. argVal = mModule->MakeAddressable(argVal);
  4959. }
  4960. }
  4961. else
  4962. {
  4963. if (mResultLocalVar != NULL)
  4964. {
  4965. // When we are capturing, we need to note that we require capturing by reference here
  4966. mResultLocalVar->mWrittenToId = mModule->mCurMethodState->GetRootMethodState()->mCurAccessId++;
  4967. }
  4968. }
  4969. }
  4970. }
  4971. if (argVal.mType->IsValuelessType())
  4972. return;
  4973. if ((!methodInstance->AllowsThisSplatting()) || (methodDef->mIsMutating))
  4974. {
  4975. argVal = mModule->MakeAddressable(argVal);
  4976. irArgs.push_back(argVal.mValue);
  4977. return;
  4978. }
  4979. auto thisType = methodInstance->GetThisType();
  4980. PushArg(argVal, irArgs, !methodInstance->AllowsThisSplatting(), thisType->IsPointer());
  4981. }
  4982. void BfExprEvaluator::FinishDeferredEvals(SizedArrayImpl<BfResolvedArg>& argValues)
  4983. {
  4984. for (int argIdx = 0; argIdx < argValues.size(); argIdx++)
  4985. {
  4986. auto& argValue = argValues[argIdx].mTypedValue;
  4987. if ((argValues[argIdx].mArgFlags & (BfArgFlag_DelegateBindAttempt | BfArgFlag_LambdaBindAttempt | BfArgFlag_UnqualifiedDotAttempt | BfArgFlag_DeferredEval)) != 0)
  4988. {
  4989. if (!argValue)
  4990. {
  4991. auto expr = BfNodeDynCast<BfExpression>(argValues[argIdx].mExpression);
  4992. if (expr != NULL)
  4993. argValue = mModule->CreateValueFromExpression(expr);
  4994. }
  4995. }
  4996. }
  4997. }
  4998. void BfExprEvaluator::AddCallDependencies(BfMethodInstance* methodInstance)
  4999. {
  5000. if (methodInstance->mReturnType != NULL)
  5001. mModule->AddDependency(methodInstance->mReturnType, mModule->mCurTypeInstance, BfDependencyMap::DependencyFlag_LocalUsage);
  5002. for (int paramIdx = 0; paramIdx < methodInstance->GetParamCount(); paramIdx++)
  5003. {
  5004. auto paramType = methodInstance->GetParamType(paramIdx);
  5005. mModule->AddDependency(paramType, mModule->mCurTypeInstance, BfDependencyMap::DependencyFlag_LocalUsage);
  5006. }
  5007. if (methodInstance->mMethodInfoEx != NULL)
  5008. {
  5009. for (auto genericArg : methodInstance->mMethodInfoEx->mMethodGenericArguments)
  5010. {
  5011. if (genericArg->IsWrappableType())
  5012. genericArg = mModule->GetWrappedStructType(genericArg);
  5013. if (genericArg != NULL)
  5014. mModule->AddDependency(genericArg, mModule->mCurTypeInstance, BfDependencyMap::DependencyFlag_LocalUsage);
  5015. }
  5016. }
  5017. }
  5018. //TODO: delete argumentsZ
  5019. BfTypedValue BfExprEvaluator::CreateCall(BfAstNode* targetSrc, const BfTypedValue& inTarget, const BfTypedValue& origTarget, BfMethodDef* methodDef, BfModuleMethodInstance moduleMethodInstance, bool bypassVirtual, SizedArrayImpl<BfResolvedArg>& argValues, bool skipThis)
  5020. {
  5021. static int sCallIdx = 0;
  5022. if (!mModule->mCompiler->mIsResolveOnly)
  5023. sCallIdx++;
  5024. int callIdx = sCallIdx;
  5025. if (callIdx == 1177)
  5026. {
  5027. NOP;
  5028. }
  5029. // Temporarily disable so we don't capture calls in params
  5030. SetAndRestoreValue<BfFunctionBindResult*> prevBindResult(mFunctionBindResult, NULL);
  5031. SetAndRestoreValue<bool> prevAllowVariableDeclarations;
  5032. if (mModule->mCurMethodState != NULL)
  5033. prevAllowVariableDeclarations.Init(mModule->mCurMethodState->mCurScope->mAllowVariableDeclarations, false);
  5034. BfMethodInstance* methodInstance = moduleMethodInstance.mMethodInstance;
  5035. SizedArray<BfIRValue, 4> irArgs;
  5036. if ((methodDef->mIsAbstract) && (bypassVirtual))
  5037. {
  5038. mModule->Fail(StrFormat("Abstract base method '%s' cannot be invoked", mModule->MethodToString(methodInstance).c_str()), targetSrc);
  5039. }
  5040. bool isSkipCall = moduleMethodInstance.mMethodInstance->IsSkipCall(bypassVirtual);
  5041. BfType* returnType = methodInstance->mReturnType;
  5042. /*if (returnType->IsSelf())
  5043. {
  5044. returnType = methodInstance->GetOwner();
  5045. BF_ASSERT(returnType->IsInterface());
  5046. }*/
  5047. BfTypedValue target = inTarget;
  5048. if (!skipThis)
  5049. {
  5050. if ((target) && (target.mType->IsFunction()) && (methodInstance->GetOwner() == target.mType))
  5051. {
  5052. CheckResultForReading(target);
  5053. target = mModule->LoadValue(target);
  5054. auto funcType = mModule->mBfIRBuilder->MapMethod(moduleMethodInstance.mMethodInstance);
  5055. auto funcPtrType = mModule->mBfIRBuilder->GetPointerTo(funcType);
  5056. moduleMethodInstance.mFunc = mModule->mBfIRBuilder->CreateIntToPtr(target.mValue, funcPtrType);
  5057. }
  5058. else if (!methodDef->mIsStatic)
  5059. {
  5060. if ((!target) && (prevBindResult.mPrevVal != NULL))
  5061. {
  5062. auto bindResult = prevBindResult.mPrevVal;
  5063. if (bindResult->mBindType != NULL)
  5064. {
  5065. // Allow binding a function to a 'this' type even if no target is specified
  5066. auto delegateInfo = bindResult->mBindType->GetDelegateInfo();
  5067. if (delegateInfo != NULL)
  5068. {
  5069. if (delegateInfo->mHasExplicitThis)
  5070. {
  5071. target = mModule->GetDefaultTypedValue(delegateInfo->mParams[0], false, BfDefaultValueKind_Addr);
  5072. }
  5073. }
  5074. else if (bindResult->mBindType->IsFunction())
  5075. {
  5076. BfMethodInstance* invokeMethodInstance = mModule->GetRawMethodInstanceAtIdx(bindResult->mBindType->ToTypeInstance(), 0, "Invoke");
  5077. if (!invokeMethodInstance->mMethodDef->mIsStatic)
  5078. {
  5079. target = mModule->GetDefaultTypedValue(invokeMethodInstance->GetThisType(), false, BfDefaultValueKind_Addr);
  5080. }
  5081. }
  5082. }
  5083. }
  5084. if (!target)
  5085. {
  5086. FinishDeferredEvals(argValues);
  5087. auto error = mModule->Fail(StrFormat("An instance reference is required to %s the non-static method '%s'",
  5088. (prevBindResult.mPrevVal != NULL) ? "bind" : "invoke",
  5089. mModule->MethodToString(methodInstance).c_str()), targetSrc);
  5090. if ((error != NULL) && (methodInstance->mMethodDef->GetRefNode() != NULL))
  5091. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("See method declaration"), methodInstance->mMethodDef->GetRefNode());
  5092. return mModule->GetDefaultTypedValue(returnType);
  5093. }
  5094. auto prevResult = mResult;
  5095. mResult = target;
  5096. CheckResultForReading(mResult);
  5097. mResult = prevResult;
  5098. if (methodDef->mMethodType != BfMethodType_Ctor)
  5099. {
  5100. bool doAccessCheck = true;
  5101. if (target.IsThis())
  5102. {
  5103. if (!mModule->mCurMethodState->mMayNeedThisAccessCheck)
  5104. doAccessCheck = false;
  5105. }
  5106. if ((mModule->mAttributeState != NULL) && (mModule->mAttributeState->mCustomAttributes != NULL) && (mModule->mAttributeState->mCustomAttributes->Contains(mModule->mCompiler->mDisableObjectAccessChecksAttributeTypeDef)))
  5107. doAccessCheck = false;
  5108. if ((doAccessCheck) && (!isSkipCall) && (prevBindResult.mPrevVal == NULL))
  5109. mModule->EmitObjectAccessCheck(target);
  5110. }
  5111. if (((prevBindResult.mPrevVal == NULL) || (!prevBindResult.mPrevVal->mSkipThis)) &&
  5112. (!isSkipCall))
  5113. {
  5114. bool skipMutCheck = false;
  5115. if ((prevBindResult.mPrevVal != NULL) && (prevBindResult.mPrevVal->mSkipMutCheck))
  5116. {
  5117. // If we are binding a delegate, then we will end up making a copy of the target anyway
  5118. // so we don't need to do a mutability check
  5119. skipMutCheck = true;
  5120. }
  5121. if (methodDef->mMethodType == BfMethodType_Extension)
  5122. PushArg(target, irArgs);
  5123. else
  5124. PushThis(targetSrc, target, moduleMethodInstance.mMethodInstance, irArgs, skipMutCheck);
  5125. }
  5126. }
  5127. else if (methodDef->mMethodType == BfMethodType_Extension)
  5128. {
  5129. // Handled in args
  5130. }
  5131. else
  5132. {
  5133. mModule->CheckStaticAccess(methodInstance->mMethodInstanceGroup->mOwner);
  5134. if (target)
  5135. {
  5136. FinishDeferredEvals(argValues);
  5137. mModule->Fail(StrFormat("Method '%s' cannot be accessed with an instance reference; qualify it with a type name instead",
  5138. mModule->MethodToString(methodInstance).c_str()), targetSrc);
  5139. return mModule->GetDefaultTypedValue(returnType);
  5140. }
  5141. }
  5142. }
  5143. if (isSkipCall)
  5144. {
  5145. FinishDeferredEvals(argValues);
  5146. mModule->EmitEnsureInstructionAt();
  5147. return mModule->GetDefaultTypedValue(returnType);
  5148. }
  5149. int argIdx = 0;
  5150. int paramIdx = 0;
  5151. BfIRValue expandedParamAlloca;
  5152. BfTypedValue expandedParamsArray;
  5153. BfType* expandedParamsElementType = NULL;
  5154. int extendedParamIdx = 0;
  5155. AddCallDependencies(methodInstance);
  5156. auto autoComplete = GetAutoComplete();
  5157. if (autoComplete != NULL)
  5158. {
  5159. // Set to false to make sure we don't capture method match info from 'params' array creation
  5160. autoComplete->mIsCapturingMethodMatchInfo = false;
  5161. }
  5162. BfScopeData* boxScopeData = mDeferScopeAlloc;
  5163. if ((boxScopeData == NULL) && (mModule->mCurMethodState != NULL))
  5164. boxScopeData = mModule->mCurMethodState->mCurScope;
  5165. bool failed = false;
  5166. while (true)
  5167. {
  5168. int argExprIdx = argIdx;
  5169. if (methodDef->mMethodType == BfMethodType_Extension)
  5170. argExprIdx--;
  5171. bool isThis = (paramIdx == -1) || ((methodDef->mHasExplicitThis) && (paramIdx == 0));
  5172. bool isDirectPass = false;
  5173. if (paramIdx >= (int)methodInstance->GetParamCount())
  5174. {
  5175. if (methodInstance->IsVarArgs())
  5176. {
  5177. if (argExprIdx >= (int)argValues.size())
  5178. break;
  5179. BfTypedValue argValue = ResolveArgValue(argValues[argExprIdx], NULL);
  5180. if (argValue)
  5181. {
  5182. auto typeInst = argValue.mType->ToTypeInstance();
  5183. if (argValue.mType == mModule->GetPrimitiveType(BfTypeCode_Float))
  5184. argValue = mModule->Cast(argValues[argExprIdx].mExpression, argValue, mModule->GetPrimitiveType(BfTypeCode_Double));
  5185. if ((typeInst != NULL) && (typeInst->mTypeDef == mModule->mCompiler->mStringTypeDef))
  5186. {
  5187. BfType* charType = mModule->GetPrimitiveType(BfTypeCode_Char8);
  5188. BfType* charPtrType = mModule->CreatePointerType(charType);
  5189. argValue = mModule->Cast(argValues[argExprIdx].mExpression, argValue, charPtrType);
  5190. }
  5191. PushArg(argValue, irArgs, true, false);
  5192. }
  5193. argIdx++;
  5194. continue;
  5195. }
  5196. if (argExprIdx < (int)argValues.size())
  5197. {
  5198. BfAstNode* errorRef = argValues[argExprIdx].mExpression;
  5199. if (errorRef == NULL)
  5200. errorRef = targetSrc;
  5201. BfError* error;
  5202. if ((argValues[argExprIdx].mArgFlags & BfArgFlag_StringInterpolateArg) != 0)
  5203. {
  5204. int checkIdx = argExprIdx - 1;
  5205. while (checkIdx >= 0)
  5206. {
  5207. if ((argValues[checkIdx].mArgFlags & BfArgFlag_StringInterpolateFormat) != 0)
  5208. {
  5209. errorRef = argValues[checkIdx].mExpression;
  5210. break;
  5211. }
  5212. checkIdx--;
  5213. }
  5214. error = mModule->Fail("Expanded string interpolation generates too many arguments. If string allocation was intended then consider adding a specifier such as 'scope'.", errorRef);
  5215. }
  5216. else if ((prevBindResult.mPrevVal != NULL) && (prevBindResult.mPrevVal->mBindType != NULL))
  5217. 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);
  5218. else
  5219. error = mModule->Fail(StrFormat("Too many arguments, expected %d fewer.", (int)argValues.size() - argExprIdx), errorRef);
  5220. if ((error != NULL) && (methodInstance->mMethodDef->mMethodDeclaration != NULL))
  5221. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("See method declaration"), methodInstance->mMethodDef->GetRefNode());
  5222. failed = true;
  5223. break;
  5224. }
  5225. break;
  5226. }
  5227. // Only create actual params if we're not just trying to bind the function
  5228. if ((prevBindResult.mPrevVal != NULL) && (!prevBindResult.mPrevVal->mWantsArgs))
  5229. break;
  5230. BfType* wantType = NULL;
  5231. bool wantsSplat = false;
  5232. if (expandedParamsElementType != NULL)
  5233. {
  5234. wantType = expandedParamsElementType;
  5235. }
  5236. else
  5237. {
  5238. wantsSplat = methodInstance->GetParamIsSplat(paramIdx);
  5239. if (methodInstance->IsImplicitCapture(paramIdx))
  5240. {
  5241. auto paramType = methodInstance->GetParamType(paramIdx);
  5242. if (mModule->mCurMethodInstance->IsMixin())
  5243. {
  5244. // Don't bother, also- can fail on captures
  5245. }
  5246. else
  5247. {
  5248. // static int captureIdx = 0;
  5249. // captureIdx++;
  5250. // int curCaptureIdx = captureIdx;
  5251. //
  5252. // if (curCaptureIdx == 0x91)
  5253. // {
  5254. // NOP;
  5255. // }
  5256. auto lookupVal = DoImplicitArgCapture(targetSrc, methodInstance, paramIdx, failed, BfImplicitParamKind_General, origTarget);
  5257. if (lookupVal)
  5258. {
  5259. if (wantsSplat)
  5260. {
  5261. SplatArgs(lookupVal, irArgs);
  5262. }
  5263. else if (paramType->IsRef())
  5264. {
  5265. irArgs.push_back(lookupVal.mValue);
  5266. }
  5267. else
  5268. PushArg(lookupVal, irArgs, true);
  5269. }
  5270. }
  5271. paramIdx++;
  5272. continue;
  5273. }
  5274. wantType = methodInstance->GetParamType(paramIdx);
  5275. if (wantType->IsSelf())
  5276. wantType = methodInstance->GetOwner();
  5277. if (wantType->IsVar())
  5278. {
  5279. // Case happens when we can't find the argument type
  5280. failed = true;
  5281. }
  5282. BfParamKind paramKind = methodInstance->GetParamKind(paramIdx);
  5283. if (paramKind == BfParamKind_Params)
  5284. {
  5285. //TODO: Check to see if it's a direct array pass
  5286. if (argIdx < (int)argValues.size())
  5287. {
  5288. auto argValue = argValues[argIdx].mTypedValue;
  5289. if ((argValue.IsParams()) /*&& (mModule->CanCast(argValue, wantType))*/)
  5290. isDirectPass = true;
  5291. }
  5292. if (!isDirectPass)
  5293. {
  5294. int numElements = BF_MAX((int)argValues.size() - argIdx, 0);
  5295. if (methodDef->mMethodType == BfMethodType_Extension)
  5296. numElements++;
  5297. if (wantType->IsArray())
  5298. {
  5299. BfArrayType* arrayType = (BfArrayType*)wantType;
  5300. mModule->PopulateType(arrayType, BfPopulateType_DataAndMethods);
  5301. expandedParamsElementType = arrayType->mGenericTypeInfo->mTypeGenericArguments[0];
  5302. int arrayClassSize = arrayType->mInstSize - expandedParamsElementType->mSize;
  5303. expandedParamsArray = BfTypedValue(mModule->AllocFromType(arrayType->GetUnderlyingType(), boxScopeData, BfIRValue(), mModule->GetConstValue(numElements), 1, BfAllocFlags_None),
  5304. arrayType, false);
  5305. BfResolvedArgs resolvedArgs;
  5306. MatchConstructor(targetSrc, NULL, expandedParamsArray, arrayType, resolvedArgs, false, false);
  5307. //TODO: Assert 'length' var is at slot 1
  5308. auto arrayBits = mModule->mBfIRBuilder->CreateBitCast(expandedParamsArray.mValue, mModule->mBfIRBuilder->MapType(arrayType->mBaseType));
  5309. int arrayLengthBitCount = arrayType->GetLengthBitCount();
  5310. if (arrayLengthBitCount == 0)
  5311. {
  5312. mModule->Fail("INTERNAL ERROR: Unable to find array 'length' field", targetSrc);
  5313. return BfTypedValue();
  5314. }
  5315. auto addr = mModule->mBfIRBuilder->CreateInBoundsGEP(arrayBits, 0, 1);
  5316. if (arrayLengthBitCount == 64)
  5317. mModule->mBfIRBuilder->CreateAlignedStore(mModule->GetConstValue64(numElements), addr, 8);
  5318. else
  5319. mModule->mBfIRBuilder->CreateAlignedStore(mModule->GetConstValue32(numElements), addr, 4);
  5320. PushArg(expandedParamsArray, irArgs);
  5321. }
  5322. else
  5323. {
  5324. auto genericTypeInst = wantType->ToGenericTypeInstance();
  5325. expandedParamsElementType = genericTypeInst->mGenericTypeInfo->mTypeGenericArguments[0];
  5326. expandedParamsArray = BfTypedValue(mModule->CreateAlloca(wantType), wantType, true);
  5327. expandedParamAlloca = mModule->CreateAlloca(genericTypeInst->mGenericTypeInfo->mTypeGenericArguments[0], true, NULL, mModule->GetConstValue(numElements));
  5328. mModule->mBfIRBuilder->CreateStore(expandedParamAlloca, mModule->mBfIRBuilder->CreateInBoundsGEP(expandedParamsArray.mValue, 0, 1));
  5329. mModule->mBfIRBuilder->CreateStore(mModule->GetConstValue(numElements), mModule->mBfIRBuilder->CreateInBoundsGEP(expandedParamsArray.mValue, 0, 2));
  5330. PushArg(expandedParamsArray, irArgs);
  5331. }
  5332. continue;
  5333. }
  5334. }
  5335. }
  5336. BfAstNode* arg = NULL;
  5337. bool hadMissingArg = false;
  5338. if (argExprIdx == -1)
  5339. arg = targetSrc;
  5340. if (argExprIdx >= 0)
  5341. {
  5342. if (argExprIdx < (int)argValues.size())
  5343. {
  5344. arg = argValues[argExprIdx].mExpression;
  5345. if (((argValues[argExprIdx].mArgFlags & BfArgFlag_StringInterpolateArg) != 0) && (!expandedParamsArray))
  5346. {
  5347. BfAstNode* errorRef = arg;
  5348. int checkIdx = argExprIdx - 1;
  5349. while (checkIdx >= 0)
  5350. {
  5351. if ((argValues[checkIdx].mArgFlags & BfArgFlag_StringInterpolateFormat) != 0)
  5352. {
  5353. errorRef = argValues[checkIdx].mExpression;
  5354. break;
  5355. }
  5356. checkIdx--;
  5357. }
  5358. 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);
  5359. }
  5360. if ((arg == NULL) && (argValues[argExprIdx].mExpression != NULL))
  5361. hadMissingArg = true;
  5362. }
  5363. else
  5364. hadMissingArg = true;
  5365. }
  5366. BfTypedValue argValue;
  5367. if (hadMissingArg)
  5368. {
  5369. if (expandedParamsArray)
  5370. break;
  5371. if ((argIdx >= (int) methodInstance->mDefaultValues.size()) || (!methodInstance->mDefaultValues[argIdx]))
  5372. {
  5373. BfAstNode* refNode = targetSrc;
  5374. if (argValues.size() > 0)
  5375. {
  5376. auto checkExpr = argValues.back().mExpression;
  5377. if (checkExpr != NULL)
  5378. refNode = checkExpr;
  5379. }
  5380. BfAstNode* prevNode = NULL;
  5381. if (targetSrc == NULL)
  5382. {
  5383. // We must be in BfModule::EmitCtorBody
  5384. }
  5385. else if (auto tupleExpr = BfNodeDynCastExact<BfTupleExpression>(targetSrc))
  5386. {
  5387. if (tupleExpr->mCommas.size() > 0)
  5388. prevNode = tupleExpr->mCommas.back();
  5389. else
  5390. prevNode = tupleExpr->mOpenParen;
  5391. if (tupleExpr->mCloseParen != NULL)
  5392. refNode = tupleExpr->mCloseParen;
  5393. }
  5394. else if (mModule->mParentNodeEntry != NULL)
  5395. {
  5396. if (auto objectCreateExpr = BfNodeDynCast<BfObjectCreateExpression>(mModule->mParentNodeEntry->mNode))
  5397. {
  5398. if (objectCreateExpr->mCommas.size() > 0)
  5399. prevNode = objectCreateExpr->mCommas.back();
  5400. else
  5401. prevNode = objectCreateExpr->mOpenToken;
  5402. if (objectCreateExpr->mCloseToken != NULL)
  5403. refNode = objectCreateExpr->mCloseToken;
  5404. if (auto newNode = BfNodeDynCast<BfNewNode>(objectCreateExpr->mNewNode))
  5405. {
  5406. if (newNode->mAllocNode == targetSrc)
  5407. refNode = targetSrc;
  5408. }
  5409. }
  5410. else if (auto invokeExpr = BfNodeDynCast<BfInvocationExpression>(mModule->mParentNodeEntry->mNode))
  5411. {
  5412. if (invokeExpr->mCommas.size() > 0)
  5413. prevNode = invokeExpr->mCommas.back();
  5414. else
  5415. prevNode = invokeExpr->mOpenParen;
  5416. if (invokeExpr->mCloseParen != NULL)
  5417. refNode = invokeExpr->mCloseParen;
  5418. }
  5419. }
  5420. if ((autoComplete != NULL) && (prevNode != NULL))
  5421. autoComplete->CheckEmptyStart(prevNode, wantType);
  5422. BfError* error = NULL;
  5423. if (mModule->mParentNodeEntry != NULL)
  5424. {
  5425. bool showCtorError = false;
  5426. if (auto ctorDeclaration = BfNodeDynCast<BfConstructorDeclaration>(mModule->mParentNodeEntry->mNode))
  5427. {
  5428. if (ctorDeclaration->mInitializer == NULL)
  5429. showCtorError = true;
  5430. }
  5431. if (auto typerDecl = BfNodeDynCast<BfTypeDeclaration>(mModule->mParentNodeEntry->mNode))
  5432. showCtorError = true;
  5433. if (showCtorError)
  5434. {
  5435. error = mModule->Fail(StrFormat("No parameterless constructor is available for base class. Consider calling base constructor '%s'.",
  5436. mModule->MethodToString(methodInstance).c_str()), refNode);
  5437. auto srcNode = mModule->mCurMethodInstance->mMethodDef->GetRefNode();
  5438. if ((autoComplete != NULL) && (autoComplete->CheckFixit(srcNode)))
  5439. autoComplete->FixitAddConstructor(mModule->mCurTypeInstance);
  5440. }
  5441. }
  5442. if (error == NULL)
  5443. error = mModule->Fail(StrFormat("Not enough parameters specified, expected %d more.", methodInstance->GetParamCount() - paramIdx), refNode);
  5444. if ((error != NULL) && (methodInstance->mMethodDef->mMethodDeclaration != NULL))
  5445. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("See method declaration"), methodInstance->mMethodDef->GetRefNode());
  5446. failed = true;
  5447. break;
  5448. }
  5449. auto foreignDefaultVal = methodInstance->mDefaultValues[argIdx];
  5450. auto foreignConst = methodInstance->GetOwner()->mConstHolder->GetConstant(foreignDefaultVal.mValue);
  5451. if (foreignConst->mConstType == BfConstType_AggZero)
  5452. {
  5453. // Allow this
  5454. }
  5455. else if (foreignConst->mTypeCode == BfTypeCode_NullPtr)
  5456. {
  5457. if (wantType->IsNullable())
  5458. {
  5459. argValue = mModule->GetDefaultTypedValue(wantType, false, BfDefaultValueKind_Addr);
  5460. }
  5461. }
  5462. else if (foreignConst->mConstType == BfConstType_GlobalVar)
  5463. {
  5464. auto globalVar = (BfGlobalVar*)foreignConst;
  5465. if (globalVar->mName[0] == '#')
  5466. {
  5467. if (strcmp(globalVar->mName, "#CallerLineNum") == 0)
  5468. {
  5469. argValue = BfTypedValue(mModule->GetConstValue(mModule->mCurFilePosition.mCurLine + 1), mModule->GetPrimitiveType(BfTypeCode_Int32));
  5470. }
  5471. else if (strcmp(globalVar->mName, "#CallerFilePath") == 0)
  5472. {
  5473. String filePath = "";
  5474. if (mModule->mCurFilePosition.mFileInstance != NULL)
  5475. filePath = mModule->mCurFilePosition.mFileInstance->mParser->mFileName;
  5476. argValue = BfTypedValue(mModule->GetStringObjectValue(filePath),
  5477. mModule->ResolveTypeDef(mModule->mCompiler->mStringTypeDef));
  5478. }
  5479. else if (strcmp(globalVar->mName, "#CallerFileName") == 0)
  5480. {
  5481. String filePath = "";
  5482. if (mModule->mCurFilePosition.mFileInstance != NULL)
  5483. filePath = mModule->mCurFilePosition.mFileInstance->mParser->mFileName;
  5484. argValue = BfTypedValue(mModule->GetStringObjectValue(GetFileName(filePath)),
  5485. mModule->ResolveTypeDef(mModule->mCompiler->mStringTypeDef));
  5486. }
  5487. else if (strcmp(globalVar->mName, "#CallerFileDir") == 0)
  5488. {
  5489. String filePath = "";
  5490. if (mModule->mCurFilePosition.mFileInstance != NULL)
  5491. filePath = mModule->mCurFilePosition.mFileInstance->mParser->mFileName;
  5492. argValue = BfTypedValue(mModule->GetStringObjectValue(GetFileDir(filePath)),
  5493. mModule->ResolveTypeDef(mModule->mCompiler->mStringTypeDef));
  5494. }
  5495. else if (strcmp(globalVar->mName, "#CallerMemberName") == 0)
  5496. {
  5497. String memberName = "";
  5498. if (mModule->mCurMethodInstance != NULL)
  5499. memberName = mModule->MethodToString(mModule->mCurMethodInstance);
  5500. argValue = BfTypedValue(mModule->GetStringObjectValue(memberName),
  5501. mModule->ResolveTypeDef(mModule->mCompiler->mStringTypeDef));
  5502. }
  5503. else if (strcmp(globalVar->mName, "#CallerProject") == 0)
  5504. {
  5505. String projectName = "";
  5506. if (mModule->mCurMethodInstance != NULL)
  5507. projectName = mModule->mCurMethodInstance->mMethodDef->mDeclaringType->mProject->mName;
  5508. argValue = BfTypedValue(mModule->GetStringObjectValue(projectName),
  5509. mModule->ResolveTypeDef(mModule->mCompiler->mStringTypeDef));
  5510. }
  5511. else
  5512. {
  5513. argValue = mModule->GetCompilerFieldValue(globalVar->mName);
  5514. }
  5515. }
  5516. }
  5517. else if (foreignConst->mConstType == BfConstType_GEP32_2)
  5518. {
  5519. auto constGep32_2 = (BfConstantGEP32_2*)foreignConst;
  5520. auto gepTarget = methodInstance->GetOwner()->mConstHolder->GetConstantById(constGep32_2->mTarget);
  5521. if (gepTarget->mConstType == BfConstType_GlobalVar)
  5522. {
  5523. auto globalVar = (BfGlobalVar*)gepTarget;
  5524. if (globalVar->mName[0] == '#')
  5525. {
  5526. if (strcmp(globalVar->mName, "#CallerExpression") == 0)
  5527. {
  5528. int exprIdx = constGep32_2->mIdx1;
  5529. if ((exprIdx >= 0) && (exprIdx <= (int)argValues.size()))
  5530. {
  5531. auto expr = argValues[exprIdx].mExpression;
  5532. if (expr != NULL)
  5533. {
  5534. argValue = BfTypedValue(mModule->GetStringObjectValue(expr->ToString()),
  5535. mModule->ResolveTypeDef(mModule->mCompiler->mStringTypeDef));
  5536. }
  5537. }
  5538. else
  5539. {
  5540. mModule->Fail("CallerExpression index out of bounds", targetSrc);
  5541. argValue = BfTypedValue(mModule->GetStringObjectValue(""),
  5542. mModule->ResolveTypeDef(mModule->mCompiler->mStringTypeDef));
  5543. }
  5544. }
  5545. }
  5546. }
  5547. }
  5548. if (!argValue)
  5549. {
  5550. argValue = mModule->GetTypedValueFromConstant(foreignConst, methodInstance->GetOwner()->mConstHolder, foreignDefaultVal.mType);
  5551. if (!argValue)
  5552. mModule->Fail("Default parameter value failed", targetSrc);
  5553. mModule->mBfIRBuilder->PopulateType(foreignDefaultVal.mType);
  5554. }
  5555. }
  5556. else
  5557. {
  5558. if (argExprIdx == -1)
  5559. argValue = target;
  5560. else
  5561. argValue = argValues[argExprIdx].mTypedValue;
  5562. if ((argValue.IsParams()) && (!isDirectPass))
  5563. {
  5564. BfAstNode* refNode = arg;
  5565. if (auto unaryOperatorExpr = BfNodeDynCast<BfUnaryOperatorExpression>(refNode))
  5566. refNode = unaryOperatorExpr->mOpToken;
  5567. mModule->Warn(0, "Unused 'params' expression", refNode);
  5568. }
  5569. if (wantType->IsMethodRef())
  5570. {
  5571. auto expr = argValues[argExprIdx].mExpression;
  5572. if (expr != NULL)
  5573. SetMethodElementType(expr);
  5574. if (!argValue)
  5575. argValue = mModule->CreateValueFromExpression(BfNodeDynCast<BfExpression>(arg), wantType, BfEvalExprFlags_NoCast);
  5576. // Add any implicit captures now
  5577. auto methodRefType = (BfMethodRefType*)wantType;
  5578. BfMethodInstance* useMethodInstance = methodRefType->mMethodRef;
  5579. for (int dataIdx = 0; dataIdx < methodRefType->GetCaptureDataCount(); dataIdx++)
  5580. {
  5581. int paramIdx = methodRefType->GetParamIdxFromDataIdx(dataIdx);
  5582. auto lookupVal = DoImplicitArgCapture(arg, useMethodInstance, paramIdx, failed, BfImplicitParamKind_General, argValue);
  5583. if (lookupVal)
  5584. {
  5585. if (methodRefType->WantsDataPassedAsSplat(dataIdx))
  5586. SplatArgs(lookupVal, irArgs);
  5587. else
  5588. irArgs.push_back(lookupVal.mValue);
  5589. }
  5590. }
  5591. paramIdx++;
  5592. argIdx++;
  5593. continue;
  5594. }
  5595. else if (argExprIdx >= 0)
  5596. {
  5597. BfParamKind paramKind = BfParamKind_Normal;
  5598. BfIdentifierNode* paramNameNode = NULL;
  5599. if (paramIdx < methodInstance->GetParamCount())
  5600. {
  5601. paramKind = methodInstance->GetParamKind(paramIdx);
  5602. paramNameNode = methodInstance->GetParamNameNode(paramIdx);
  5603. }
  5604. argValues[argExprIdx].mExpectedType = wantType;
  5605. argValue = ResolveArgValue(argValues[argExprIdx], wantType, NULL, paramKind, paramNameNode);
  5606. }
  5607. }
  5608. if (!argValue)
  5609. {
  5610. failed = true;
  5611. }
  5612. if (argValue)
  5613. {
  5614. if ((isThis) && (argValue.mType->IsRef()))
  5615. {
  5616. // Convert a 'ref this' to a 'this*'
  5617. argValue.mType = mModule->CreatePointerType(argValue.mType->GetUnderlyingType());
  5618. }
  5619. BfAstNode* refNode = arg;
  5620. if (refNode == NULL)
  5621. refNode = targetSrc;
  5622. if (mModule->mCurMethodState != NULL)
  5623. {
  5624. SetAndRestoreValue<BfScopeData*> prevScopeData(mModule->mCurMethodState->mOverrideScope, boxScopeData);
  5625. argValue = mModule->Cast(refNode, argValue, wantType);
  5626. }
  5627. else
  5628. argValue = mModule->Cast(refNode, argValue, wantType);
  5629. if (!argValue)
  5630. {
  5631. if ((argExprIdx < (int)argValues.size()) && ((argValues[argExprIdx].mArgFlags & BfArgFlag_StringInterpolateArg) != 0))
  5632. {
  5633. BfAstNode* errorRef = NULL;
  5634. int checkIdx = argExprIdx - 1;
  5635. while (checkIdx >= 0)
  5636. {
  5637. if ((argValues[checkIdx].mArgFlags & BfArgFlag_StringInterpolateFormat) != 0)
  5638. {
  5639. errorRef = argValues[checkIdx].mExpression;
  5640. break;
  5641. }
  5642. checkIdx--;
  5643. }
  5644. if (errorRef != NULL)
  5645. mModule->Warn(0, "If string allocation was intended then consider adding a specifier such as 'scope'.", errorRef);
  5646. }
  5647. failed = true;
  5648. }
  5649. else if ((wantType->IsComposite()) && (!expandedParamsArray))
  5650. {
  5651. if (methodInstance->mIsIntrinsic)
  5652. {
  5653. // Intrinsics can handle structs either by value or address
  5654. }
  5655. else
  5656. {
  5657. // We need to make a temp and get the addr of that
  5658. if ((!wantsSplat) && (!argValue.IsValuelessType()) && (!argValue.IsAddr()))
  5659. {
  5660. argValue = mModule->MakeAddressable(argValue);
  5661. }
  5662. }
  5663. }
  5664. else if (!wantType->IsRef())
  5665. argValue = mModule->LoadValue(argValue);
  5666. }
  5667. if (expandedParamsArray)
  5668. {
  5669. if (argValue)
  5670. {
  5671. if (expandedParamAlloca)
  5672. {
  5673. argValue = mModule->LoadValue(argValue);
  5674. auto addr = mModule->mBfIRBuilder->CreateInBoundsGEP(expandedParamAlloca, extendedParamIdx);
  5675. auto storeInst = mModule->mBfIRBuilder->CreateAlignedStore(argValue.mValue, addr, argValue.mType->mAlign);
  5676. }
  5677. else
  5678. {
  5679. auto firstElem = mModule->GetFieldByName(expandedParamsArray.mType->ToTypeInstance(), "mFirstElement");
  5680. if (firstElem != NULL)
  5681. {
  5682. argValue = mModule->LoadValue(argValue);
  5683. auto firstAddr = mModule->mBfIRBuilder->CreateInBoundsGEP(expandedParamsArray.mValue, 0, firstElem->mDataIdx);
  5684. auto indexedAddr = mModule->CreateIndexedValue(argValue.mType, firstAddr, extendedParamIdx);
  5685. if (argValue.IsSplat())
  5686. mModule->AggregateSplatIntoAddr(argValue, indexedAddr);
  5687. else
  5688. mModule->mBfIRBuilder->CreateAlignedStore(argValue.mValue, indexedAddr, argValue.mType->mAlign);
  5689. }
  5690. }
  5691. }
  5692. extendedParamIdx++;
  5693. }
  5694. else
  5695. {
  5696. if ((paramIdx == 0) && (methodInstance->GetParamName(paramIdx) == "this") && (wantType->IsPointer()))
  5697. {
  5698. auto underlyingType = wantType->GetUnderlyingType();
  5699. mModule->PopulateType(underlyingType, BfPopulateType_Data);
  5700. if (underlyingType->IsValuelessType())
  5701. {
  5702. // We don't actually pass a 'this' pointer for mut methods on valueless structs
  5703. argIdx++;
  5704. paramIdx++;
  5705. continue;
  5706. }
  5707. }
  5708. if (argValue)
  5709. {
  5710. if (isThis)
  5711. PushThis(targetSrc, argValue, methodInstance, irArgs);
  5712. else if (wantsSplat)
  5713. SplatArgs(argValue, irArgs);
  5714. else
  5715. PushArg(argValue, irArgs, true, false, methodInstance->mIsIntrinsic);
  5716. }
  5717. paramIdx++;
  5718. }
  5719. argIdx++;
  5720. }
  5721. if (failed)
  5722. {
  5723. // Process the other unused arguments
  5724. while (argIdx < argValues.size())
  5725. {
  5726. mModule->AssertErrorState();
  5727. auto argValue = argValues[argIdx].mTypedValue;
  5728. if ((argValues[argIdx].mArgFlags & (BfArgFlag_DelegateBindAttempt | BfArgFlag_LambdaBindAttempt | BfArgFlag_UnqualifiedDotAttempt | BfArgFlag_DeferredEval | BfArgFlag_VariableDeclaration | BfArgFlag_UninitializedExpr)) != 0)
  5729. {
  5730. if (!argValue)
  5731. {
  5732. auto expr = BfNodeDynCast<BfExpression>(argValues[argIdx].mExpression);
  5733. if (expr != NULL)
  5734. argValue = mModule->CreateValueFromExpression(expr);
  5735. }
  5736. }
  5737. argIdx++;
  5738. }
  5739. mModule->AssertErrorState();
  5740. return mModule->GetDefaultTypedValue(returnType, false, BfDefaultValueKind_Addr);
  5741. }
  5742. prevBindResult.Restore();
  5743. if (!methodDef->mIsStatic)
  5744. {
  5745. bool ignoreVirtualError = (mModule->mBfIRBuilder->mIgnoreWrites) && (mModule->mCurMethodInstance != NULL) && (mModule->mCurMethodInstance->mIsForeignMethodDef);
  5746. if ((methodInstance->GetOwner()->IsInterface()) && (!target.mType->IsGenericParam()) && (!target.mType->IsConcreteInterfaceType()) &&
  5747. (!mModule->mCurTypeInstance->IsInterface()) && (!ignoreVirtualError))
  5748. {
  5749. if (methodInstance->mVirtualTableIdx == -1)
  5750. {
  5751. mModule->PopulateType(methodInstance->GetOwner(), BfPopulateType_DataAndMethods);
  5752. }
  5753. if (methodInstance->mVirtualTableIdx == -1)
  5754. {
  5755. if (methodInstance->mMethodDef->mIsConcrete)
  5756. {
  5757. 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);
  5758. }
  5759. else if (methodInstance->HasSelf())
  5760. {
  5761. 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);
  5762. }
  5763. else
  5764. {
  5765. if ((bypassVirtual) && (mModule->mCurTypeInstance->IsInterface()))
  5766. {
  5767. // Allow a base call to be defined
  5768. }
  5769. else if ((methodInstance->IsSpecializedGenericMethod()) && (origTarget) && (!origTarget.mType->IsInterface()))
  5770. {
  5771. if (!mModule->mBfIRBuilder->mIgnoreWrites)
  5772. mModule->AssertErrorState();
  5773. }
  5774. else if ((!mModule->mCurMethodInstance->mIsUnspecialized))
  5775. {
  5776. // Compiler error?
  5777. String errorString = "Unable to dynamically dispatch '%s'";
  5778. if (methodInstance->IsSpecializedGenericMethod())
  5779. errorString = "Unable to dynamically dispatch '%s' because generic methods can only be directly dispatched";
  5780. if (methodInstance->mReturnType->IsConcreteInterfaceType())
  5781. errorString = "Unable to dynamically dispatch '%s' because the concrete return type is unknown";
  5782. mModule->Fail(StrFormat(errorString.c_str(), mModule->MethodToString(methodInstance).c_str()), targetSrc);
  5783. }
  5784. //BF_ASSERT(mModule->mCurMethodInstance->mIsUnspecialized);
  5785. }
  5786. if (mFunctionBindResult != NULL)
  5787. {
  5788. mFunctionBindResult->mMethodInstance = methodInstance;
  5789. mFunctionBindResult->mTarget = target;
  5790. mFunctionBindResult->mFunc = moduleMethodInstance.mFunc;
  5791. for (auto arg : irArgs)
  5792. mFunctionBindResult->mIRArgs.push_back(arg);
  5793. }
  5794. return mModule->GetDefaultTypedValue(returnType);
  5795. }
  5796. }
  5797. }
  5798. else
  5799. {
  5800. //BF_ASSERT(!methodInstance->GetOwner()->IsInterface());
  5801. }
  5802. if (target.mType != NULL)
  5803. {
  5804. // When we call a method from a static ctor, that method could access static fields so we need to make sure
  5805. // the type has been initialized
  5806. auto targetTypeInst = target.mType->ToTypeInstance();
  5807. if (targetTypeInst != NULL)
  5808. mModule->CheckStaticAccess(targetTypeInst);
  5809. }
  5810. auto func = moduleMethodInstance.mFunc;
  5811. BfTypedValue result = CreateCall(targetSrc, methodInstance, func, bypassVirtual, irArgs);
  5812. if ((result.mType != NULL) && (result.mType->IsVar()) && (mModule->mCompiler->mIsResolveOnly))
  5813. mModule->Fail("Method return type reference failed to resolve", targetSrc);
  5814. return result;
  5815. }
  5816. BfTypedValue BfExprEvaluator::MatchConstructor(BfAstNode* targetSrc, BfMethodBoundExpression* methodBoundExpr, BfTypedValue target, BfTypeInstance* targetType, BfResolvedArgs& argValues, bool callCtorBodyOnly, bool allowAppendAlloc, BfTypedValue* appendIndexValue)
  5817. {
  5818. // Temporarily disable so we don't capture calls in params
  5819. SetAndRestoreValue<BfFunctionBindResult*> prevBindResult(mFunctionBindResult, NULL);
  5820. static int sCtorCount = 0;
  5821. sCtorCount++;
  5822. BfMethodMatcher methodMatcher(targetSrc, mModule, "", argValues.mResolvedArgs, NULL);
  5823. methodMatcher.mBfEvalExprFlags = mBfEvalExprFlags;
  5824. BfTypeVector typeGenericArguments;
  5825. auto curTypeInst = targetType;
  5826. auto curTypeDef = targetType->mTypeDef;
  5827. BfProtectionCheckFlags protectionCheckFlags = BfProtectionCheckFlag_None;
  5828. auto activeTypeDef = mModule->GetActiveTypeDef();
  5829. auto visibleProjectSet = mModule->GetVisibleProjectSet();
  5830. bool isFailurePass = false;
  5831. for (int pass = 0; pass < 2; pass++)
  5832. {
  5833. isFailurePass = pass == 1;
  5834. curTypeDef->PopulateMemberSets();
  5835. BfMethodDef* nextMethodDef = NULL;
  5836. BfMemberSetEntry* entry;
  5837. if (curTypeDef->mMethodSet.TryGetWith(String("__BfCtor"), &entry))
  5838. nextMethodDef = (BfMethodDef*)entry->mMemberDef;
  5839. while (nextMethodDef != NULL)
  5840. {
  5841. auto checkMethod = nextMethodDef;
  5842. nextMethodDef = nextMethodDef->mNextWithSameName;
  5843. if ((isFailurePass) && (checkMethod->mMethodDeclaration == NULL))
  5844. continue; // Don't match private default ctor if there's a user-defined one
  5845. if (checkMethod->mIsStatic)
  5846. continue;
  5847. if ((checkMethod->mDeclaringType->IsExtension()) && (mModule->mAttributeState != NULL) && (mModule->mAttributeState->mCustomAttributes != NULL) &&
  5848. (mModule->mAttributeState->mCustomAttributes->Contains(mModule->mCompiler->mNoExtensionAttributeTypeDef)))
  5849. {
  5850. mModule->mAttributeState->mUsed = true;
  5851. continue;
  5852. }
  5853. if (!mModule->IsInSpecializedSection())
  5854. {
  5855. if ((!curTypeInst->IsTypeMemberIncluded(checkMethod->mDeclaringType, activeTypeDef, mModule)) ||
  5856. (!curTypeInst->IsTypeMemberAccessible(checkMethod->mDeclaringType, visibleProjectSet)))
  5857. continue;
  5858. }
  5859. auto checkProt = checkMethod->mProtection;
  5860. if (!isFailurePass)
  5861. {
  5862. if (callCtorBodyOnly)
  5863. {
  5864. if (curTypeDef != mModule->mCurTypeInstance->mTypeDef)
  5865. {
  5866. // We're calling the base class's ctor from a derived class
  5867. if (checkProt <= BfProtection_Private)
  5868. continue;
  5869. }
  5870. }
  5871. else
  5872. {
  5873. if ((checkProt == BfProtection_Protected) || (checkProt == BfProtection_ProtectedInternal)) // Treat protected constructors as private
  5874. checkProt = BfProtection_Private;
  5875. if (!mModule->CheckProtection(protectionCheckFlags, curTypeInst, checkMethod->mDeclaringType->mProject, checkProt, curTypeInst))
  5876. continue;
  5877. }
  5878. }
  5879. methodMatcher.CheckMethod(NULL, curTypeInst, checkMethod, isFailurePass);
  5880. }
  5881. if ((methodMatcher.mBestMethodDef != NULL) || (methodMatcher.mBackupMethodDef != NULL))
  5882. break;
  5883. }
  5884. if (methodMatcher.mBestMethodDef == NULL)
  5885. methodMatcher.mBestMethodDef = methodMatcher.mBackupMethodDef;
  5886. if (methodMatcher.mBestMethodDef == NULL)
  5887. {
  5888. mModule->Fail("No constructor available", targetSrc);
  5889. return BfTypedValue();
  5890. }
  5891. auto methodDef = methodMatcher.mBestMethodDef;
  5892. if (mModule->mCompiler->mResolvePassData != NULL)
  5893. mModule->mCompiler->mResolvePassData->HandleMethodReference(targetSrc, curTypeInst->mTypeDef, methodDef);
  5894. // There should always be a constructor
  5895. BF_ASSERT(methodMatcher.mBestMethodDef != NULL);
  5896. auto moduleMethodInstance = mModule->GetMethodInstance(methodMatcher.mBestMethodTypeInstance, methodMatcher.mBestMethodDef, methodMatcher.mBestMethodGenericArguments);
  5897. BfAutoComplete* autoComplete = GetAutoComplete();
  5898. if (autoComplete != NULL)
  5899. {
  5900. BfTypeInstance* resolvedTypeInstance = target.mType->ToTypeInstance();
  5901. auto ctorDecl = BfNodeDynCast<BfConstructorDeclaration>(methodDef->mMethodDeclaration);
  5902. if ((autoComplete->mIsGetDefinition) && (autoComplete->IsAutocompleteNode(targetSrc)) && (!BfNodeIsA<BfDelegateBindExpression>(targetSrc)))
  5903. {
  5904. if ((autoComplete->mDefMethod == NULL) && (autoComplete->mDefField == NULL) &&
  5905. (autoComplete->mDefProp == NULL)
  5906. && ((autoComplete->mDefType == NULL) || (autoComplete->mDefType == resolvedTypeInstance->mTypeDef)))
  5907. {
  5908. // Do we need to do this mDefType setting? If we do, then make sure we only get the element type of generics and such
  5909. //autoComplete->mDefType = resolvedTypeInstance->mTypeDef;
  5910. if (ctorDecl != NULL)
  5911. autoComplete->SetDefinitionLocation(ctorDecl->mThisToken, true);
  5912. else if (resolvedTypeInstance->mTypeDef->mTypeDeclaration != NULL)
  5913. autoComplete->SetDefinitionLocation(resolvedTypeInstance->mTypeDef->mTypeDeclaration->mNameNode, true);
  5914. }
  5915. }
  5916. else if ((autoComplete->mResolveType == BfResolveType_GetResultString) && (autoComplete->IsAutocompleteNode(targetSrc)) &&
  5917. (moduleMethodInstance.mMethodInstance != NULL))
  5918. {
  5919. autoComplete->mResultString = ":";
  5920. autoComplete->mResultString += mModule->MethodToString(moduleMethodInstance.mMethodInstance);
  5921. }
  5922. }
  5923. BfConstructorDeclaration* ctorDecl = (BfConstructorDeclaration*)methodMatcher.mBestMethodDef->mMethodDeclaration;
  5924. if ((methodMatcher.mBestMethodDef->mHasAppend) && (targetType->IsObject()))
  5925. {
  5926. if (!allowAppendAlloc)
  5927. {
  5928. if (mModule->mCurMethodInstance->mMethodDef->mMethodDeclaration == NULL)
  5929. mModule->Fail("Constructors with append allocations cannot be called from a default constructor. Considering adding an explicit default constructor with the [AllowAppend] specifier.", targetSrc);
  5930. else
  5931. mModule->Fail("Constructors with append allocations cannot be called from a constructor without [AllowAppend] specified.", targetSrc);
  5932. }
  5933. else
  5934. {
  5935. BfResolvedArg resolvedArg;
  5936. if (appendIndexValue != NULL)
  5937. {
  5938. resolvedArg.mTypedValue = *appendIndexValue;
  5939. }
  5940. else
  5941. {
  5942. auto intPtrType = mModule->GetPrimitiveType(BfTypeCode_IntPtr);
  5943. auto intPtrRefType = mModule->CreateRefType(intPtrType);
  5944. if (target.mValue.IsFake())
  5945. {
  5946. resolvedArg.mTypedValue = BfTypedValue(mModule->mBfIRBuilder->GetFakeVal(), intPtrRefType);
  5947. }
  5948. else
  5949. {
  5950. BFMODULE_FATAL(mModule, "Bad");
  5951. }
  5952. }
  5953. methodMatcher.mArguments.Insert(0, resolvedArg);
  5954. }
  5955. }
  5956. if (isFailurePass)
  5957. mModule->Fail(StrFormat("'%s' is inaccessible due to its protection level", mModule->MethodToString(moduleMethodInstance.mMethodInstance).c_str()), targetSrc);
  5958. prevBindResult.Restore();
  5959. return CreateCall(methodMatcher.mTargetSrc, target, BfTypedValue(), methodMatcher.mBestMethodDef, moduleMethodInstance, false, methodMatcher.mArguments);
  5960. }
  5961. static int sInvocationIdx = 0;
  5962. BfTypedValue BfExprEvaluator::ResolveArgValue(BfResolvedArg& resolvedArg, BfType* wantType, BfTypedValue* receivingValue, BfParamKind paramKind, BfIdentifierNode* paramNameNode)
  5963. {
  5964. BfTypedValue argValue = resolvedArg.mTypedValue;
  5965. if ((resolvedArg.mArgFlags & (BfArgFlag_DelegateBindAttempt | BfArgFlag_LambdaBindAttempt | BfArgFlag_UnqualifiedDotAttempt | BfArgFlag_DeferredEval)) != 0)
  5966. {
  5967. if ((!argValue) || (argValue.mValue.IsFake()) || (resolvedArg.mWantsRecalc))
  5968. {
  5969. resolvedArg.mWantsRecalc = false;
  5970. auto expr = BfNodeDynCast<BfExpression>(resolvedArg.mExpression);
  5971. if (expr != NULL)
  5972. {
  5973. BfExprEvaluator exprEvaluator(mModule);
  5974. exprEvaluator.mReceivingValue = receivingValue;
  5975. BfEvalExprFlags flags = (BfEvalExprFlags)((mBfEvalExprFlags & BfEvalExprFlags_NoAutoComplete) | BfEvalExprFlags_NoCast);
  5976. if ((paramKind == BfParamKind_Params) || (paramKind == BfParamKind_DelegateParam))
  5977. flags = (BfEvalExprFlags)(flags | BfEvalExprFlags_AllowParamsExpr);
  5978. argValue = mModule->CreateValueFromExpression(exprEvaluator, expr, wantType, flags);
  5979. if ((argValue) && (argValue.mType != wantType) && (wantType != NULL))
  5980. {
  5981. if ((mDeferScopeAlloc != NULL) && (wantType == mModule->mContext->mBfObjectType))
  5982. {
  5983. BfAllocTarget allocTarget(mDeferScopeAlloc);
  5984. argValue = mModule->BoxValue(expr, argValue, wantType, allocTarget);
  5985. }
  5986. else
  5987. argValue = mModule->Cast(expr, argValue, wantType);
  5988. }
  5989. }
  5990. }
  5991. }
  5992. else if ((resolvedArg.mArgFlags & (BfArgFlag_DeferredValue)) != 0)
  5993. {
  5994. // We should have already had an error on the first call
  5995. SetAndRestoreValue<bool> prevIgnoreErrors(mModule->mIgnoreErrors, mModule->mHadBuildError);
  5996. auto expr = BfNodeDynCast<BfExpression>(resolvedArg.mExpression);
  5997. BF_ASSERT(expr != NULL);
  5998. argValue = mModule->CreateValueFromExpression(expr, wantType, (BfEvalExprFlags)(BfEvalExprFlags_NoCast | BfEvalExprFlags_AllowRefExpr | BfEvalExprFlags_AllowOutExpr));
  5999. if ((argValue) && (wantType != NULL))
  6000. argValue = mModule->Cast(expr, argValue, wantType);
  6001. }
  6002. else if ((resolvedArg.mArgFlags & (BfArgFlag_UntypedDefault)) != 0)
  6003. {
  6004. argValue = mModule->GetDefaultTypedValue(wantType);
  6005. }
  6006. else if ((resolvedArg.mArgFlags & (BfArgFlag_VariableDeclaration | BfArgFlag_UninitializedExpr)) != 0)
  6007. {
  6008. auto variableDeclaration = BfNodeDynCast<BfVariableDeclaration>(resolvedArg.mExpression);
  6009. auto variableType = wantType;
  6010. bool isLet = (variableDeclaration != NULL) && (variableDeclaration->mTypeRef->IsExact<BfLetTypeReference>());
  6011. bool isVar = (variableDeclaration == NULL) || (variableDeclaration->mTypeRef->IsExact<BfVarTypeReference>());
  6012. if (mModule->mCurMethodState->mPendingNullConditional != NULL)
  6013. {
  6014. mModule->Fail("Variables cannot be declared in method arguments inside null conditional expressions", variableDeclaration);
  6015. }
  6016. if ((!isLet) && (!isVar))
  6017. {
  6018. if (variableType->IsVar())
  6019. {
  6020. auto resolvedType = mModule->ResolveTypeRef(variableDeclaration->mTypeRef);
  6021. if (resolvedType != NULL)
  6022. variableType = resolvedType;
  6023. }
  6024. else
  6025. {
  6026. mModule->Fail("Only 'ref' or 'var' variables can be declared in method arguments", variableDeclaration);
  6027. auto autoComplete = GetAutoComplete();
  6028. if (autoComplete != NULL)
  6029. autoComplete->CheckTypeRef(variableDeclaration->mTypeRef, true, true);
  6030. }
  6031. }
  6032. else
  6033. {
  6034. if (variableType->IsVar())
  6035. {
  6036. mModule->Fail("Variable type required for 'var' parameter types", variableDeclaration);
  6037. }
  6038. }
  6039. if (wantType->IsRef())
  6040. {
  6041. auto refType = (BfRefType*)wantType;
  6042. variableType = refType->mElementType;
  6043. }
  6044. if ((variableDeclaration != NULL) && (variableDeclaration->mInitializer != NULL))
  6045. {
  6046. mModule->Fail("Initializers cannot be used when declaring variables for 'out' parameters", variableDeclaration->mEqualsNode);
  6047. mModule->CreateValueFromExpression(variableDeclaration->mInitializer, variableType, BfEvalExprFlags_NoCast);
  6048. }
  6049. BfLocalVariable* localVar = new BfLocalVariable();
  6050. if ((variableDeclaration != NULL) && (variableDeclaration->mNameNode != NULL))
  6051. {
  6052. localVar->mName = variableDeclaration->mNameNode->ToString();
  6053. localVar->mNameNode = BfNodeDynCast<BfIdentifierNode>(variableDeclaration->mNameNode);
  6054. }
  6055. else
  6056. {
  6057. if (paramNameNode != NULL)
  6058. {
  6059. localVar->mName = "__";
  6060. paramNameNode->ToString(localVar->mName);
  6061. localVar->mName += "_";
  6062. localVar->mName += StrFormat("%d", mModule->mCurMethodState->GetRootMethodState()->mCurLocalVarId);
  6063. }
  6064. else
  6065. localVar->mName = "__" + StrFormat("%d", mModule->mCurMethodState->GetRootMethodState()->mCurLocalVarId);
  6066. }
  6067. localVar->mResolvedType = variableType;
  6068. if (!variableType->IsValuelessType())
  6069. localVar->mAddr = mModule->CreateAlloca(variableType);
  6070. localVar->mIsReadOnly = isLet;
  6071. localVar->mReadFromId = 0;
  6072. localVar->mWrittenToId = 0;
  6073. localVar->mAssignedKind = BfLocalVarAssignKind_Unconditional;
  6074. mModule->CheckVariableDef(localVar);
  6075. localVar->Init();
  6076. mModule->AddLocalVariableDef(localVar, true);
  6077. CheckVariableDeclaration(resolvedArg.mExpression, false, false, false);
  6078. argValue = BfTypedValue(localVar->mAddr, mModule->CreateRefType(variableType, BfRefType::RefKind_Out));
  6079. auto curScope = mModule->mCurMethodState->mCurScope;
  6080. if (curScope->mScopeKind == BfScopeKind_StatementTarget)
  6081. {
  6082. // Move this variable into the parent scope
  6083. curScope->mLocalVarStart = (int)mModule->mCurMethodState->mLocals.size();
  6084. }
  6085. }
  6086. return argValue;
  6087. }
  6088. BfTypedValue BfExprEvaluator::CheckEnumCreation(BfAstNode* targetSrc, BfTypeInstance* enumType, const StringImpl& caseName, BfResolvedArgs& argValues)
  6089. {
  6090. auto activeTypeDef = mModule->GetActiveTypeDef();
  6091. mModule->mBfIRBuilder->PopulateType(enumType);
  6092. auto resolvePassData = mModule->mCompiler->mResolvePassData;
  6093. // if (resolvePassData != NULL)
  6094. // {
  6095. // if (mModule->mParentNodeEntry != NULL)
  6096. // {
  6097. // if (auto invocationExpr = BfNodeDynCast<BfInvocationExpression>(mModule->mParentNodeEntry->mNode))
  6098. // {
  6099. // if (auto memberRefExpr = BfNodeDynCast<BfMemberReferenceExpression>(invocationExpr->mTarget))
  6100. // {
  6101. // BfAstNode* dotNode = memberRefExpr->mDotToken;
  6102. // BfAstNode* nameNode = targetSrc;
  6103. // String filter;
  6104. // auto autoComplete = resolvePassData->mAutoComplete;
  6105. // if ((autoComplete != NULL) && (autoComplete->InitAutocomplete(dotNode, nameNode, filter)))
  6106. // autoComplete->AddEnumTypeMembers(enumType, caseName, false, enumType == mModule->mCurTypeInstance);
  6107. // }
  6108. // }
  6109. // }
  6110. // }
  6111. for (int fieldIdx = 0; fieldIdx < (int)enumType->mFieldInstances.size(); fieldIdx++)
  6112. {
  6113. auto fieldInstance = &enumType->mFieldInstances[fieldIdx];
  6114. auto fieldDef = fieldInstance->GetFieldDef();
  6115. if (fieldDef == NULL)
  6116. continue;
  6117. if ((fieldInstance->mIsEnumPayloadCase) && (fieldDef->mName == caseName))
  6118. {
  6119. if ((!enumType->IsTypeMemberIncluded(fieldDef->mDeclaringType, activeTypeDef, mModule)) ||
  6120. (!enumType->IsTypeMemberAccessible(fieldDef->mDeclaringType, activeTypeDef)))
  6121. continue;
  6122. auto autoComplete = GetAutoComplete();
  6123. if ((autoComplete != NULL) && (autoComplete->mIsCapturingMethodMatchInfo))
  6124. {
  6125. BfAutoComplete::MethodMatchEntry methodMatchEntry;
  6126. methodMatchEntry.mPayloadEnumField = fieldInstance;
  6127. methodMatchEntry.mTypeInstance = enumType;
  6128. methodMatchEntry.mCurMethodInstance = mModule->mCurMethodInstance;
  6129. autoComplete->mMethodMatchInfo->mInstanceList.push_back(methodMatchEntry);
  6130. }
  6131. if (resolvePassData != NULL)
  6132. {
  6133. BfAstNode* nameNode = targetSrc;
  6134. if (resolvePassData->mGetSymbolReferenceKind == BfGetSymbolReferenceKind_Field)
  6135. resolvePassData->HandleFieldReference(nameNode, enumType->mTypeDef, fieldDef);
  6136. }
  6137. BfIRValue enumValue;
  6138. BfTypedValue result;
  6139. if ((mReceivingValue != NULL) && (mReceivingValue->mType == enumType) && (mReceivingValue->IsAddr()))
  6140. {
  6141. result = *mReceivingValue;
  6142. mReceivingValue = NULL;
  6143. enumValue = result.mValue;
  6144. }
  6145. else
  6146. {
  6147. mResultIsTempComposite = true;
  6148. enumValue = mModule->CreateAlloca(enumType);
  6149. result = BfTypedValue(enumValue, fieldInstance->mOwner, BfTypedValueKind_TempAddr);
  6150. }
  6151. BF_ASSERT(fieldInstance->mResolvedType->IsTuple());
  6152. auto tupleType = (BfTypeInstance*)fieldInstance->mResolvedType;
  6153. mModule->mBfIRBuilder->PopulateType(tupleType);
  6154. BfIRValue fieldPtr;
  6155. BfIRValue tuplePtr;
  6156. if (!tupleType->IsValuelessType())
  6157. {
  6158. fieldPtr = mModule->mBfIRBuilder->CreateInBoundsGEP(enumValue, 0, 1);
  6159. auto tuplePtrType = mModule->CreatePointerType(tupleType);
  6160. auto mappedPtrType = mModule->mBfIRBuilder->MapType(tuplePtrType);
  6161. tuplePtr = mModule->mBfIRBuilder->CreateBitCast(fieldPtr, mappedPtrType);
  6162. }
  6163. for (int tupleFieldIdx = 0; tupleFieldIdx < (int)tupleType->mFieldInstances.size(); tupleFieldIdx++)
  6164. {
  6165. auto tupleFieldInstance = &tupleType->mFieldInstances[tupleFieldIdx];
  6166. auto resolvedFieldType = tupleFieldInstance->GetResolvedType();
  6167. if (tupleFieldIdx >= argValues.mResolvedArgs.size())
  6168. {
  6169. BfAstNode* refNode = targetSrc;
  6170. BfAstNode* prevNode = NULL;
  6171. if (mModule->mParentNodeEntry != NULL)
  6172. {
  6173. if (auto invokeExpr = BfNodeDynCast<BfInvocationExpression>(mModule->mParentNodeEntry->mNode))
  6174. {
  6175. if (invokeExpr->mCloseParen != NULL)
  6176. refNode = invokeExpr->mCloseParen;
  6177. }
  6178. }
  6179. BfError* error = mModule->Fail(StrFormat("Not enough parameters specified, expected %d more.", tupleType->mFieldInstances.size() - (int)argValues.mArguments->size()), refNode);
  6180. if (error != NULL)
  6181. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("See enum declaration"), fieldDef->mFieldDeclaration);
  6182. break;
  6183. }
  6184. BfTypedValue receivingValue;
  6185. BfIRValue tupleFieldPtr;
  6186. if (tuplePtr)
  6187. {
  6188. tupleFieldPtr = mModule->mBfIRBuilder->CreateInBoundsGEP(tuplePtr, 0, tupleFieldInstance->mDataIdx);
  6189. receivingValue = BfTypedValue(tupleFieldPtr, tupleFieldInstance->mResolvedType, true);
  6190. }
  6191. auto argValue = ResolveArgValue(argValues.mResolvedArgs[tupleFieldIdx], resolvedFieldType, &receivingValue);
  6192. // Used receiving value?
  6193. if (argValue.mValue == receivingValue.mValue)
  6194. continue;
  6195. if ((!argValue) || (argValue.IsValuelessType()))
  6196. continue;
  6197. argValue = mModule->AggregateSplat(argValue);
  6198. argValues.mResolvedArgs[tupleFieldIdx].mExpectedType = resolvedFieldType;
  6199. if ((argValues.mResolvedArgs[tupleFieldIdx].mArgFlags & (BfArgFlag_DelegateBindAttempt | BfArgFlag_LambdaBindAttempt | BfArgFlag_UnqualifiedDotAttempt)) != 0)
  6200. {
  6201. auto expr = BfNodeDynCast<BfExpression>(argValues.mResolvedArgs[tupleFieldIdx].mExpression);
  6202. BF_ASSERT(expr != NULL);
  6203. argValue = mModule->CreateValueFromExpression(expr, resolvedFieldType);
  6204. }
  6205. if (argValue)
  6206. {
  6207. // argValue can have a value even if tuplePtr does not have a value. This can happen if we are assigning to a (void) tuple,
  6208. // but we have a value that needs to be attempted to be casted to void
  6209. argValue = mModule->Cast(argValues.mResolvedArgs[tupleFieldIdx].mExpression, argValue, resolvedFieldType);
  6210. if (tupleFieldPtr)
  6211. {
  6212. argValue = mModule->LoadValue(argValue);
  6213. if (argValue)
  6214. mModule->mBfIRBuilder->CreateAlignedStore(argValue.mValue, tupleFieldPtr, resolvedFieldType->mAlign);
  6215. }
  6216. }
  6217. }
  6218. if ((intptr)argValues.mResolvedArgs.size() > tupleType->mFieldInstances.size())
  6219. {
  6220. BfAstNode* errorRef = argValues.mResolvedArgs[tupleType->mFieldInstances.size()].mExpression;
  6221. if (errorRef == NULL)
  6222. errorRef = targetSrc;
  6223. BfError* error = mModule->Fail(StrFormat("Too many arguments, expected %d fewer.", argValues.mResolvedArgs.size() - tupleType->mFieldInstances.size()), errorRef);
  6224. if (error != NULL)
  6225. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("See enum declaration"), fieldDef->mFieldDeclaration);
  6226. }
  6227. //auto fieldPtr = mModule->mBfIRBuilder->CreateInBoundsGEP(enumValue, 0, 2);
  6228. auto dscrType = enumType->GetDiscriminatorType();
  6229. auto dscrField = &enumType->mFieldInstances.back();
  6230. int tagIdx = -fieldInstance->mDataIdx - 1;
  6231. auto dscFieldPtr = mModule->mBfIRBuilder->CreateInBoundsGEP(enumValue, 0, dscrField->mDataIdx);
  6232. mModule->mBfIRBuilder->CreateAlignedStore(mModule->mBfIRBuilder->CreateConst(dscrType->mTypeDef->mTypeCode, tagIdx), dscFieldPtr, 4);
  6233. return result;
  6234. }
  6235. }
  6236. return BfTypedValue();
  6237. }
  6238. bool BfExprEvaluator::CheckGenericCtor(BfGenericParamType* genericParamType, BfResolvedArgs& argValues, BfAstNode* targetSrc)
  6239. {
  6240. auto genericConstraint = mModule->GetGenericParamInstance(genericParamType);
  6241. bool success = true;
  6242. if ((argValues.mArguments != NULL) && (argValues.mArguments->size() != 0))
  6243. {
  6244. mModule->Fail(StrFormat("Only default parameterless constructors can be called on generic argument '%s'", genericConstraint->GetGenericParamDef()->mName.c_str()), targetSrc);
  6245. success = false;
  6246. }
  6247. else if ((genericConstraint->mGenericParamFlags & (BfGenericParamFlag_New | BfGenericParamFlag_Struct)) == 0)
  6248. {
  6249. mModule->Fail(StrFormat("Must add 'where %s : new, struct' constraint to generic parameter to instantiate type", genericConstraint->GetGenericParamDef()->mName.c_str()), targetSrc);
  6250. success = false;
  6251. }
  6252. else if ((genericConstraint->mGenericParamFlags & BfGenericParamFlag_New) == 0)
  6253. {
  6254. mModule->Fail(StrFormat("Must add 'where %s : new' constraint to generic parameter to instantiate type", genericConstraint->GetGenericParamDef()->mName.c_str()), targetSrc);
  6255. success = false;
  6256. }
  6257. else if ((genericConstraint->mGenericParamFlags & BfGenericParamFlag_Struct) == 0)
  6258. {
  6259. mModule->Fail(StrFormat("Must add 'where %s : struct' constraint to generic parameter to instantiate type without allocator", genericConstraint->GetGenericParamDef()->mName.c_str()), targetSrc);
  6260. success = false;
  6261. }
  6262. return success;
  6263. }
  6264. BfTypedValue BfExprEvaluator::MatchMethod(BfAstNode* targetSrc, BfMethodBoundExpression* methodBoundExpr, BfTypedValue target, bool allowImplicitThis, bool bypassVirtual, const StringImpl& methodName,
  6265. BfResolvedArgs& argValues, BfSizedArray<ASTREF(BfTypeReference*)>* methodGenericArguments, BfCheckedKind checkedKind)
  6266. {
  6267. BP_ZONE("MatchMethod");
  6268. if (bypassVirtual)
  6269. {
  6270. // "bypassVirtual" means that we know for sure that the target is EXACTLY the specified target type,
  6271. // not derived from (or implementing) the target type. This cannot apply to interfaces.
  6272. BF_ASSERT(!target.mType->IsInterface());
  6273. }
  6274. auto origTarget = target;
  6275. if (mFunctionBindResult != NULL)
  6276. {
  6277. BF_ASSERT(!mFunctionBindResult->mOrigTarget);
  6278. mFunctionBindResult->mOrigTarget = origTarget;
  6279. }
  6280. if (target)
  6281. {
  6282. // Turn T* into a T, if we can
  6283. if ((target.mType->IsPointer()) && (target.mType->GetUnderlyingType()->IsGenericParam()))
  6284. {
  6285. auto underlyingType = target.mType->GetUnderlyingType();
  6286. auto genericParam = mModule->GetGenericParamInstance((BfGenericParamType*)underlyingType);
  6287. if (((genericParam->mTypeConstraint != NULL) && (genericParam->mTypeConstraint->IsValueType())) ||
  6288. ((genericParam->mGenericParamFlags & (BfGenericParamFlag_Struct)) != 0))
  6289. {
  6290. target.mType = underlyingType;
  6291. }
  6292. }
  6293. if ((!target.mType->IsGenericParam()) && (!target.IsSplat()) && (!target.mType->IsVar()))
  6294. target = MakeCallableTarget(targetSrc, target);
  6295. }
  6296. // static int sCallIdx = 0;
  6297. // if (!mModule->mCompiler->mIsResolveOnly)
  6298. // sCallIdx++;
  6299. // int callIdx = sCallIdx;
  6300. // if (callIdx == 118)
  6301. // {
  6302. // NOP;
  6303. // }
  6304. bool prevAllowVariableDeclarations = true;
  6305. if (mModule->mCurMethodState != NULL)
  6306. {
  6307. // Don't allow variable declarations in arguments for this method call
  6308. prevAllowVariableDeclarations = mModule->mCurMethodState->mCurScope->mAllowVariableDeclarations;
  6309. mModule->mCurMethodState->mCurScope->mAllowVariableDeclarations = false;
  6310. }
  6311. defer
  6312. (
  6313. if (mModule->mCurMethodState != NULL)
  6314. mModule->mCurMethodState->mCurScope->mAllowVariableDeclarations = prevAllowVariableDeclarations;
  6315. );
  6316. // Temporarily disable so we don't capture calls in params
  6317. SetAndRestoreValue<BfFunctionBindResult*> prevBindResult(mFunctionBindResult, NULL);
  6318. sInvocationIdx++;
  6319. bool wantCtor = methodName.IsEmpty();
  6320. BfAutoComplete::MethodMatchInfo* restoreCapturingMethodMatchInfo = NULL;
  6321. auto autoComplete = GetAutoComplete();
  6322. if ((autoComplete != NULL) && (autoComplete->mIsCapturingMethodMatchInfo))
  6323. {
  6324. if ((!targetSrc->IsFromParser(mModule->mCompiler->mResolvePassData->mParser)) ||
  6325. ((autoComplete->mMethodMatchInfo->mInvocationSrcIdx != -1) && (autoComplete->mMethodMatchInfo->mInvocationSrcIdx != targetSrc->GetSrcStart())))
  6326. {
  6327. autoComplete->mIsCapturingMethodMatchInfo = false;
  6328. restoreCapturingMethodMatchInfo = autoComplete->mMethodMatchInfo;
  6329. }
  6330. }
  6331. defer(
  6332. {
  6333. if ((restoreCapturingMethodMatchInfo != NULL) && (autoComplete->mMethodMatchInfo == restoreCapturingMethodMatchInfo))
  6334. autoComplete->mIsCapturingMethodMatchInfo = true;
  6335. });
  6336. /*if ((autoComplete != NULL) && (autoComplete->mIsCapturingMethodMatchInfo) && (autoComplete->mMethodMatchInfo->mInstanceList.size() != 0))
  6337. autoComplete->mIsCapturingMethodMatchInfo = false;*/
  6338. bool isUnboundCall = false;
  6339. if (target.mType != NULL)
  6340. {
  6341. if (target.mType->IsGenericParam())
  6342. {
  6343. auto genericParamTarget = (BfGenericParamType*) target.mType;
  6344. auto genericParamInstance = mModule->GetGenericParamInstance(genericParamTarget);
  6345. isUnboundCall = (genericParamInstance->mGenericParamFlags & BfGenericParamFlag_Var) != 0;
  6346. if (isUnboundCall)
  6347. {
  6348. if (mModule->mCurMethodInstance->mIsUnspecialized)
  6349. {
  6350. auto varType = mModule->GetPrimitiveType(BfTypeCode_Var);
  6351. target.mType = varType;
  6352. }
  6353. }
  6354. }
  6355. else if (target.mType->IsVar())
  6356. isUnboundCall = true;
  6357. }
  6358. /*if (mPrefixedAttributeState != NULL)
  6359. {
  6360. auto customAttr = mPrefixedAttributeState->mCustomAttributes->Get(mModule->mCompiler->mUnboundAttributeTypeDef);
  6361. if (customAttr != NULL)
  6362. {
  6363. if (!mModule->IsInGeneric())
  6364. {
  6365. mModule->Fail("'Unbound' can only be used within generics");
  6366. }
  6367. mPrefixedAttributeState->mUsed = true;
  6368. isUnboundCall = true;
  6369. }
  6370. }*/
  6371. if ((mModule->mAttributeState != NULL) && (mModule->mAttributeState->mCustomAttributes != NULL))
  6372. {
  6373. auto customAttr = mModule->mAttributeState->mCustomAttributes->Get(mModule->mCompiler->mUnboundAttributeTypeDef);
  6374. if (customAttr != NULL)
  6375. {
  6376. if (!mModule->IsInGeneric())
  6377. {
  6378. mModule->Fail("'Unbound' can only be used within generics");
  6379. }
  6380. mModule->mAttributeState->mUsed = true;
  6381. isUnboundCall = true;
  6382. }
  6383. }
  6384. if (isUnboundCall)
  6385. {
  6386. if ((mModule->mCurMethodInstance != NULL) && (mModule->mCurMethodInstance->mIsUnspecialized))
  6387. {
  6388. auto varType = mModule->GetPrimitiveType(BfTypeCode_Var);
  6389. for (int argIdx = 0; argIdx < (int)argValues.mResolvedArgs.size(); argIdx++)
  6390. {
  6391. if ((argValues.mResolvedArgs[argIdx].mArgFlags & BfArgFlag_DeferredEval) != 0)
  6392. {
  6393. mModule->CreateValueFromExpression((*argValues.mArguments)[argIdx], varType);
  6394. }
  6395. }
  6396. return BfTypedValue(mModule->GetDefaultValue(varType), varType);
  6397. }
  6398. }
  6399. SetAndRestoreValue<bool> prevNoBind(mNoBind, mNoBind || isUnboundCall);
  6400. bool wantsExtensionCheck = target;
  6401. auto targetType = target.mType;
  6402. BfTypeDef* curTypeDef = NULL;
  6403. BfTypeInstance* targetTypeInst = NULL;
  6404. bool checkNonStatic = true;
  6405. if (target)
  6406. {
  6407. if (targetType->IsVar())
  6408. return mModule->GetDefaultTypedValue(targetType);
  6409. targetTypeInst = targetType->ToTypeInstance();
  6410. if (targetTypeInst != NULL)
  6411. curTypeDef = targetTypeInst->mTypeDef;
  6412. }
  6413. else if (targetType != NULL) // Static targeted
  6414. {
  6415. if (targetType->IsWrappableType())
  6416. {
  6417. targetTypeInst = mModule->GetWrappedStructType(targetType);
  6418. }
  6419. else if (targetType->IsGenericParam())
  6420. {
  6421. auto genericParamInstance = mModule->GetGenericParamInstance((BfGenericParamType*)targetType);
  6422. if (genericParamInstance->mTypeConstraint != NULL)
  6423. targetTypeInst = genericParamInstance->mTypeConstraint->ToTypeInstance();
  6424. if (genericParamInstance->mGenericParamFlags & BfGenericParamFlag_Var)
  6425. {
  6426. auto varType = mModule->GetPrimitiveType(BfTypeCode_Var);
  6427. return BfTypedValue(mModule->GetDefaultValue(varType), varType);
  6428. }
  6429. }
  6430. else
  6431. targetTypeInst = targetType->ToTypeInstance();
  6432. if (targetTypeInst == NULL)
  6433. {
  6434. //mModule->Fail("No static methods available", targetSrc);
  6435. //return BfTypedValue();
  6436. }
  6437. else
  6438. {
  6439. curTypeDef = targetTypeInst->mTypeDef;
  6440. checkNonStatic = false;
  6441. }
  6442. }
  6443. else // Current scopeData
  6444. {
  6445. if ((mModule->mCurMethodInstance != NULL) && (mModule->mCurMethodInstance->mIsForeignMethodDef) && (mModule->mCurMethodInstance->mMethodInfoEx->mForeignType->IsInterface()))
  6446. {
  6447. targetTypeInst = mModule->mCurMethodInstance->mMethodInfoEx->mForeignType;
  6448. curTypeDef = targetTypeInst->mTypeDef;
  6449. checkNonStatic = true;
  6450. target = mModule->GetThis();
  6451. //target.mType = targetTypeInst;
  6452. }
  6453. else
  6454. {
  6455. curTypeDef = mModule->mCurTypeInstance->mTypeDef;
  6456. targetTypeInst = mModule->mCurTypeInstance;
  6457. if (mModule->mCurMethodState == NULL)
  6458. {
  6459. checkNonStatic = false;
  6460. }
  6461. else
  6462. {
  6463. if (mModule->mCurMethodState->mMixinState != NULL)
  6464. {
  6465. targetTypeInst = mModule->mCurMethodState->mMixinState->mMixinMethodInstance->GetOwner();
  6466. curTypeDef = targetTypeInst->mTypeDef;
  6467. }
  6468. if (mModule->mCurMethodState->mTempKind != BfMethodState::TempKind_None)
  6469. {
  6470. checkNonStatic = mModule->mCurMethodState->mTempKind == BfMethodState::TempKind_NonStatic;
  6471. }
  6472. else
  6473. checkNonStatic = !mModule->mCurMethodInstance->mMethodDef->mIsStatic;
  6474. }
  6475. }
  6476. }
  6477. bool isIndirectMethodCall = false;
  6478. BfType* lookupType = targetType;
  6479. BfTypeInstance* lookupTypeInst = targetTypeInst;
  6480. if (targetType != NULL)
  6481. {
  6482. lookupType = BindGenericType(targetSrc, targetType);
  6483. if (lookupType->IsGenericParam())
  6484. lookupTypeInst = NULL;
  6485. }
  6486. BfMethodDef* methodDef = NULL;
  6487. BfTypeVector checkMethodGenericArguments;
  6488. BfTypeInstance* curTypeInst = targetTypeInst;
  6489. BfMethodMatcher methodMatcher(targetSrc, mModule, methodName, argValues.mResolvedArgs, methodGenericArguments);
  6490. methodMatcher.mOrigTarget = origTarget;
  6491. methodMatcher.mTarget = target;
  6492. methodMatcher.mCheckedKind = checkedKind;
  6493. methodMatcher.mAllowImplicitThis = allowImplicitThis;
  6494. methodMatcher.mAllowStatic = !target.mValue;
  6495. methodMatcher.mAllowNonStatic = !methodMatcher.mAllowStatic;
  6496. methodMatcher.mAutoFlushAmbiguityErrors = !wantsExtensionCheck;
  6497. if (allowImplicitThis)
  6498. {
  6499. if (mModule->mCurMethodState == NULL)
  6500. {
  6501. methodMatcher.mAllowStatic = true;
  6502. methodMatcher.mAllowNonStatic = false;
  6503. }
  6504. else if (mModule->mCurMethodState->mTempKind != BfMethodState::TempKind_None)
  6505. {
  6506. methodMatcher.mAllowNonStatic = mModule->mCurMethodState->mTempKind == BfMethodState::TempKind_NonStatic;
  6507. methodMatcher.mAllowStatic = true;
  6508. }
  6509. else
  6510. {
  6511. if (!mModule->mCurMethodInstance->mMethodDef->mIsStatic)
  6512. methodMatcher.mAllowNonStatic = true;
  6513. methodMatcher.mAllowStatic = true;
  6514. if (mModule->mCurMethodInstance->mMethodDef->mIsLocalMethod)
  6515. {
  6516. auto rootMethodState = mModule->mCurMethodState->GetRootMethodState();
  6517. methodMatcher.mAllowNonStatic = !rootMethodState->mMethodInstance->mMethodDef->mIsStatic;
  6518. }
  6519. }
  6520. }
  6521. if (methodName == BF_METHODNAME_CALCAPPEND)
  6522. methodMatcher.mMethodType = BfMethodType_CtorCalcAppend;
  6523. BF_ASSERT(methodMatcher.mBestMethodDef == NULL);
  6524. BfLocalMethod* matchedLocalMethod = NULL;
  6525. if (target.mType == NULL)
  6526. {
  6527. CheckLocalMethods(targetSrc, curTypeInst, methodName, methodMatcher, BfMethodType_Normal);
  6528. if (methodMatcher.mBestMethodDef == NULL)
  6529. methodMatcher.mBestMethodDef = methodMatcher.mBackupMethodDef;
  6530. if (methodMatcher.mBestMethodDef != NULL)
  6531. {
  6532. auto rootMethodState = mModule->mCurMethodState->GetRootMethodState();
  6533. auto methodDef = methodMatcher.mBestMethodDef;
  6534. if (mModule->mCompiler->mResolvePassData != NULL)
  6535. {
  6536. auto identifierNode = BfNodeDynCast<BfIdentifierNode>(targetSrc);
  6537. mModule->mCompiler->mResolvePassData->HandleLocalReference(identifierNode, curTypeInst->mTypeDef, rootMethodState->mMethodInstance->mMethodDef, ~methodDef->mIdx);
  6538. auto autoComplete = GetAutoComplete();
  6539. if ((autoComplete != NULL) && (autoComplete->IsAutocompleteNode(identifierNode)))
  6540. {
  6541. autoComplete->SetDefinitionLocation(methodDef->GetRefNode(), true);
  6542. if (autoComplete->mDefType == NULL)
  6543. {
  6544. autoComplete->mDefMethod = mModule->mCurMethodState->GetRootMethodState()->mMethodInstance->mMethodDef;
  6545. autoComplete->mDefType = curTypeDef;
  6546. autoComplete->mReplaceLocalId = ~methodDef->mIdx;
  6547. }
  6548. }
  6549. if ((autoComplete != NULL) && (autoComplete->mIsCapturingMethodMatchInfo))
  6550. {
  6551. BfAutoComplete::MethodMatchEntry methodMatchEntry;
  6552. methodMatchEntry.mMethodDef = methodDef;
  6553. methodMatchEntry.mTypeInstance = mModule->mCurTypeInstance;
  6554. methodMatchEntry.mCurMethodInstance = mModule->mCurMethodInstance;
  6555. autoComplete->mMethodMatchInfo->mInstanceList.push_back(methodMatchEntry);
  6556. }
  6557. }
  6558. if ((mModule->mCurMethodState->mClosureState != NULL) && (mModule->mCurMethodState->mClosureState->mCapturing))
  6559. {
  6560. auto methodInstance = mModule->GetRawMethodInstance(methodMatcher.mBestMethodTypeInstance, methodMatcher.mBestMethodDef);
  6561. if (methodInstance->mReturnType == NULL)
  6562. {
  6563. FinishDeferredEvals(argValues.mResolvedArgs);
  6564. // If we are recursive then we won't even have a completed methodInstance yet to look at
  6565. return mModule->GetDefaultTypedValue(mModule->mContext->mBfObjectType);
  6566. }
  6567. }
  6568. }
  6569. }
  6570. if (methodMatcher.mBestMethodDef == NULL)
  6571. {
  6572. if (lookupTypeInst == NULL)
  6573. {
  6574. if ((lookupType != NULL) && (lookupType->IsConcreteInterfaceType()))
  6575. {
  6576. auto concreteInterfaceType = (BfConcreteInterfaceType*)lookupType;
  6577. lookupTypeInst = concreteInterfaceType->mInterface;
  6578. }
  6579. else if (isUnboundCall)
  6580. {
  6581. //auto resolvedType = mModule->ResolveGenericType(lookupType);
  6582. }
  6583. else if (lookupType->IsGenericParam())
  6584. {
  6585. auto genericParamTarget = (BfGenericParamType*)lookupType;
  6586. auto _HandleGenericParamInstance = [&](BfGenericParamInstance* genericParamInstance)
  6587. {
  6588. if (genericParamInstance->mTypeConstraint != NULL)
  6589. lookupTypeInst = genericParamInstance->mTypeConstraint->ToTypeInstance();
  6590. else
  6591. lookupTypeInst = mModule->mContext->mBfObjectType;
  6592. for (BfType* ifaceInst : genericParamInstance->mInterfaceConstraints)
  6593. {
  6594. if (ifaceInst->IsUnspecializedType())
  6595. ifaceInst = mModule->ResolveType(ifaceInst);
  6596. BfTypeInstance* typeInst = ifaceInst->ToTypeInstance();
  6597. BF_ASSERT(typeInst != NULL);
  6598. if (methodMatcher.CheckType(typeInst, target, false))
  6599. methodMatcher.mSelfType = lookupType;
  6600. }
  6601. };
  6602. auto genericParamInstance = mModule->GetGenericParamInstance(genericParamTarget);
  6603. _HandleGenericParamInstance(genericParamInstance);
  6604. // Check method generic constraints
  6605. if ((mModule->mCurMethodInstance != NULL) && (mModule->mCurMethodInstance->mIsUnspecialized) && (mModule->mCurMethodInstance->mMethodInfoEx != NULL))
  6606. {
  6607. for (int genericParamIdx = (int)mModule->mCurMethodInstance->mMethodInfoEx->mMethodGenericArguments.size();
  6608. genericParamIdx < mModule->mCurMethodInstance->mMethodInfoEx->mGenericParams.size(); genericParamIdx++)
  6609. {
  6610. auto genericParam = mModule->mCurMethodInstance->mMethodInfoEx->mGenericParams[genericParamIdx];
  6611. if (genericParam->mExternType == lookupType)
  6612. _HandleGenericParamInstance(genericParam);
  6613. }
  6614. }
  6615. }
  6616. }
  6617. if ((lookupTypeInst != NULL) && (!wantCtor))
  6618. {
  6619. methodMatcher.mBypassVirtual = bypassVirtual;
  6620. methodMatcher.CheckType(lookupTypeInst, target, false);
  6621. }
  6622. if ((lookupType != NULL) && (lookupType->IsGenericParam()))
  6623. {
  6624. //lookupType = mModule->ResolveGenericType(lookupType);
  6625. if (!lookupType->IsGenericParam())
  6626. {
  6627. target = MakeCallableTarget(targetSrc, target);
  6628. if (target)
  6629. {
  6630. lookupTypeInst = lookupType->ToTypeInstance();
  6631. }
  6632. }
  6633. }
  6634. }
  6635. bool isFailurePass = false;
  6636. if (methodMatcher.mBestMethodDef == NULL)
  6637. {
  6638. isFailurePass = true;
  6639. if (lookupTypeInst != NULL)
  6640. methodMatcher.CheckType(lookupTypeInst, target, true);
  6641. }
  6642. BfTypedValue staticResult;
  6643. methodMatcher.TryDevirtualizeCall(target, &origTarget, &staticResult);
  6644. if (staticResult)
  6645. return staticResult;
  6646. bypassVirtual |= methodMatcher.mBypassVirtual;
  6647. if (methodMatcher.mBestMethodDef != NULL)
  6648. {
  6649. curTypeInst = methodMatcher.mBestMethodTypeInstance;
  6650. methodDef = methodMatcher.mBestMethodDef;
  6651. }
  6652. if ((methodDef) && (!methodDef->mIsStatic) && (!target) && (allowImplicitThis))
  6653. {
  6654. target = mModule->GetThis();
  6655. }
  6656. // If we call "GetType" on a value type, statically determine the type rather than boxing and then dispatching
  6657. if ((methodDef) && (target) && (curTypeInst == mModule->mContext->mBfObjectType) &&
  6658. (methodDef->mName == "GetType") && (target.mType->IsValueType()) && (argValues.mArguments->IsEmpty()))
  6659. {
  6660. BfType* targetType = target.mType;
  6661. if (origTarget)
  6662. targetType = origTarget.mType;
  6663. auto typeType = mModule->ResolveTypeDef(mModule->mCompiler->mTypeTypeDef);
  6664. mModule->AddDependency(targetType, mModule->mCurTypeInstance, BfDependencyMap::DependencyFlag_ExprTypeReference);
  6665. return BfTypedValue(mModule->CreateTypeDataRef(targetType), typeType);
  6666. }
  6667. bool skipThis = false;
  6668. // Fail, check for delegate field invocation
  6669. if ((methodDef == NULL) && ((methodGenericArguments == NULL) || (methodGenericArguments->size() == 0)))
  6670. {
  6671. // Check for payload enum initialization first
  6672. BfTypedValue enumResult;
  6673. BfTypeInstance* enumType = NULL;
  6674. if ((!target) && (mModule->mCurTypeInstance->IsPayloadEnum()))
  6675. {
  6676. enumType = mModule->mCurTypeInstance;
  6677. //enumResult = CheckEnumCreation(targetSrc, mModule->mCurTypeInstance, methodName, argValues);
  6678. }
  6679. else if ((!target) && (target.HasType()) && (targetType->IsPayloadEnum()))
  6680. {
  6681. enumType = targetType->ToTypeInstance();
  6682. //enumResult = CheckEnumCreation(targetSrc, enumType, methodName, argValues);
  6683. }
  6684. if (enumType != NULL)
  6685. {
  6686. enumResult = CheckEnumCreation(targetSrc, enumType, methodName, argValues);
  6687. }
  6688. if (enumResult)
  6689. {
  6690. if ((mModule->mCompiler->mResolvePassData != NULL) &&
  6691. (targetSrc->IsFromParser(mModule->mCompiler->mResolvePassData->mParser)) &&
  6692. (mModule->mCompiler->mResolvePassData->mSourceClassifier != NULL))
  6693. {
  6694. mModule->mCompiler->mResolvePassData->mSourceClassifier->SetElementType(targetSrc, BfSourceElementType_Normal);
  6695. }
  6696. return enumResult;
  6697. }
  6698. BfTypedValue fieldVal;
  6699. if (allowImplicitThis)
  6700. {
  6701. auto identifierNode = BfNodeDynCast<BfIdentifierNode>(targetSrc);
  6702. if (identifierNode != NULL)
  6703. fieldVal = LookupIdentifier(identifierNode);
  6704. }
  6705. else
  6706. {
  6707. SetAndRestoreValue<BfEvalExprFlags> prevFlags(mBfEvalExprFlags, (BfEvalExprFlags)(mBfEvalExprFlags & ~BfEvalExprFlags_AllowEnumId));
  6708. fieldVal = LookupField(targetSrc, target, methodName);
  6709. }
  6710. if (mPropDef != NULL)
  6711. fieldVal = GetResult();
  6712. if (fieldVal)
  6713. {
  6714. if (fieldVal.mType->IsGenericParam())
  6715. {
  6716. bool delegateFailed = true;
  6717. auto genericParamInstance = mModule->GetGenericParamInstance((BfGenericParamType*)fieldVal.mType);
  6718. BfTypeInstance* typeInstConstraint = NULL;
  6719. if (genericParamInstance->mTypeConstraint != NULL)
  6720. typeInstConstraint = genericParamInstance->mTypeConstraint->ToTypeInstance();
  6721. if ((typeInstConstraint != NULL) &&
  6722. ((typeInstConstraint->mTypeDef == mModule->mCompiler->mDelegateTypeDef) || (typeInstConstraint->mTypeDef == mModule->mCompiler->mFunctionTypeDef)))
  6723. {
  6724. MarkResultUsed();
  6725. // if (argValues.mResolvedArgs.size() > 0)
  6726. // {
  6727. // if ((argValues.mResolvedArgs[0].mArgFlags & BfArgFlag_FromParamComposite) != 0)
  6728. // delegateFailed = false;
  6729. // }
  6730. // else
  6731. if (argValues.mArguments->size() == 1)
  6732. {
  6733. BfExprEvaluator exprEvaluator(mModule);
  6734. exprEvaluator.mBfEvalExprFlags = BfEvalExprFlags_AllowParamsExpr;
  6735. exprEvaluator.Evaluate((*argValues.mArguments)[0]);
  6736. if ((mModule->mCurMethodState != NULL) && (exprEvaluator.mResultLocalVar != NULL) && (exprEvaluator.mResultLocalVarRefNode != NULL))
  6737. {
  6738. /*if (exprEvaluator.mResult.mKind != BfTypedValueKind_Params)
  6739. mModule->Warn(0, "'params' token expected", (*argValues.mArguments)[0]);*/
  6740. auto localVar = exprEvaluator.mResultLocalVar;
  6741. if ((localVar->mCompositeCount >= 0) && (localVar->mResolvedType == fieldVal.mType))
  6742. {
  6743. delegateFailed = false;
  6744. if (mModule->mCurMethodInstance->mIsUnspecialized)
  6745. {
  6746. auto retTypeType = mModule->CreateModifiedTypeType(fieldVal.mType, BfToken_RetType);
  6747. return mModule->GetFakeTypedValue(retTypeType);
  6748. }
  6749. }
  6750. }
  6751. }
  6752. if (delegateFailed)
  6753. {
  6754. mModule->Fail(StrFormat("Generic delegates can only be invoked with 'params %s' composite parameters", mModule->TypeToString(fieldVal.mType).c_str()), targetSrc);
  6755. return BfTypedValue();
  6756. }
  6757. }
  6758. }
  6759. if (fieldVal.mType->IsTypeInstance())
  6760. {
  6761. prevBindResult.Restore();
  6762. auto fieldTypeInst = fieldVal.mType->ToTypeInstance();
  6763. MarkResultUsed();
  6764. return MatchMethod(targetSrc, NULL, fieldVal, false, false, "Invoke", argValues, methodGenericArguments, checkedKind);
  6765. }
  6766. if (fieldVal.mType->IsVar())
  6767. return BfTypedValue(mModule->GetDefaultValue(fieldVal.mType), fieldVal.mType);
  6768. if (fieldVal.mType->IsGenericParam())
  6769. {
  6770. auto genericParam = mModule->GetGenericParamInstance((BfGenericParamType*)fieldVal.mType);
  6771. if ((genericParam->mTypeConstraint != NULL) &&
  6772. ((genericParam->mTypeConstraint->IsDelegate()) || (genericParam->mTypeConstraint->IsFunction())))
  6773. {
  6774. BfMethodInstance* invokeMethodInstance = mModule->GetRawMethodInstanceAtIdx(genericParam->mTypeConstraint->ToTypeInstance(), 0, "Invoke");
  6775. methodDef = invokeMethodInstance->mMethodDef;
  6776. methodMatcher.mBestMethodInstance = invokeMethodInstance;
  6777. methodMatcher.mBestMethodTypeInstance = invokeMethodInstance->GetOwner();
  6778. methodMatcher.mBestMethodDef = invokeMethodInstance->mMethodDef;
  6779. target = mModule->GetDefaultTypedValue(methodMatcher.mBestMethodTypeInstance);
  6780. isFailurePass = false;
  6781. isIndirectMethodCall = true;
  6782. }
  6783. }
  6784. else if (fieldVal.mType->IsMethodRef())
  6785. {
  6786. auto functionBindResults = prevBindResult.mPrevVal;
  6787. if (functionBindResults != NULL)
  6788. {
  6789. functionBindResults->mOrigTarget = fieldVal;
  6790. }
  6791. origTarget = fieldVal;
  6792. auto methodRefType = (BfMethodRefType*)fieldVal.mType;
  6793. BfMethodInstance* methodInstance = methodRefType->mMethodRef;
  6794. methodDef = methodInstance->mMethodDef;
  6795. if (methodDef->mIsLocalMethod)
  6796. {
  6797. methodMatcher.mBestMethodInstance = mModule->ReferenceExternalMethodInstance(methodInstance);
  6798. }
  6799. else
  6800. {
  6801. BfTypeVector methodGenericArguments;
  6802. if (methodInstance->mMethodInfoEx != NULL)
  6803. methodGenericArguments = methodInstance->mMethodInfoEx->mMethodGenericArguments;
  6804. methodMatcher.mBestMethodInstance = mModule->GetMethodInstance(methodInstance->GetOwner(), methodInstance->mMethodDef, methodGenericArguments);
  6805. }
  6806. methodMatcher.mBestMethodTypeInstance = methodInstance->GetOwner();
  6807. if (methodInstance->HasThis())
  6808. {
  6809. bool failed = false;
  6810. target = DoImplicitArgCapture(targetSrc, methodInstance, -1, failed, BfImplicitParamKind_General, origTarget);
  6811. }
  6812. else if (!methodDef->mIsStatic)
  6813. {
  6814. auto thisType = methodInstance->GetParamType(-1);
  6815. BF_ASSERT(thisType->IsValuelessType());
  6816. target = BfTypedValue(mModule->mBfIRBuilder->GetFakeVal(), methodMatcher.mBestMethodTypeInstance);
  6817. }
  6818. else
  6819. target = BfTypedValue(methodMatcher.mBestMethodTypeInstance);
  6820. methodMatcher.mBypassVirtual = true;
  6821. bypassVirtual = true;
  6822. isFailurePass = false;
  6823. isIndirectMethodCall = true;
  6824. }
  6825. if (methodDef == NULL)
  6826. {
  6827. mModule->Fail(StrFormat("Cannot perform invocation on type '%s'", mModule->TypeToString(fieldVal.mType).c_str()), targetSrc);
  6828. return BfTypedValue();
  6829. }
  6830. }
  6831. }
  6832. if ((!methodDef) && (!target.mValue))
  6833. {
  6834. // Check to see if we're constructing a struct via a call like: "Struct structVal = Struct()"
  6835. int wantNumGenericArgs = 0;
  6836. if ((methodGenericArguments != NULL) && (methodGenericArguments->size() > 0))
  6837. wantNumGenericArgs = (int)methodGenericArguments->size();
  6838. BfTypeInstance* resolvedTypeInstance = NULL;
  6839. if (wantCtor)
  6840. {
  6841. resolvedTypeInstance = targetTypeInst;
  6842. }
  6843. else if (targetType != NULL)
  6844. {
  6845. if (auto invocationExpr = BfNodeDynCast<BfInvocationExpression>(methodBoundExpr))
  6846. {
  6847. auto resolvedType = mModule->ResolveTypeRef(invocationExpr->mTarget, methodGenericArguments);
  6848. if (resolvedType != NULL)
  6849. resolvedTypeInstance = resolvedType->ToTypeInstance();
  6850. }
  6851. }
  6852. else
  6853. {
  6854. BfIdentifierNode* identifierNode = BfNodeDynCast<BfIdentifierNode>(targetSrc);
  6855. if (identifierNode != NULL)
  6856. {
  6857. SetAndRestoreValue<bool> prevIgnoreErrors(mModule->mIgnoreErrors, true);
  6858. BfType* refType;
  6859. if (methodGenericArguments != NULL)
  6860. {
  6861. refType = mModule->ResolveTypeRef(identifierNode, methodGenericArguments);
  6862. }
  6863. else
  6864. refType = mModule->ResolveTypeRef(identifierNode, NULL);
  6865. prevIgnoreErrors.Restore();
  6866. if ((refType != NULL) && (refType->IsPrimitiveType()))
  6867. {
  6868. FinishDeferredEvals(argValues.mResolvedArgs);
  6869. if (argValues.mResolvedArgs.size() != 1)
  6870. {
  6871. mModule->Fail("Cast requires one parameter", targetSrc);
  6872. return BfTypedValue();
  6873. }
  6874. // This is just a primitive cast
  6875. auto& resolvedArg = argValues.mResolvedArgs[0];
  6876. BfTypedValue castedValue;
  6877. BfTypedValue castTarget = resolvedArg.mTypedValue;
  6878. if (resolvedArg.mTypedValue)
  6879. {
  6880. castTarget = mModule->LoadValue(castTarget);
  6881. castedValue = mModule->Cast(targetSrc, castTarget, refType, BfCastFlags_Explicit);
  6882. }
  6883. if (!castedValue)
  6884. castedValue = mModule->GetDefaultTypedValue(refType);
  6885. return castedValue;
  6886. }
  6887. if (refType != NULL)
  6888. {
  6889. resolvedTypeInstance = refType->ToTypeInstance();
  6890. if (refType->IsGenericParam())
  6891. {
  6892. CheckGenericCtor((BfGenericParamType*)refType, argValues, targetSrc);
  6893. return mModule->GetDefaultTypedValue(refType);
  6894. }
  6895. }
  6896. }
  6897. }
  6898. if (resolvedTypeInstance != NULL)
  6899. {
  6900. if ((!resolvedTypeInstance->IsStruct()) && (!resolvedTypeInstance->IsTypedPrimitive()))
  6901. {
  6902. mModule->Fail("Objects must be allocated through 'new' or 'scope'", targetSrc);
  6903. return BfTypedValue();
  6904. }
  6905. if (auto identifier = BfNodeDynCastExact<BfIdentifierNode>(targetSrc))
  6906. mModule->SetElementType(identifier, BfSourceElementType_Type);
  6907. if (mModule->mCompiler->mResolvePassData != NULL)
  6908. mModule->mCompiler->mResolvePassData->HandleTypeReference(targetSrc, resolvedTypeInstance->mTypeDef);
  6909. BfTypedValue structInst;
  6910. mModule->PopulateType(resolvedTypeInstance);
  6911. if (!resolvedTypeInstance->IsValuelessType())
  6912. {
  6913. if ((mReceivingValue != NULL) && (mReceivingValue->mType == resolvedTypeInstance) && (mReceivingValue->IsAddr()))
  6914. {
  6915. structInst = *mReceivingValue;
  6916. mReceivingValue = NULL;
  6917. }
  6918. else
  6919. {
  6920. auto allocaInst = mModule->CreateAlloca(resolvedTypeInstance);
  6921. structInst = BfTypedValue(allocaInst, resolvedTypeInstance, true);
  6922. }
  6923. mResultIsTempComposite = true;
  6924. }
  6925. else
  6926. {
  6927. structInst = BfTypedValue(mModule->mBfIRBuilder->GetFakeVal(), resolvedTypeInstance, true);
  6928. }
  6929. mResultLocalVar = NULL;
  6930. mResultFieldInstance = NULL;
  6931. mResultLocalVarRefNode = NULL;
  6932. MatchConstructor(targetSrc, methodBoundExpr, structInst, resolvedTypeInstance, argValues, false, false);
  6933. mModule->ValidateAllocation(resolvedTypeInstance, targetSrc);
  6934. mModule->AddDependency(resolvedTypeInstance, mModule->mCurTypeInstance, BfDependencyMap::DependencyFlag_LocalUsage);
  6935. if (mUsedAsStatement)
  6936. {
  6937. mModule->Warn(0, "Struct constructor being used as a statement", targetSrc);
  6938. }
  6939. return structInst;
  6940. }
  6941. }
  6942. // For for extensions in current type
  6943. if (wantsExtensionCheck)
  6944. {
  6945. auto checkTypeInst = mModule->mCurTypeInstance;
  6946. methodMatcher.mMethodType = BfMethodType_Extension;
  6947. if (methodMatcher.CheckType(checkTypeInst, BfTypedValue(), false, true))
  6948. {
  6949. isFailurePass = false;
  6950. curTypeInst = methodMatcher.mBestMethodTypeInstance;
  6951. methodDef = methodMatcher.mBestMethodDef;
  6952. }
  6953. }
  6954. // Look in globals. Always check for extension methods.
  6955. if ((methodDef == NULL) || (wantsExtensionCheck))
  6956. {
  6957. if (mModule->mContext->mCurTypeState != NULL)
  6958. {
  6959. BfGlobalLookup globalLookup;
  6960. globalLookup.mKind = BfGlobalLookup::Kind_Method;
  6961. globalLookup.mName = methodName;
  6962. mModule->PopulateGlobalContainersList(globalLookup);
  6963. for (auto& globalContainer : mModule->mContext->mCurTypeState->mGlobalContainers)
  6964. {
  6965. if (globalContainer.mTypeInst == NULL)
  6966. continue;
  6967. methodMatcher.mMethodType = wantsExtensionCheck ? BfMethodType_Extension : BfMethodType_Normal;
  6968. if (methodMatcher.CheckType(globalContainer.mTypeInst, BfTypedValue(), false))
  6969. {
  6970. isFailurePass = false;
  6971. curTypeInst = methodMatcher.mBestMethodTypeInstance;
  6972. methodDef = methodMatcher.mBestMethodDef;
  6973. }
  6974. }
  6975. }
  6976. }
  6977. // Look in static search. Always check for extension methods.
  6978. if ((methodDef == NULL) || (wantsExtensionCheck))
  6979. {
  6980. BfStaticSearch* staticSearch = mModule->GetStaticSearch();
  6981. if (staticSearch != NULL)
  6982. {
  6983. for (auto typeInst : staticSearch->mStaticTypes)
  6984. {
  6985. methodMatcher.mMethodType = wantsExtensionCheck ? BfMethodType_Extension : BfMethodType_Normal;
  6986. if (methodMatcher.CheckType(typeInst, BfTypedValue(), false))
  6987. {
  6988. isFailurePass = false;
  6989. curTypeInst = methodMatcher.mBestMethodTypeInstance;
  6990. methodDef = methodMatcher.mBestMethodDef;
  6991. }
  6992. }
  6993. }
  6994. }
  6995. // This will flush out any new ambiguity errors from extension methods
  6996. methodMatcher.FlushAmbiguityError();
  6997. if (methodDef == NULL)
  6998. {
  6999. FinishDeferredEvals(argValues.mResolvedArgs);
  7000. auto compiler = mModule->mCompiler;
  7001. if ((compiler->IsAutocomplete()) && (compiler->mResolvePassData->mAutoComplete->CheckFixit(targetSrc)))
  7002. {
  7003. mModule->CheckTypeRefFixit(targetSrc);
  7004. bool wantStatic = !target.mValue;
  7005. if ((targetType == NULL) && (allowImplicitThis))
  7006. {
  7007. targetType = mModule->mCurTypeInstance;
  7008. if (mModule->mCurMethodInstance != NULL)
  7009. wantStatic = mModule->mCurMethodInstance->mMethodDef->mIsStatic;
  7010. }
  7011. if (targetType != NULL)
  7012. {
  7013. auto typeInst = targetType->ToTypeInstance();
  7014. if ((targetType != NULL) && (!methodName.IsEmpty()))
  7015. {
  7016. BfTypeVector paramTypes;
  7017. for (int argIdx = 0; argIdx < (int)argValues.mResolvedArgs.size(); argIdx++)
  7018. {
  7019. auto& resolvedArg = argValues.mResolvedArgs[argIdx];
  7020. paramTypes.Add(resolvedArg.mTypedValue.mType);
  7021. }
  7022. autoComplete->FixitAddMethod(typeInst, methodName, mExpectingType, paramTypes, wantStatic);
  7023. }
  7024. }
  7025. }
  7026. if (methodName.IsEmpty())
  7027. {
  7028. // Would have caused a parsing error
  7029. }
  7030. else if (target.mType != NULL)
  7031. mModule->Fail(StrFormat("Method '%s' does not exist in type '%s'", methodName.c_str(), mModule->TypeToString(target.mType).c_str()), targetSrc);
  7032. else
  7033. mModule->Fail(StrFormat("Method '%s' does not exist", methodName.c_str()), targetSrc);
  7034. return BfTypedValue();
  7035. }
  7036. if ((prevBindResult.mPrevVal != NULL) && (methodMatcher.mMethodCheckCount > 1))
  7037. prevBindResult.mPrevVal->mCheckedMultipleMethods = true;
  7038. BfModuleMethodInstance moduleMethodInstance = GetSelectedMethod(targetSrc, curTypeInst, methodDef, methodMatcher);
  7039. if ((mModule->mCurMethodInstance != NULL) && (mModule->mCurMethodInstance->mIsUnspecialized))
  7040. {
  7041. if (methodMatcher.mHasVarArguments)
  7042. {
  7043. BfType* retType = mModule->GetPrimitiveType(BfTypeCode_Var);
  7044. if ((!methodMatcher.mHadVarConflictingReturnType) && (methodMatcher.mBestRawMethodInstance != NULL) && (!methodMatcher.mBestRawMethodInstance->mReturnType->IsUnspecializedTypeVariation()))
  7045. {
  7046. if ((!methodMatcher.mBestRawMethodInstance->mReturnType->IsGenericParam()) ||
  7047. (((BfGenericParamType*)methodMatcher.mBestRawMethodInstance->mReturnType)->mGenericParamKind != BfGenericParamKind_Method))
  7048. retType = methodMatcher.mBestRawMethodInstance->mReturnType;
  7049. }
  7050. return mModule->GetDefaultTypedValue(retType, true, BfDefaultValueKind_Addr);
  7051. }
  7052. }
  7053. if ((bypassVirtual) && (!target.mValue) && (target.mType->IsInterface()))
  7054. {
  7055. target = mModule->GetThis();
  7056. }
  7057. if (!moduleMethodInstance)
  7058. {
  7059. FinishDeferredEvals(argValues.mResolvedArgs);
  7060. return BfTypedValue();
  7061. }
  7062. bool isSkipCall = moduleMethodInstance.mMethodInstance->IsSkipCall(bypassVirtual);
  7063. if ((moduleMethodInstance.mMethodInstance->IsOrInUnspecializedVariation()) && (!mModule->mBfIRBuilder->mIgnoreWrites))
  7064. {
  7065. // Invalid methods such as types with a HasVar tuple generic arg will be marked as mIsUnspecializedVariation and shouldn't actually be called
  7066. FinishDeferredEvals(argValues.mResolvedArgs);
  7067. return mModule->GetDefaultTypedValue(moduleMethodInstance.mMethodInstance->mReturnType, true, BfDefaultValueKind_Addr);
  7068. }
  7069. if (methodDef->IsEmptyPartial())
  7070. {
  7071. // Ignore call
  7072. return mModule->GetDefaultTypedValue(moduleMethodInstance.mMethodInstance->mReturnType, true, BfDefaultValueKind_Addr);
  7073. }
  7074. if ((moduleMethodInstance.mMethodInstance->mMethodDef->mIsStatic) && (moduleMethodInstance.mMethodInstance->GetOwner()->IsInterface()))
  7075. {
  7076. bool isConstrained = false;
  7077. if (target.mType != NULL)
  7078. isConstrained = target.mType->IsGenericParam();
  7079. if ((target.mType == NULL) && ((mModule->mCurMethodInstance->mIsForeignMethodDef) || (mModule->mCurTypeInstance->IsInterface())))
  7080. isConstrained = true;
  7081. // If mIgnoreWrites is off then we skip devirtualization, so allow this
  7082. if ((target.mType != NULL) && (!target.mType->IsInterface()) && (mModule->mBfIRBuilder->mIgnoreWrites))
  7083. isConstrained = true;
  7084. if (!isConstrained)
  7085. {
  7086. if (mModule->mCurTypeInstance->IsInterface())
  7087. {
  7088. if (methodDef->mBody == NULL)
  7089. mModule->Fail(StrFormat("Interface method '%s' must provide a body to be explicitly invoked", mModule->MethodToString(moduleMethodInstance.mMethodInstance).c_str()), targetSrc);
  7090. }
  7091. else
  7092. 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);
  7093. FinishDeferredEvals(argValues.mResolvedArgs);
  7094. return mModule->GetDefaultTypedValue(moduleMethodInstance.mMethodInstance->mReturnType, true, BfDefaultValueKind_Addr);
  7095. }
  7096. }
  7097. // 'base' could really mean 'this' if we're in an extension
  7098. if ((target.IsBase()) && (targetTypeInst == mModule->mCurTypeInstance))
  7099. target.ToThis();
  7100. else
  7101. MakeBaseConcrete(target);
  7102. BfType* callTargetType = curTypeInst;
  7103. if (methodDef->mMethodType == BfMethodType_Extension)
  7104. {
  7105. callTargetType = moduleMethodInstance.mMethodInstance->GetParamType(0);
  7106. if ((callTargetType->IsRef()) && (target.IsAddr()) && (!target.IsReadOnly()) && (target.mType->IsValueType()))
  7107. {
  7108. target = BfTypedValue(target.mValue, mModule->CreateRefType(target.mType));
  7109. }
  7110. }
  7111. BfTypedValue callTarget;
  7112. if (isSkipCall)
  7113. {
  7114. // Just a fake value so we can continue on without generating any code (boxing, conversion, etc)
  7115. if (target)
  7116. callTarget = BfTypedValue(mModule->mBfIRBuilder->GetFakeVal(), targetTypeInst);
  7117. }
  7118. else if (targetTypeInst == callTargetType)
  7119. {
  7120. if ((target) && (methodDef->HasNoThisSplat()))
  7121. {
  7122. callTarget = mModule->MakeAddressable(target);
  7123. }
  7124. else
  7125. callTarget = target;
  7126. if ((callTarget) && (moduleMethodInstance.mMethodInstance->GetOwner()->IsInterface()))
  7127. {
  7128. auto wantThis = moduleMethodInstance.mMethodInstance->GetParamType(-1);
  7129. if ((callTarget.mType != wantThis) && (wantThis->IsInterface()))
  7130. callTarget = mModule->Cast(targetSrc, callTarget, wantThis, BfCastFlags_Explicit);
  7131. }
  7132. }
  7133. else if (target)
  7134. {
  7135. if (methodMatcher.mFakeConcreteTarget)
  7136. {
  7137. BF_ASSERT(callTargetType->IsInterface());
  7138. callTarget = mModule->GetDefaultTypedValue(mModule->CreateConcreteInterfaceType(callTargetType->ToTypeInstance()));
  7139. }
  7140. else if (((target.mType->IsGenericParam()) || (target.mType->IsConcreteInterfaceType())) && (callTargetType->IsInterface()))
  7141. {
  7142. // Leave as generic
  7143. callTarget = target;
  7144. }
  7145. else
  7146. {
  7147. bool handled = false;
  7148. if ((target.mType->IsTypedPrimitive()) && (callTargetType->IsTypedPrimitive()))
  7149. {
  7150. handled = true;
  7151. callTarget = target;
  7152. }
  7153. else if ((target.mType->IsStructOrStructPtr()) || (target.mType->IsTypedPrimitive()))
  7154. {
  7155. //BF_ASSERT(target.IsAddr());
  7156. if (callTargetType->IsObjectOrInterface())
  7157. {
  7158. // Box it
  7159. callTarget = mModule->Cast(targetSrc, target, callTargetType, BfCastFlags_Explicit);
  7160. handled = true;
  7161. }
  7162. else
  7163. {
  7164. //BF_ASSERT(target.IsAddr() || target.IsSplat() || target.mType->IsPointer());
  7165. }
  7166. }
  7167. else
  7168. target = mModule->LoadValue(target);
  7169. if (!handled)
  7170. {
  7171. // Could we have just unconditionally done this?
  7172. callTarget = mModule->Cast(targetSrc, target, callTargetType, BfCastFlags_Explicit);
  7173. }
  7174. }
  7175. }
  7176. if (isFailurePass)
  7177. {
  7178. BfError* error;
  7179. if (methodMatcher.mMatchFailKind == BfMethodMatcher::MatchFailKind_CheckedMismatch)
  7180. 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);
  7181. else
  7182. error = mModule->Fail(StrFormat("'%s' is inaccessible due to its protection level", mModule->MethodToString(moduleMethodInstance.mMethodInstance).c_str()), targetSrc);
  7183. if (error != NULL)
  7184. {
  7185. if ((error != NULL) && (moduleMethodInstance.mMethodInstance->mMethodDef->mMethodDeclaration != NULL))
  7186. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("See method declaration"), moduleMethodInstance.mMethodInstance->mMethodDef->GetRefNode());
  7187. }
  7188. }
  7189. if ((mModule->mCompiler->mResolvePassData != NULL) && (methodDef != NULL))
  7190. {
  7191. auto identifierNode = BfNodeDynCast<BfIdentifierNode>(targetSrc);
  7192. while (auto qualifiedNameNode = BfNodeDynCast<BfQualifiedNameNode>(identifierNode))
  7193. identifierNode = qualifiedNameNode->mRight;
  7194. if ((identifierNode != NULL) && (methodDef->mIdx >= 0) && (!isIndirectMethodCall))
  7195. {
  7196. mModule->mCompiler->mResolvePassData->HandleMethodReference(identifierNode, moduleMethodInstance.mMethodInstance->GetOwner()->mTypeDef, methodDef);
  7197. auto autoComplete = GetAutoComplete();
  7198. if ((autoComplete != NULL) && (autoComplete->IsAutocompleteNode(identifierNode)))
  7199. {
  7200. autoComplete->SetDefinitionLocation(methodDef->GetRefNode(), true);
  7201. int virtualIdx = moduleMethodInstance.mMethodInstance->mVirtualTableIdx;
  7202. if ((autoComplete->mResolveType == BfResolveType_GoToDefinition) &&
  7203. (virtualIdx != -1) && (targetTypeInst != NULL) && (!targetTypeInst->IsStruct()) && (!targetTypeInst->IsTypedPrimitive()) && (!targetTypeInst->IsInterface()) &&
  7204. // 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
  7205. (targetTypeInst->mVirtualMethodTable.size() != 0))
  7206. {
  7207. auto methodEntry = targetTypeInst->mVirtualMethodTable[virtualIdx];
  7208. if (methodEntry.mImplementingMethod.mMethodNum != -1)
  7209. {
  7210. BfMethodInstance* callingMethodInstance = methodEntry.mImplementingMethod;
  7211. if (callingMethodInstance != NULL)
  7212. {
  7213. auto callingMethodDef = callingMethodInstance->mMethodDef;
  7214. auto callingMethodDeclaration = callingMethodDef->GetMethodDeclaration();
  7215. if ((callingMethodDeclaration != NULL) && (callingMethodDeclaration->mNameNode != NULL))
  7216. autoComplete->SetDefinitionLocation(callingMethodDeclaration->mNameNode, true);
  7217. }
  7218. }
  7219. }
  7220. if (autoComplete->mDefType == NULL)
  7221. {
  7222. autoComplete->mDefMethod = methodDef;
  7223. autoComplete->mDefType = moduleMethodInstance.mMethodInstance->GetOwner()->mTypeDef;
  7224. }
  7225. if (autoComplete->mResolveType == BfResolveType_GetResultString)
  7226. {
  7227. autoComplete->mResultString = ":";
  7228. autoComplete->mResultString += mModule->MethodToString(moduleMethodInstance.mMethodInstance);
  7229. auto methodDecl = moduleMethodInstance.mMethodInstance->mMethodDef->GetMethodDeclaration();
  7230. if ((methodDecl != NULL) && (methodDecl->mDocumentation != NULL))
  7231. {
  7232. autoComplete->mResultString += "\x03";
  7233. methodDecl->mDocumentation->GetDocString(autoComplete->mResultString);
  7234. }
  7235. }
  7236. }
  7237. }
  7238. }
  7239. // This was causing forward-backward-forward steps when we just used 'targetSrc'. Using closeParen is undesirable because most of the time
  7240. // we DO just want it to just go to the targetSrc... do we even need this?
  7241. /*if (auto invokeExpr = BfNodeDynCast<BfInvocationExpression>(targetSrc->mParent))
  7242. {
  7243. // We set the srcPos to the close paren right before the call so we keep a forward progression of src positions in the case
  7244. // where some of the params are method calls and such
  7245. if (invokeExpr->mCloseParen != NULL)
  7246. mModule->UpdateExprSrcPos(invokeExpr->mCloseParen);
  7247. else
  7248. mModule->UpdateExprSrcPos(targetSrc);
  7249. }
  7250. else
  7251. mModule->UpdateExprSrcPos(targetSrc);*/
  7252. if (!mModule->mBfIRBuilder->mIgnoreWrites)
  7253. {
  7254. //BF_ASSERT(!callTarget.mValue.IsFake());
  7255. }
  7256. prevBindResult.Restore();
  7257. // Check mut
  7258. if ((callTarget.mType != NULL) &&
  7259. (callTarget.mType->IsGenericParam()) &&
  7260. ((!callTarget.IsAddr()) || (callTarget.IsReadOnly())) &&
  7261. (callTarget.mKind != BfTypedValueKind_MutableValue) &&
  7262. (moduleMethodInstance.mMethodInstance->mMethodDef->mIsMutating))
  7263. {
  7264. auto genericParamInstance = mModule->GetGenericParamInstance((BfGenericParamType*)callTarget.mType);
  7265. bool needsMut = true;
  7266. if ((genericParamInstance->mGenericParamFlags & (BfGenericParamFlag_StructPtr | BfGenericParamFlag_Class | BfGenericParamFlag_Var)) != 0)
  7267. needsMut = false;
  7268. if (genericParamInstance->mTypeConstraint != NULL)
  7269. {
  7270. auto typeConstaintTypeInstance = genericParamInstance->mTypeConstraint->ToTypeInstance();
  7271. if ((typeConstaintTypeInstance != NULL) && (!typeConstaintTypeInstance->IsComposite()))
  7272. needsMut = false;
  7273. }
  7274. if (needsMut)
  7275. {
  7276. String err = StrFormat("call mutating method '%s' on", mModule->MethodToString(moduleMethodInstance.mMethodInstance).c_str());
  7277. CheckModifyResult(callTarget, targetSrc, err.c_str(), true);
  7278. }
  7279. }
  7280. // Check mut on interface
  7281. if ((callTarget.mType != NULL) &&
  7282. (callTarget.mType->IsInterface()) &&
  7283. (target.IsThis()) &&
  7284. (mModule->mCurTypeInstance) &&
  7285. (!mModule->mCurMethodInstance->mMethodDef->mIsMutating) &&
  7286. (methodDef->mIsMutating))
  7287. {
  7288. mModule->Fail(StrFormat("Cannot call mutating method '%s' within default interface method '%s'. Consider adding 'mut' specifier to this method.",
  7289. mModule->MethodToString(moduleMethodInstance.mMethodInstance).c_str(), mModule->MethodToString(mModule->mCurMethodInstance).c_str()), targetSrc);
  7290. }
  7291. auto result = CreateCall(targetSrc, callTarget, origTarget, methodDef, moduleMethodInstance, bypassVirtual, argValues.mResolvedArgs, skipThis);
  7292. if (result)
  7293. {
  7294. if (result.mType->IsRef())
  7295. result = mModule->RemoveRef(result);
  7296. if (result.mType->IsSelf())
  7297. {
  7298. if (methodMatcher.mSelfType != NULL)
  7299. {
  7300. BF_ASSERT(mModule->IsInGeneric());
  7301. result = mModule->GetDefaultTypedValue(methodMatcher.mSelfType);
  7302. }
  7303. else
  7304. {
  7305. // Will be an error
  7306. result = mModule->GetDefaultTypedValue(methodMatcher.mBestMethodTypeInstance);
  7307. }
  7308. }
  7309. }
  7310. PerformCallChecks(moduleMethodInstance.mMethodInstance, targetSrc);
  7311. if (result)
  7312. {
  7313. bool discardedReturnValue = mUsedAsStatement;
  7314. if (discardedReturnValue)
  7315. {
  7316. auto _ShowDiscardWaring = [&](const String& text, BfCustomAttributes* customAttributes, BfIRConstHolder* constHolder, BfAstNode* refNode)
  7317. {
  7318. if (customAttributes != NULL)
  7319. {
  7320. auto customAttribute = customAttributes->Get(mModule->mCompiler->mNoDiscardAttributeTypeDef);
  7321. if (!customAttribute->mCtorArgs.IsEmpty())
  7322. {
  7323. String* str = mModule->GetStringPoolString(customAttribute->mCtorArgs[0], constHolder);
  7324. if ((str != NULL) && (!str->IsEmpty()))
  7325. {
  7326. mModule->Warn(0, text + ": " + *str, targetSrc);
  7327. return;
  7328. }
  7329. }
  7330. }
  7331. mModule->Warn(0, text, targetSrc);
  7332. };
  7333. bool showedWarning = false;
  7334. if (moduleMethodInstance.mMethodInstance->mMethodDef->mIsNoDiscard)
  7335. {
  7336. _ShowDiscardWaring("Discarding return value of method with [NoDiscard] attribute", moduleMethodInstance.mMethodInstance->GetCustomAttributes(),
  7337. moduleMethodInstance.mMethodInstance->GetOwner()->mConstHolder, targetSrc);
  7338. showedWarning = true;
  7339. }
  7340. auto typeInst = result.mType->ToTypeInstance();
  7341. if (typeInst != NULL)
  7342. {
  7343. if ((typeInst->mTypeDef->mIsNoDiscard) && (!showedWarning))
  7344. {
  7345. _ShowDiscardWaring("Discarding return value whose type has [NoDiscard] attribute", typeInst->mCustomAttributes, typeInst->mConstHolder, targetSrc);
  7346. }
  7347. BfModuleMethodInstance moduleMethodInstance = mModule->GetMethodByName(typeInst, "ReturnValueDiscarded", 0, true);
  7348. if (moduleMethodInstance)
  7349. {
  7350. auto wasGetDefinition = (autoComplete != NULL) && (autoComplete->mIsGetDefinition);
  7351. if (wasGetDefinition)
  7352. autoComplete->mIsGetDefinition = false;
  7353. result = mModule->MakeAddressable(result);
  7354. BfResolvedArgs resolvedArgs;
  7355. MatchMethod(targetSrc, NULL, result, false, false, "ReturnValueDiscarded", resolvedArgs, NULL);
  7356. if (wasGetDefinition)
  7357. autoComplete->mIsGetDefinition = true;
  7358. }
  7359. }
  7360. }
  7361. }
  7362. return result;
  7363. }
  7364. void BfExprEvaluator::LookupQualifiedName(BfQualifiedNameNode* nameNode, bool ignoreInitialError, bool* hadError)
  7365. {
  7366. BfIdentifierNode* nameLeft = nameNode->mLeft;
  7367. BfIdentifierNode* nameRight = nameNode->mRight;
  7368. StringT<64> fieldName;
  7369. if (nameNode->mRight != NULL)
  7370. nameNode->mRight->ToString(fieldName);
  7371. bool wasBaseLookup = false;
  7372. if (auto qualifiedLeftName = BfNodeDynCast<BfQualifiedNameNode>(nameNode->mLeft))
  7373. {
  7374. if (CheckIsBase(qualifiedLeftName->mRight))
  7375. {
  7376. wasBaseLookup = true;
  7377. auto type = mModule->ResolveTypeRef(qualifiedLeftName->mLeft, NULL);
  7378. if (type == NULL)
  7379. return;
  7380. auto fieldName = nameNode->mRight->ToString();
  7381. auto target = mModule->GetThis();
  7382. target.mType = type;
  7383. mResult = LookupField(nameNode->mRight, target, fieldName);
  7384. if ((mPropDef != NULL) && (mPropDef->IsVirtual()))
  7385. mPropDefBypassVirtual = true;
  7386. return;
  7387. }
  7388. }
  7389. if (!wasBaseLookup)
  7390. mResult = LookupIdentifier(nameNode->mLeft, ignoreInitialError, hadError);
  7391. GetResult();
  7392. if (!mResult)
  7393. {
  7394. if (!ignoreInitialError)
  7395. mModule->Fail("Identifier not found", nameNode->mLeft);
  7396. return;
  7397. }
  7398. if (mResult.mType->IsObject())
  7399. {
  7400. mResult = mModule->LoadValue(mResult, 0, mIsVolatileReference);
  7401. }
  7402. else if ((mResult.mType->IsPointer()) && mResult.mType->IsStructOrStructPtr())
  7403. {
  7404. BfPointerType* structPtrType = (BfPointerType*)mResult.mType;
  7405. mResult = mModule->LoadValue(mResult, 0, mIsVolatileReference);
  7406. mResult.mType = structPtrType->mElementType;
  7407. if (mResult.mKind == BfTypedValueKind_ThisValue)
  7408. mResult.mKind = BfTypedValueKind_ThisAddr;
  7409. else
  7410. mResult.mKind = BfTypedValueKind_Addr;
  7411. }
  7412. mIsVolatileReference = false;
  7413. mIsHeapReference = false;
  7414. if (!mResult)
  7415. return;
  7416. auto origResult = mResult;
  7417. auto lookupType = BindGenericType(nameNode, mResult.mType);
  7418. if (mResult.mType->IsVar())
  7419. {
  7420. mResult = BfTypedValue(mModule->GetDefaultValue(mResult.mType), mResult.mType, true);
  7421. return;
  7422. }
  7423. if ((!mResult.mType->IsTypeInstance()) && (!mResult.mType->IsGenericParam()))
  7424. {
  7425. if (hadError != NULL)
  7426. *hadError = true;
  7427. mModule->Fail(StrFormat("Type '%s' has no fields", mModule->TypeToString(mResult.mType).c_str()), nameNode->mLeft);
  7428. mResult = BfTypedValue();
  7429. return;
  7430. }
  7431. BfTypedValue lookupVal = mResult;
  7432. mResult = LookupField(nameNode->mRight, lookupVal, fieldName);
  7433. if ((!mResult) && (mPropDef == NULL) && (lookupType->IsGenericParam()))
  7434. {
  7435. auto genericParamInst = mModule->GetGenericParamInstance((BfGenericParamType*)lookupType);
  7436. SizedArray<BfTypeInstance*, 8> searchConstraints;
  7437. for (auto ifaceConstraint : genericParamInst->mInterfaceConstraints)
  7438. {
  7439. if (!searchConstraints.Contains(ifaceConstraint))
  7440. {
  7441. searchConstraints.push_back(ifaceConstraint);
  7442. for (auto& innerIFaceEntry : ifaceConstraint->mInterfaces)
  7443. {
  7444. auto innerIFace = innerIFaceEntry.mInterfaceType;
  7445. if (!searchConstraints.Contains(innerIFace))
  7446. {
  7447. searchConstraints.push_back(innerIFace);
  7448. }
  7449. }
  7450. }
  7451. }
  7452. BfTypedValue prevTarget;
  7453. BfPropertyDef* prevDef = NULL;
  7454. for (auto ifaceConstraint : searchConstraints)
  7455. {
  7456. BfTypedValue lookupVal = BfTypedValue(mModule->mBfIRBuilder->GetFakeVal(), ifaceConstraint);
  7457. mResult = LookupField(nameNode->mRight, lookupVal, fieldName);
  7458. if (mPropDef != NULL)
  7459. {
  7460. if (prevDef != NULL)
  7461. {
  7462. bool isBetter = mModule->TypeIsSubTypeOf(mPropTarget.mType->ToTypeInstance(), prevTarget.mType->ToTypeInstance());
  7463. bool isWorse = mModule->TypeIsSubTypeOf(prevTarget.mType->ToTypeInstance(), mPropTarget.mType->ToTypeInstance());
  7464. if ((isWorse) && (!isBetter))
  7465. continue;
  7466. if (isBetter == isWorse)
  7467. {
  7468. auto error = mModule->Fail("Ambiguous property reference", nameNode->mRight);
  7469. if (error != NULL)
  7470. {
  7471. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("'%s' has a candidate", mModule->TypeToString(prevTarget.mType).c_str()), prevDef->GetRefNode());
  7472. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("'%s' has a candidate", mModule->TypeToString(mPropTarget.mType).c_str()), mPropDef->GetRefNode());
  7473. }
  7474. }
  7475. }
  7476. prevDef = mPropDef;
  7477. prevTarget = mPropTarget;
  7478. }
  7479. }
  7480. /*if ((mResult) || (mPropDef != NULL))
  7481. break;*/
  7482. }
  7483. if (mPropDef != NULL)
  7484. {
  7485. mOrigPropTarget = origResult;
  7486. if (((CheckIsBase(nameNode->mLeft)) || (wasBaseLookup)) && (mPropDef->IsVirtual()))
  7487. mPropDefBypassVirtual = true;
  7488. }
  7489. if ((mResult) || (mPropDef != NULL))
  7490. return;
  7491. if (hadError != NULL)
  7492. *hadError = true;
  7493. BfTypeInstance* typeInst = lookupType->ToTypeInstance();
  7494. auto compiler = mModule->mCompiler;
  7495. if ((typeInst != NULL) && (compiler->IsAutocomplete()) && (compiler->mResolvePassData->mAutoComplete->CheckFixit(nameNode->mRight)))
  7496. {
  7497. FixitAddMember(typeInst, mExpectingType, nameNode->mRight->ToString(), false);
  7498. }
  7499. mModule->Fail("Unable to find member", nameNode->mRight);
  7500. }
  7501. void BfExprEvaluator::LookupQualifiedName(BfAstNode* nameNode, BfIdentifierNode* nameLeft, BfIdentifierNode* nameRight, bool ignoreInitialError, bool* hadError)
  7502. {
  7503. String fieldName;
  7504. if (nameRight != NULL)
  7505. fieldName = nameRight->ToString();
  7506. bool wasBaseLookup = false;
  7507. if (auto qualifiedLeftName = BfNodeDynCast<BfQualifiedNameNode>(nameLeft))
  7508. {
  7509. if (CheckIsBase(qualifiedLeftName->mRight))
  7510. {
  7511. wasBaseLookup = true;
  7512. auto type = mModule->ResolveTypeRef(qualifiedLeftName->mLeft, NULL);
  7513. if (type == NULL)
  7514. return;
  7515. auto fieldName = nameRight->ToString();
  7516. auto target = mModule->GetThis();
  7517. target.mType = type;
  7518. mResult = LookupField(nameRight, target, fieldName);
  7519. if ((mPropDef != NULL) && (mPropDef->IsVirtual()))
  7520. mPropDefBypassVirtual = true;
  7521. return;
  7522. }
  7523. }
  7524. if (!wasBaseLookup)
  7525. {
  7526. mResult = LookupIdentifier(nameLeft, ignoreInitialError, hadError);
  7527. if ((mResult) && (!mResult.mType->IsComposite()))
  7528. CheckResultForReading(mResult);
  7529. }
  7530. GetResult();
  7531. if (!mResult)
  7532. {
  7533. if (!ignoreInitialError)
  7534. mModule->Fail("Identifier not found", nameLeft);
  7535. return;
  7536. }
  7537. if (mResult.mType->IsObject())
  7538. {
  7539. mResult = mModule->LoadValue(mResult, 0, mIsVolatileReference);
  7540. }
  7541. else if ((mResult.mType->IsPointer()) && mResult.mType->IsStructOrStructPtr())
  7542. {
  7543. BfPointerType* structPtrType = (BfPointerType*)mResult.mType;
  7544. mResult = mModule->LoadValue(mResult, 0, mIsVolatileReference);
  7545. mResult.mType = structPtrType->mElementType;
  7546. if (mResult.mKind == BfTypedValueKind_ThisValue)
  7547. mResult.mKind = BfTypedValueKind_ThisAddr;
  7548. else
  7549. mResult.mKind = BfTypedValueKind_Addr;
  7550. }
  7551. mIsVolatileReference = false;
  7552. mIsHeapReference = false;
  7553. if (!mResult)
  7554. return;
  7555. if (mResult.mType->IsAllocType())
  7556. mResult.mType = mResult.mType->GetUnderlyingType();
  7557. auto origResult = mResult;
  7558. if (mResult.mType->IsVar())
  7559. {
  7560. mResult = BfTypedValue(mModule->GetDefaultValue(mResult.mType), mResult.mType, true);
  7561. return;
  7562. }
  7563. if ((!mResult.mType->IsTypeInstance()) && (!mResult.mType->IsGenericParam()))
  7564. {
  7565. if (mResult.mType->IsSizedArray())
  7566. {
  7567. mResult.mType = mModule->GetWrappedStructType(mResult.mType);
  7568. mResult.mValue = mModule->mBfIRBuilder->CreateBitCast(mResult.mValue, mModule->mBfIRBuilder->MapTypeInstPtr(mResult.mType->ToTypeInstance()));
  7569. }
  7570. else if (mResult.mType->IsWrappableType())
  7571. {
  7572. mResult.mType = mModule->GetWrappedStructType(mResult.mType);
  7573. }
  7574. else
  7575. {
  7576. if (hadError != NULL)
  7577. *hadError = true;
  7578. mModule->Fail(StrFormat("Type '%s' has no fields", mModule->TypeToString(mResult.mType).c_str()), nameLeft);
  7579. mResult = BfTypedValue();
  7580. return;
  7581. }
  7582. }
  7583. BfTypedValue lookupVal = mResult;
  7584. auto lookupType = BindGenericType(nameNode, mResult.mType);
  7585. if ((lookupType->IsGenericParam()) && (!mResult.mType->IsGenericParam()))
  7586. {
  7587. // Try to lookup from generic binding
  7588. mResult = LookupField(nameRight, BfTypedValue(mModule->mBfIRBuilder->GetFakeVal(), lookupType), fieldName, BfLookupFieldFlag_BindOnly);
  7589. if (mPropDef != NULL)
  7590. {
  7591. mOrigPropTarget = lookupVal;
  7592. return;
  7593. }
  7594. }
  7595. if (mPropDef == NULL)
  7596. mResult = LookupField(nameRight, lookupVal, fieldName, CheckIsBase(nameLeft) ? BfLookupFieldFlag_BaseLookup : BfLookupFieldFlag_None);
  7597. if ((!mResult) && (mPropDef == NULL) && (lookupType->IsGenericParam()))
  7598. {
  7599. auto genericParamInst = mModule->GetGenericParamInstance((BfGenericParamType*)lookupType);
  7600. SizedArray<BfTypeInstance*, 8> searchConstraints;
  7601. for (auto ifaceConstraint : genericParamInst->mInterfaceConstraints)
  7602. {
  7603. if (!searchConstraints.Contains(ifaceConstraint))
  7604. {
  7605. searchConstraints.push_back(ifaceConstraint);
  7606. for (auto& innerIFaceEntry : ifaceConstraint->mInterfaces)
  7607. {
  7608. auto innerIFace = innerIFaceEntry.mInterfaceType;
  7609. if (!searchConstraints.Contains(innerIFace))
  7610. {
  7611. searchConstraints.push_back(innerIFace);
  7612. }
  7613. }
  7614. }
  7615. }
  7616. BfTypedValue prevTarget;
  7617. BfPropertyDef* prevDef = NULL;
  7618. for (auto ifaceConstraint : searchConstraints)
  7619. {
  7620. BfTypedValue lookupVal = BfTypedValue(mModule->mBfIRBuilder->GetFakeVal(), ifaceConstraint);
  7621. mResult = LookupField(nameRight, lookupVal, fieldName);
  7622. if (mPropDef != NULL)
  7623. {
  7624. if (prevDef != NULL)
  7625. {
  7626. bool isBetter = mModule->TypeIsSubTypeOf(mPropTarget.mType->ToTypeInstance(), prevTarget.mType->ToTypeInstance());
  7627. bool isWorse = mModule->TypeIsSubTypeOf(prevTarget.mType->ToTypeInstance(), mPropTarget.mType->ToTypeInstance());
  7628. if ((isWorse) && (!isBetter))
  7629. continue;
  7630. if (isBetter == isWorse)
  7631. {
  7632. auto error = mModule->Fail("Ambiguous property reference", nameRight);
  7633. if (error != NULL)
  7634. {
  7635. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("'%s' has a candidate", mModule->TypeToString(prevTarget.mType).c_str()), prevDef->GetRefNode());
  7636. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("'%s' has a candidate", mModule->TypeToString(mPropTarget.mType).c_str()), mPropDef->GetRefNode());
  7637. }
  7638. }
  7639. }
  7640. prevDef = mPropDef;
  7641. prevTarget = mPropTarget;
  7642. }
  7643. }
  7644. }
  7645. if (mPropDef != NULL)
  7646. {
  7647. mOrigPropTarget = origResult;
  7648. if ((CheckIsBase(nameLeft)) || (wasBaseLookup))
  7649. {
  7650. if (mPropDef->IsVirtual())
  7651. mPropDefBypassVirtual = true;
  7652. }
  7653. }
  7654. if ((mResult) || (mPropDef != NULL))
  7655. return;
  7656. if (hadError != NULL)
  7657. *hadError = true;
  7658. BfTypeInstance* typeInst = lookupType->ToTypeInstance();
  7659. auto compiler = mModule->mCompiler;
  7660. if ((typeInst != NULL) && (compiler->IsAutocomplete()) && (compiler->mResolvePassData->mAutoComplete->CheckFixit(nameRight)))
  7661. {
  7662. FixitAddMember(typeInst, mExpectingType, nameRight->ToString(), false);
  7663. }
  7664. mModule->Fail("Unable to find member", nameRight);
  7665. }
  7666. void BfExprEvaluator::LookupQualifiedStaticField(BfQualifiedNameNode* nameNode, bool ignoreIdentifierNotFoundError)
  7667. {
  7668. // Lookup left side as a type
  7669. {
  7670. BfType* type = NULL;
  7671. {
  7672. type = mModule->ResolveTypeRef(nameNode->mLeft, NULL, BfPopulateType_Data, BfResolveTypeRefFlag_AllowRef);
  7673. mModule->CheckTypeRefFixit(nameNode->mLeft);
  7674. }
  7675. if (type != NULL)
  7676. {
  7677. BfTypedValue lookupType;
  7678. if (type->IsWrappableType())
  7679. lookupType = BfTypedValue(mModule->GetWrappedStructType(type));
  7680. else
  7681. lookupType = BfTypedValue(type);
  7682. auto findName = nameNode->mRight->ToString();
  7683. /*if (findName == "base")
  7684. {
  7685. mResult = BfTypedValue(lookupType);
  7686. return;
  7687. }*/
  7688. mResult = LookupField(nameNode->mRight, lookupType, findName);
  7689. if ((mResult) || (mPropDef != NULL))
  7690. return;
  7691. if (lookupType.mType != NULL)
  7692. {
  7693. BfTypeInstance* typeInst = lookupType.mType->ToTypeInstance();
  7694. auto compiler = mModule->mCompiler;
  7695. if ((typeInst != NULL) && (compiler->IsAutocomplete()) && (compiler->mResolvePassData->mAutoComplete->CheckFixit(nameNode->mRight)))
  7696. {
  7697. FixitAddMember(typeInst, mExpectingType, nameNode->mRight->ToString(), true);
  7698. }
  7699. }
  7700. if ((mBfEvalExprFlags & BfEvalExprFlags_NoLookupError) == 0)
  7701. mModule->Fail("Field not found", nameNode->mRight);
  7702. return;
  7703. }
  7704. }
  7705. String fieldName = nameNode->mRight->ToString();
  7706. if (auto qualifiedLeftName = BfNodeDynCast<BfQualifiedNameNode>(nameNode->mLeft))
  7707. LookupQualifiedStaticField(qualifiedLeftName, true);
  7708. else if (auto leftName = BfNodeDynCast<BfIdentifierNode>(nameNode->mLeft))
  7709. {
  7710. mResult = LookupIdentifier(leftName);
  7711. }
  7712. GetResult();
  7713. if (!mResult)
  7714. {
  7715. if (!ignoreIdentifierNotFoundError)
  7716. mModule->Fail("Identifier not found", nameNode->mLeft);
  7717. return;
  7718. }
  7719. if (mResult.mType->IsObject())
  7720. {
  7721. mResult = mModule->LoadValue(mResult);
  7722. }
  7723. else if ((mResult.mType->IsPointer()) && mResult.mType->IsStructOrStructPtr())
  7724. {
  7725. BfPointerType* structPtrType = (BfPointerType*) mResult.mType;
  7726. mResult = mModule->LoadValue(mResult);
  7727. mResult.mType = structPtrType->mElementType;
  7728. }
  7729. if (!mResult)
  7730. return;
  7731. if (!mResult.mType->IsTypeInstance())
  7732. {
  7733. mModule->Fail(StrFormat("Type '%s' has no fields", mModule->TypeToString(mResult.mType).c_str()), nameNode->mLeft);
  7734. return;
  7735. }
  7736. mResult = LookupField(nameNode->mRight, mResult, fieldName);
  7737. if ((mResult) || (mPropDef != NULL))
  7738. return;
  7739. mModule->Fail("Unable to find member", nameNode->mRight);
  7740. }
  7741. void BfExprEvaluator::LookupQualifiedStaticField(BfAstNode* nameNode, BfIdentifierNode* nameLeft, BfIdentifierNode* nameRight, bool ignoreIdentifierNotFoundError)
  7742. {
  7743. // Lookup left side as a type
  7744. {
  7745. BfType* type = NULL;
  7746. {
  7747. SetAndRestoreValue<bool> prevIgnoreErrors(mModule->mIgnoreErrors, true);
  7748. type = mModule->ResolveTypeRef(nameLeft, NULL, BfPopulateType_Declaration, BfResolveTypeRefFlag_AllowRef);
  7749. }
  7750. if (type != NULL)
  7751. {
  7752. BfTypedValue lookupType;
  7753. if (type->IsWrappableType())
  7754. lookupType = BfTypedValue(mModule->GetWrappedStructType(type));
  7755. else
  7756. lookupType = BfTypedValue(type);
  7757. auto findName = nameRight->ToString();
  7758. if ((lookupType.mType != NULL) && (lookupType.mType->IsGenericParam()))
  7759. {
  7760. auto genericParamInstance = mModule->GetGenericParamInstance((BfGenericParamType*)lookupType.mType);
  7761. if (genericParamInstance->mTypeConstraint != NULL)
  7762. {
  7763. mResult = LookupField(nameRight, BfTypedValue(genericParamInstance->mTypeConstraint), findName);
  7764. if ((mResult) || (mPropDef != NULL))
  7765. return;
  7766. }
  7767. for (auto constraint : genericParamInstance->mInterfaceConstraints)
  7768. {
  7769. mResult = LookupField(nameRight, BfTypedValue(constraint), findName);
  7770. if ((mResult) || (mPropDef != NULL))
  7771. return;
  7772. }
  7773. }
  7774. /*if (findName == "base")
  7775. {
  7776. mResult = BfTypedValue(lookupType);
  7777. return;
  7778. }*/
  7779. mResult = LookupField(nameRight, lookupType, findName);
  7780. if ((mResult) || (mPropDef != NULL))
  7781. return;
  7782. if (lookupType.mType != NULL)
  7783. {
  7784. BfTypeInstance* typeInst = lookupType.mType->ToTypeInstance();
  7785. auto compiler = mModule->mCompiler;
  7786. if ((typeInst != NULL) && (compiler->IsAutocomplete()) && (compiler->mResolvePassData->mAutoComplete->CheckFixit(nameRight)))
  7787. {
  7788. FixitAddMember(typeInst, mExpectingType, nameRight->ToString(), true);
  7789. }
  7790. }
  7791. if ((mBfEvalExprFlags & BfEvalExprFlags_NoLookupError) == 0)
  7792. mModule->Fail("Field not found", nameRight);
  7793. return;
  7794. }
  7795. }
  7796. String fieldName = nameRight->ToString();
  7797. if (auto qualifiedLeftName = BfNodeDynCast<BfQualifiedNameNode>(nameLeft))
  7798. LookupQualifiedStaticField(qualifiedLeftName, qualifiedLeftName->mLeft, qualifiedLeftName->mRight, true);
  7799. else if (auto leftName = BfNodeDynCast<BfIdentifierNode>(nameLeft))
  7800. {
  7801. mResult = LookupIdentifier(leftName);
  7802. }
  7803. GetResult();
  7804. if (!mResult)
  7805. {
  7806. if (!ignoreIdentifierNotFoundError)
  7807. mModule->Fail("Identifier not found", nameLeft);
  7808. return;
  7809. }
  7810. if (mResult.mType->IsObject())
  7811. {
  7812. mResult = mModule->LoadValue(mResult);
  7813. }
  7814. else if ((mResult.mType->IsPointer()) && mResult.mType->IsStructOrStructPtr())
  7815. {
  7816. BfPointerType* structPtrType = (BfPointerType*)mResult.mType;
  7817. mResult = mModule->LoadValue(mResult);
  7818. mResult = BfTypedValue(mResult.mValue, structPtrType->mElementType, true);
  7819. }
  7820. if (!mResult)
  7821. return;
  7822. if (!mResult.mType->IsTypeInstance())
  7823. {
  7824. if (mResult.mType->IsSizedArray())
  7825. {
  7826. mResult.mType = mModule->GetWrappedStructType(mResult.mType);
  7827. mResult.mValue = mModule->mBfIRBuilder->CreateBitCast(mResult.mValue, mModule->mBfIRBuilder->MapTypeInstPtr(mResult.mType->ToTypeInstance()));
  7828. }
  7829. else if (mResult.mType->IsWrappableType())
  7830. {
  7831. mResult.mType = mModule->GetWrappedStructType(mResult.mType);
  7832. }
  7833. else
  7834. {
  7835. mModule->Fail(StrFormat("Type '%s' has no fields", mModule->TypeToString(mResult.mType).c_str()), nameLeft);
  7836. return;
  7837. }
  7838. }
  7839. mResult = LookupField(nameRight, mResult, fieldName);
  7840. if ((mResult) || (mPropDef != NULL))
  7841. return;
  7842. mModule->CheckTypeRefFixit(nameLeft);
  7843. mModule->Fail("Unable to find member", nameRight);
  7844. }
  7845. void BfExprEvaluator::Visit(BfQualifiedNameNode* nameNode)
  7846. {
  7847. auto autoComplete = GetAutoComplete();
  7848. if (autoComplete != NULL)
  7849. {
  7850. autoComplete->CheckMemberReference(nameNode->mLeft, nameNode->mDot, nameNode->mRight);
  7851. }
  7852. bool hadError = false;
  7853. LookupQualifiedName(nameNode, nameNode->mLeft, nameNode->mRight, true, &hadError);
  7854. if ((mResult) || (mPropDef != NULL))
  7855. return;
  7856. if (hadError)
  7857. return;
  7858. LookupQualifiedStaticField(nameNode, nameNode->mLeft, nameNode->mRight, false);
  7859. }
  7860. void BfExprEvaluator::Visit(BfThisExpression* thisExpr)
  7861. {
  7862. mResult = mModule->GetThis();
  7863. if (!mResult)
  7864. {
  7865. mModule->Fail("Static methods don't have 'this'", thisExpr);
  7866. return;
  7867. }
  7868. auto autoComplete = GetAutoComplete();
  7869. if ((autoComplete != NULL) && (autoComplete->IsAutocompleteNode(thisExpr)))
  7870. autoComplete->SetDefinitionLocation(mModule->mCurTypeInstance->mTypeDef->GetRefNode());
  7871. mResultLocalVar = mModule->GetThisVariable();
  7872. mResultFieldInstance = NULL;
  7873. }
  7874. void BfExprEvaluator::Visit(BfBaseExpression* baseExpr)
  7875. {
  7876. mResult = mModule->GetThis();
  7877. if (!mResult)
  7878. {
  7879. mModule->Fail("Static methods don't have 'base'", baseExpr);
  7880. return;
  7881. }
  7882. auto baseType = mModule->mCurTypeInstance->mBaseType;
  7883. if (baseType == NULL)
  7884. baseType = mModule->mContext->mBfObjectType;
  7885. auto autoComplete = GetAutoComplete();
  7886. if ((autoComplete != NULL) && (autoComplete->IsAutocompleteNode(baseExpr)))
  7887. autoComplete->SetDefinitionLocation(baseType->mTypeDef->GetRefNode());
  7888. mModule->PopulateType(baseType, BfPopulateType_Data);
  7889. mResult = mModule->Cast(baseExpr, mResult, baseType, BfCastFlags_Explicit);
  7890. }
  7891. void BfExprEvaluator::Visit(BfMixinExpression* mixinExpr)
  7892. {
  7893. if (mModule->mCurMethodInstance->mMethodDef->mMethodType == BfMethodType_Mixin)
  7894. {
  7895. auto varType = mModule->GetPrimitiveType(BfTypeCode_Var);
  7896. auto newVar = mModule->AllocFromType(varType, mModule->mCurMethodState->mCurScope);
  7897. mResult = BfTypedValue(newVar, varType, true);
  7898. return;
  7899. }
  7900. auto curMethodState = mModule->mCurMethodState;
  7901. if (curMethodState->mMixinState == NULL)
  7902. {
  7903. mModule->Fail("Mixin references can only be used within mixins", mixinExpr);
  7904. return;
  7905. }
  7906. int localIdx = GetMixinVariable();
  7907. if (localIdx != -1)
  7908. {
  7909. auto varDecl = curMethodState->mLocals[localIdx];
  7910. if (varDecl != NULL)
  7911. {
  7912. BfTypedValue localResult = LoadLocal(varDecl);
  7913. mResult = localResult;
  7914. mResultLocalVar = varDecl;
  7915. mResultFieldInstance = NULL;
  7916. mResultLocalVarRefNode = mixinExpr;
  7917. return;
  7918. }
  7919. }
  7920. if (mModule->mCurMethodInstance->mIsUnspecialized)
  7921. {
  7922. mResult = mModule->GetDefaultTypedValue(mModule->GetPrimitiveType(BfTypeCode_Var));
  7923. return;
  7924. }
  7925. mModule->Fail("Mixin value cannot be inferred", mixinExpr);
  7926. }
  7927. void BfExprEvaluator::Visit(BfSizedArrayCreateExpression* createExpr)
  7928. {
  7929. auto type = mModule->ResolveTypeRef(createExpr->mTypeRef);
  7930. if (type == NULL)
  7931. return;
  7932. if (type->IsArray())
  7933. {
  7934. // If we have a case like 'int[] (1, 2)' then we infer the sized array size from the initializer
  7935. auto arrayType = (BfArrayType*)type;
  7936. if (arrayType->mDimensions == 1)
  7937. {
  7938. int arraySize = 0;
  7939. if (auto arrayInitExpr = BfNodeDynCast<BfCollectionInitializerExpression>(createExpr->mInitializer))
  7940. {
  7941. arraySize = (int)arrayInitExpr->mValues.size();
  7942. }
  7943. type = mModule->CreateSizedArrayType(arrayType->GetUnderlyingType(), arraySize);
  7944. }
  7945. }
  7946. if (!type->IsSizedArray())
  7947. {
  7948. mModule->Fail("Sized array expected", createExpr->mTypeRef);
  7949. return;
  7950. }
  7951. BfSizedArrayType* arrayType = (BfSizedArrayType*)type;
  7952. if (createExpr->mInitializer == NULL)
  7953. {
  7954. mModule->AssertErrorState();
  7955. mResult = mModule->GetDefaultTypedValue(arrayType);
  7956. return;
  7957. }
  7958. InitializedSizedArray(arrayType, createExpr->mInitializer->mOpenBrace, createExpr->mInitializer->mValues, createExpr->mInitializer->mCommas, createExpr->mInitializer->mCloseBrace);
  7959. }
  7960. void BfExprEvaluator::Visit(BfInitializerExpression* initExpr)
  7961. {
  7962. VisitChild(initExpr->mTarget);
  7963. if (!mResult)
  7964. mResult = mModule->GetDefaultTypedValue(mModule->mContext->mBfObjectType);
  7965. BfTypedValue initValue = GetResult(true);
  7966. bool isFirstAdd = true;
  7967. BfFunctionBindResult addFunctionBindResult;
  7968. addFunctionBindResult.mWantsArgs = true;
  7969. for (auto elementExpr : initExpr->mValues)
  7970. {
  7971. bool wasValidInitKind = false;
  7972. if (auto assignExpr = BfNodeDynCast<BfAssignmentExpression>(elementExpr))
  7973. {
  7974. BfTypedValue fieldResult;
  7975. if (auto identifierNode = BfNodeDynCast<BfIdentifierNode>(assignExpr->mLeft))
  7976. {
  7977. StringT<128> findName;
  7978. identifierNode->ToString(findName);
  7979. fieldResult = LookupField(identifierNode, initValue, findName, BfLookupFieldFlag_IsImplicitThis);
  7980. if ((fieldResult.mKind == BfTypedValueKind_TempAddr) || (fieldResult.mKind == BfTypedValueKind_RestrictedTempAddr))
  7981. fieldResult.mKind = BfTypedValueKind_Addr;
  7982. wasValidInitKind = true;
  7983. if ((fieldResult) || (mPropDef != NULL))
  7984. {
  7985. mResult = fieldResult;
  7986. PerformAssignment(assignExpr, true, BfTypedValue());
  7987. mResult = BfTypedValue();
  7988. }
  7989. else
  7990. {
  7991. mModule->Fail(StrFormat("'%s' does not contain a definition for '%s'", mModule->TypeToString(initValue.mType).c_str(),
  7992. findName.c_str()), identifierNode);
  7993. }
  7994. }
  7995. }
  7996. else
  7997. {
  7998. auto autoComplete = GetAutoComplete();
  7999. if ((autoComplete != NULL) && (autoComplete->IsAutocompleteNode(elementExpr)))
  8000. {
  8001. if (auto identiferNode = BfNodeDynCast<BfIdentifierNode>(elementExpr))
  8002. {
  8003. auto typeInstance = initValue.mType->ToTypeInstance();
  8004. if (typeInstance != NULL)
  8005. {
  8006. String filter;
  8007. identiferNode->ToString(filter);
  8008. autoComplete->AddTypeMembers(typeInstance, false, true, filter, typeInstance, false, true);
  8009. }
  8010. }
  8011. }
  8012. bool wasFirstAdd = isFirstAdd;
  8013. if (isFirstAdd)
  8014. {
  8015. BfExprEvaluator exprEvaluator(mModule);
  8016. exprEvaluator.mFunctionBindResult = &addFunctionBindResult;
  8017. SizedArray<BfExpression*, 2> argExprs;
  8018. argExprs.push_back(elementExpr);
  8019. BfSizedArray<BfExpression*> sizedArgExprs(argExprs);
  8020. BfResolvedArgs argValues(&sizedArgExprs);
  8021. exprEvaluator.ResolveArgValues(argValues);
  8022. exprEvaluator.MatchMethod(elementExpr, NULL, initValue, false, false, "Add", argValues, NULL);
  8023. if (addFunctionBindResult.mMethodInstance != NULL)
  8024. CreateCall(initExpr, addFunctionBindResult.mMethodInstance, addFunctionBindResult.mFunc, true, addFunctionBindResult.mIRArgs);
  8025. isFirstAdd = false;
  8026. }
  8027. else if ((addFunctionBindResult.mMethodInstance == NULL) || (addFunctionBindResult.mMethodInstance->GetParamCount() == 0))
  8028. {
  8029. mModule->CreateValueFromExpression(elementExpr);
  8030. }
  8031. else
  8032. {
  8033. auto argValue = mModule->CreateValueFromExpression(elementExpr, addFunctionBindResult.mMethodInstance->GetParamType(0));
  8034. if ((argValue) && (!mModule->mBfIRBuilder->mIgnoreWrites))
  8035. {
  8036. SizedArray<BfIRValue, 2> irArgs;
  8037. PushThis(elementExpr, initValue, addFunctionBindResult.mMethodInstance, irArgs);
  8038. PushArg(argValue, irArgs);
  8039. for (int argIdx = (int)irArgs.size(); argIdx < (int)addFunctionBindResult.mIRArgs.size(); argIdx++)
  8040. irArgs.Add(addFunctionBindResult.mIRArgs[argIdx]);
  8041. CreateCall(initExpr, addFunctionBindResult.mMethodInstance, addFunctionBindResult.mFunc, true, irArgs);
  8042. }
  8043. }
  8044. wasValidInitKind = true;
  8045. }
  8046. if (!wasValidInitKind)
  8047. {
  8048. mModule->Fail("Invalid initializer member declarator", initExpr);
  8049. }
  8050. }
  8051. mResult = initValue;
  8052. }
  8053. void BfExprEvaluator::Visit(BfCollectionInitializerExpression* arrayInitExpr)
  8054. {
  8055. mModule->Fail("Collection initializer not usable here", arrayInitExpr);
  8056. }
  8057. void BfExprEvaluator::Visit(BfTypeOfExpression* typeOfExpr)
  8058. {
  8059. auto typeType = mModule->ResolveTypeDef(mModule->mCompiler->mTypeTypeDef);
  8060. auto autoComplete = GetAutoComplete();
  8061. if ((autoComplete != NULL) && (typeOfExpr->mTypeRef != NULL))
  8062. {
  8063. autoComplete->CheckTypeRef(typeOfExpr->mTypeRef, false, true);
  8064. }
  8065. BfType* type;
  8066. if (auto genericTypeRef = BfNodeDynCast<BfGenericInstanceTypeRef>(typeOfExpr->mTypeRef))
  8067. {
  8068. type = mModule->ResolveTypeRefAllowUnboundGenerics(typeOfExpr->mTypeRef, BfPopulateType_Identity);
  8069. }
  8070. else
  8071. {
  8072. type = ResolveTypeRef(typeOfExpr->mTypeRef, BfPopulateType_Identity);
  8073. }
  8074. if (type == NULL)
  8075. {
  8076. mResult = mModule->GetDefaultTypedValue(mModule->ResolveTypeDef(mModule->mCompiler->mTypeTypeDef));
  8077. return;
  8078. }
  8079. mModule->AddDependency(type, mModule->mCurTypeInstance, BfDependencyMap::DependencyFlag_ExprTypeReference);
  8080. mResult = BfTypedValue(mModule->CreateTypeDataRef(type), typeType);
  8081. }
  8082. bool BfExprEvaluator::LookupTypeProp(BfTypeOfExpression* typeOfExpr, BfIdentifierNode* propName)
  8083. {
  8084. // We ignore errors because we go through the normal Visit(BfTypeOfExpression) if this fails, which will throw the error again
  8085. SetAndRestoreValue<bool> prevIgnoreErrors(mModule->mIgnoreErrors, true);
  8086. auto typeType = mModule->ResolveTypeDef(mModule->mCompiler->mTypeTypeDef);
  8087. BfType* type;
  8088. if (auto genericTypeRef = BfNodeDynCast<BfGenericInstanceTypeRef>(typeOfExpr->mTypeRef))
  8089. {
  8090. type = mModule->ResolveTypeRefAllowUnboundGenerics(typeOfExpr->mTypeRef, BfPopulateType_Identity);
  8091. }
  8092. else
  8093. {
  8094. type = ResolveTypeRef(typeOfExpr->mTypeRef, BfPopulateType_Identity);
  8095. }
  8096. if (type == NULL)
  8097. {
  8098. mResult = mModule->GetDefaultTypedValue(mModule->ResolveTypeDef(mModule->mCompiler->mTypeTypeDef));
  8099. return false;
  8100. }
  8101. mModule->AddDependency(type, mModule->mCurTypeInstance, BfDependencyMap::DependencyFlag_ExprTypeReference);
  8102. mModule->PopulateType(type);
  8103. auto typeInstance = type->ToTypeInstance();
  8104. auto _BoolResult = [&](bool val)
  8105. {
  8106. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConst(BfTypeCode_Boolean, val ? 1 : 0), mModule->GetPrimitiveType(BfTypeCode_Boolean));
  8107. };
  8108. auto _Int32Result = [&](int32 val)
  8109. {
  8110. mResult = BfTypedValue(mModule->GetConstValue32(val), mModule->GetPrimitiveType(BfTypeCode_Int32));
  8111. };
  8112. String memberName;
  8113. propName->ToString(memberName);
  8114. bool handled = true;
  8115. if (memberName == "IsTypedPrimitive")
  8116. _BoolResult(type->IsPrimitiveType());
  8117. else if (memberName == "IsObject")
  8118. _BoolResult(type->IsObject());
  8119. else if (memberName == "IsValueType")
  8120. _BoolResult(type->IsValueType());
  8121. else if (memberName == "IsStruct")
  8122. _BoolResult(type->IsStruct());
  8123. else if (memberName == "IsSplattable")
  8124. _BoolResult(type->IsSplattable());
  8125. else if (memberName == "IsUnion")
  8126. _BoolResult(type->IsUnion());
  8127. else if (memberName == "IsBoxed")
  8128. _BoolResult(type->IsBoxed());
  8129. else if (memberName == "IsEnum")
  8130. _BoolResult(type->IsEnum());
  8131. else if (memberName == "IsTuple")
  8132. _BoolResult(type->IsTuple());
  8133. else if (memberName == "IsNullable")
  8134. _BoolResult(type->IsNullable());
  8135. else if (memberName == "IsGenericType")
  8136. _BoolResult(type->IsGenericTypeInstance());
  8137. else if (memberName == "TypeId")
  8138. _Int32Result(type->mTypeId);
  8139. else if (memberName == "GenericParamCount")
  8140. {
  8141. auto genericTypeInst = type->ToGenericTypeInstance();
  8142. _Int32Result((genericTypeInst != NULL) ? (int)genericTypeInst->mGenericTypeInfo->mTypeGenericArguments.size() : 0);
  8143. }
  8144. else if (memberName == "Size")
  8145. _Int32Result(type->mSize);
  8146. else if (memberName == "Align")
  8147. _Int32Result(type->mAlign);
  8148. else if (memberName == "Stride")
  8149. _Int32Result(type->GetStride());
  8150. else if (memberName == "InstanceSize")
  8151. _Int32Result((typeInstance != NULL) ? typeInstance->mInstSize : type->mSize);
  8152. else if (memberName == "InstanceAlign")
  8153. _Int32Result((typeInstance != NULL) ? typeInstance->mInstAlign : type->mSize);
  8154. else if (memberName == "InstanceStride")
  8155. _Int32Result((typeInstance != NULL) ? typeInstance->GetInstStride() : type->GetStride());
  8156. else if ((memberName == "MinValue") || (memberName == "MaxValue"))
  8157. {
  8158. bool isMin = memberName == "MinValue";
  8159. BfType* checkType = typeInstance;
  8160. if (checkType->IsTypedPrimitive())
  8161. checkType = checkType->GetUnderlyingType();
  8162. if (checkType->IsPrimitiveType())
  8163. {
  8164. auto primType = (BfPrimitiveType*)checkType;
  8165. if (typeInstance->IsEnum())
  8166. {
  8167. if (typeInstance->mTypeInfoEx != NULL)
  8168. {
  8169. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConst(primType->mTypeDef->mTypeCode, isMin ? (uint64)typeInstance->mTypeInfoEx->mMinValue : (uint64)typeInstance->mTypeInfoEx->mMaxValue), typeInstance);
  8170. return true;
  8171. }
  8172. }
  8173. else
  8174. {
  8175. switch (primType->mTypeDef->mTypeCode)
  8176. {
  8177. case BfTypeCode_Int8:
  8178. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConst(primType->mTypeDef->mTypeCode, isMin ? -0x80 : 0x7F), typeInstance);
  8179. return true;
  8180. case BfTypeCode_Int16:
  8181. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConst(primType->mTypeDef->mTypeCode, isMin ? -0x8000 : 0x7FFF), typeInstance);
  8182. return true;
  8183. case BfTypeCode_Int32:
  8184. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConst(primType->mTypeDef->mTypeCode, isMin ? (uint64)-0x80000000LL : 0x7FFFFFFF), typeInstance);
  8185. return true;
  8186. case BfTypeCode_Int64:
  8187. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConst(primType->mTypeDef->mTypeCode, isMin ? (uint64)-0x8000000000000000LL : (uint64)0x7FFFFFFFFFFFFFFFLL), typeInstance);
  8188. return true;
  8189. case BfTypeCode_UInt8:
  8190. case BfTypeCode_Char8:
  8191. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConst(primType->mTypeDef->mTypeCode, isMin ? 0 : 0xFF), typeInstance);
  8192. return true;
  8193. case BfTypeCode_UInt16:
  8194. case BfTypeCode_Char16:
  8195. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConst(primType->mTypeDef->mTypeCode, isMin ? 0 : 0xFFFF), typeInstance);
  8196. return true;
  8197. case BfTypeCode_UInt32:
  8198. case BfTypeCode_Char32:
  8199. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConst(primType->mTypeDef->mTypeCode, isMin ? 0 : (uint64)0xFFFFFFFFLL), typeInstance);
  8200. return true;
  8201. case BfTypeCode_UInt64:
  8202. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConst(primType->mTypeDef->mTypeCode, isMin ? 0 : (uint64)0xFFFFFFFFFFFFFFFFLL), typeInstance);
  8203. return true;
  8204. default: break;
  8205. }
  8206. }
  8207. }
  8208. if (typeInstance->IsEnum())
  8209. {
  8210. mModule->Fail("'MinValue' cannot be used on enums with payloads", propName);
  8211. }
  8212. else
  8213. {
  8214. mModule->Fail(StrFormat("'%s' cannot be used on type '%s'", memberName.c_str(), mModule->TypeToString(typeInstance).c_str()), propName);
  8215. }
  8216. }
  8217. else
  8218. return false;
  8219. auto autoComplete = GetAutoComplete();
  8220. if ((autoComplete != NULL) && (typeOfExpr->mTypeRef != NULL))
  8221. {
  8222. autoComplete->CheckTypeRef(typeOfExpr->mTypeRef, false, true);
  8223. }
  8224. return true;
  8225. }
  8226. void BfExprEvaluator::DoTypeIntAttr(BfTypeReference* typeRef, BfToken token)
  8227. {
  8228. auto type = mModule->ResolveTypeRef(typeRef, BfPopulateType_Data, BfResolveTypeRefFlag_AutoComplete);
  8229. if (type == NULL)
  8230. return;
  8231. mModule->AddDependency(type, mModule->mCurTypeInstance, BfDependencyMap::DependencyFlag_LocalUsage); // Local usage ensures it changes when the type data changes
  8232. auto typeInst = type->ToTypeInstance();
  8233. if ((typeInst != NULL) && (typeInst->mTypeDef->mIsOpaque))
  8234. {
  8235. mModule->Fail(StrFormat("Unable to determine attributes for opaque type '%s'", mModule->TypeToString(type).c_str()), typeRef);
  8236. }
  8237. BfType* sizeType = mModule->GetPrimitiveType(BfTypeCode_Int32);
  8238. int attrVal = 0;
  8239. switch (token)
  8240. {
  8241. case BfToken_SizeOf: attrVal = type->mSize; break;
  8242. case BfToken_AlignOf: attrVal = type->mAlign; break;
  8243. case BfToken_StrideOf: attrVal = type->GetStride(); break;
  8244. default: break;
  8245. }
  8246. bool isUndefVal = false;
  8247. if (type->IsGenericParam())
  8248. isUndefVal = true;
  8249. if (type->IsSizedArray())
  8250. {
  8251. auto sizedArray = (BfSizedArrayType*)type;
  8252. if (sizedArray->mElementCount == -1)
  8253. isUndefVal = true;
  8254. }
  8255. if (isUndefVal)
  8256. {
  8257. // We do this so we know it's a constant but we can't assume anything about its value
  8258. // We make the value an Int32 which doesn't match the IntPtr type, but it allows us to
  8259. // assume it can be implicitly cased to int32
  8260. mResult = BfTypedValue(mModule->mBfIRBuilder->GetUndefConstValue(BfTypeCode_Int32), sizeType);
  8261. }
  8262. else
  8263. mResult = BfTypedValue(mModule->GetConstValue(attrVal, sizeType), sizeType);
  8264. }
  8265. void BfExprEvaluator::Visit(BfSizeOfExpression* sizeOfExpr)
  8266. {
  8267. DoTypeIntAttr(sizeOfExpr->mTypeRef, BfToken_SizeOf);
  8268. }
  8269. void BfExprEvaluator::Visit(BfAlignOfExpression* alignOfExpr)
  8270. {
  8271. DoTypeIntAttr(alignOfExpr->mTypeRef, BfToken_AlignOf);
  8272. }
  8273. void BfExprEvaluator::Visit(BfStrideOfExpression* strideOfExpr)
  8274. {
  8275. DoTypeIntAttr(strideOfExpr->mTypeRef, BfToken_StrideOf);
  8276. }
  8277. void BfExprEvaluator::Visit(BfDefaultExpression* defaultExpr)
  8278. {
  8279. auto autoComplete = GetAutoComplete();
  8280. if (autoComplete != NULL)
  8281. autoComplete->CheckTypeRef(defaultExpr->mTypeRef, false, true);
  8282. BfType* type = NULL;
  8283. if (defaultExpr->mOpenParen == NULL)
  8284. {
  8285. if (mExpectingType)
  8286. {
  8287. type = mExpectingType;
  8288. }
  8289. else
  8290. {
  8291. mModule->Fail("Type cannot be inferred, consider adding explicit type name", defaultExpr);
  8292. return;
  8293. }
  8294. }
  8295. else
  8296. type = mModule->ResolveTypeRef(defaultExpr->mTypeRef);
  8297. if (type == NULL)
  8298. return;
  8299. BfDefaultValueKind defaultKind = BfDefaultValueKind_Const;
  8300. if (type->IsRef())
  8301. {
  8302. mModule->Fail(StrFormat("There is no default value for type '%s'", mModule->TypeToString(type).c_str()), defaultExpr);
  8303. defaultKind = BfDefaultValueKind_Addr;
  8304. }
  8305. mModule->ValidateAllocation(type, defaultExpr->mTypeRef);
  8306. mModule->AddDependency(type, mModule->mCurTypeInstance, BfDependencyMap::DependencyFlag_ExprTypeReference);
  8307. mResult = mModule->GetDefaultTypedValue(type, true, defaultKind);
  8308. }
  8309. void BfExprEvaluator::Visit(BfUninitializedExpression* uninitialziedExpr)
  8310. {
  8311. mModule->Fail("Invalid use of the '?' uninitialized specifier", uninitialziedExpr);
  8312. }
  8313. void BfExprEvaluator::Visit(BfCheckTypeExpression* checkTypeExpr)
  8314. {
  8315. auto targetValue = mModule->CreateValueFromExpression(checkTypeExpr->mTarget);
  8316. if (!targetValue)
  8317. return;
  8318. if (checkTypeExpr->mTypeRef == NULL)
  8319. {
  8320. mModule->AssertErrorState();
  8321. return;
  8322. }
  8323. auto autoComplete = GetAutoComplete();
  8324. if (autoComplete != NULL)
  8325. autoComplete->CheckTypeRef(checkTypeExpr->mTypeRef, false, true);
  8326. auto targetType = mModule->ResolveTypeRef(checkTypeExpr->mTypeRef);
  8327. if (!targetType)
  8328. {
  8329. mModule->AssertErrorState();
  8330. return;
  8331. }
  8332. mModule->AddDependency(targetType, mModule->mCurTypeInstance, BfDependencyMap::DependencyFlag_ExprTypeReference);
  8333. auto boolType = mModule->GetPrimitiveType(BfTypeCode_Boolean);
  8334. if (targetValue.mType->IsValueTypeOrValueTypePtr())
  8335. {
  8336. auto typeInstance = targetValue.mType->ToTypeInstance();
  8337. if (targetValue.mType->IsWrappableType())
  8338. typeInstance = mModule->GetWrappedStructType(targetValue.mType);
  8339. bool matches = (targetValue.mType == targetType) || (mModule->mContext->mBfObjectType == targetType);
  8340. if (!matches)
  8341. matches = mModule->TypeIsSubTypeOf(typeInstance, targetType->ToTypeInstance());
  8342. mResult = BfTypedValue(mModule->GetConstValue(matches ? 1 : 0, boolType), boolType);
  8343. return;
  8344. }
  8345. if (targetType->IsValueType())
  8346. {
  8347. if ((targetValue.mType != mModule->mContext->mBfObjectType) && (!targetValue.mType->IsInterface()))
  8348. {
  8349. mResult = BfTypedValue(mModule->GetConstValue(0, boolType), boolType);
  8350. return;
  8351. }
  8352. }
  8353. int wantTypeId = 0;
  8354. if (!targetType->IsGenericParam())
  8355. wantTypeId = targetType->mTypeId;
  8356. auto objectType = mModule->mContext->mBfObjectType;
  8357. mModule->PopulateType(objectType, BfPopulateType_Full);
  8358. targetValue = mModule->LoadValue(targetValue);
  8359. BfTypeInstance* srcTypeInstance = targetValue.mType->ToTypeInstance();
  8360. BfTypeInstance* targetTypeInstance = targetType->ToTypeInstance();
  8361. bool wasGenericParamType = false;
  8362. if ((srcTypeInstance != NULL) && (targetTypeInstance != NULL))
  8363. {
  8364. if (mModule->TypeIsSubTypeOf(srcTypeInstance, targetTypeInstance))
  8365. {
  8366. // We don't give this warning when we have wasGenericParmType set because that indicates we had a generic type constraint,
  8367. // and a type constraint infers that the ACTUAL type used will be equal to or derived from that type and therefore
  8368. // it may be a "necessary cast" indeed
  8369. if ((!wasGenericParamType) && (mModule->mCurMethodState->mMixinState == NULL))
  8370. {
  8371. if (srcTypeInstance == targetType)
  8372. mModule->Warn(BfWarning_BF4203_UnnecessaryDynamicCast, StrFormat("Unnecessary cast, the value is already type '%s'",
  8373. mModule->TypeToString(srcTypeInstance).c_str()), checkTypeExpr->mIsToken);
  8374. else
  8375. mModule->Warn(BfWarning_BF4203_UnnecessaryDynamicCast, StrFormat("Unnecessary cast, '%s' is a subtype of '%s'",
  8376. mModule->TypeToString(srcTypeInstance).c_str(), mModule->TypeToString(targetType).c_str()), checkTypeExpr->mIsToken);
  8377. }
  8378. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConst(BfTypeCode_Boolean, 1), boolType);
  8379. return;
  8380. }
  8381. else if ((!targetType->IsInterface()) && (srcTypeInstance != mModule->mContext->mBfObjectType) && (!mModule->TypeIsSubTypeOf(targetTypeInstance, srcTypeInstance)))
  8382. {
  8383. mModule->Fail(StrFormat("Cannot convert type '%s' to '%s' via any conversion",
  8384. mModule->TypeToString(targetValue.mType).c_str(), mModule->TypeToString(targetTypeInstance).c_str()), checkTypeExpr->mIsToken);
  8385. }
  8386. }
  8387. if (mModule->mCompiler->IsAutocomplete())
  8388. {
  8389. mResult = mModule->GetDefaultTypedValue(boolType, false, BfDefaultValueKind_Addr);
  8390. return;
  8391. }
  8392. auto irb = mModule->mBfIRBuilder;
  8393. auto prevBB = mModule->mBfIRBuilder->GetInsertBlock();
  8394. auto matchBB = mModule->mBfIRBuilder->CreateBlock("is.match");
  8395. auto endBB = mModule->mBfIRBuilder->CreateBlock("is.done");
  8396. BfIRValue boolResult = mModule->CreateAlloca(boolType);
  8397. irb->CreateStore(irb->CreateConst(BfTypeCode_Boolean, 0), boolResult);
  8398. mModule->EmitDynamicCastCheck(targetValue, targetType, matchBB, endBB);
  8399. mModule->AddBasicBlock(matchBB);
  8400. irb->CreateStore(irb->CreateConst(BfTypeCode_Boolean, 1), boolResult);
  8401. irb->CreateBr(endBB);
  8402. mModule->AddBasicBlock(endBB);
  8403. mResult = BfTypedValue(irb->CreateLoad(boolResult), boolType);
  8404. }
  8405. void BfExprEvaluator::Visit(BfDynamicCastExpression* dynCastExpr)
  8406. {
  8407. auto targetValue = mModule->CreateValueFromExpression(dynCastExpr->mTarget);
  8408. auto targetType = mModule->ResolveTypeRefAllowUnboundGenerics(dynCastExpr->mTypeRef, BfPopulateType_Data, false);
  8409. auto autoComplete = GetAutoComplete();
  8410. if (autoComplete != NULL)
  8411. {
  8412. autoComplete->CheckTypeRef(dynCastExpr->mTypeRef, false, true);
  8413. }
  8414. auto origTargetType = targetType;
  8415. if (!targetValue)
  8416. return;
  8417. if (!targetType)
  8418. {
  8419. mModule->AssertErrorState();
  8420. return;
  8421. }
  8422. bool wasGenericParamType = false;
  8423. if (targetType->IsGenericParam())
  8424. {
  8425. //targetType = mModule->ResolveGenericType(targetType);
  8426. //wasGenericParamType = true;
  8427. }
  8428. if ((targetValue.mType->IsMethodRef()) || (targetType->IsMethodRef()))
  8429. {
  8430. // We can never cast a MethodRef to any class type
  8431. mResult = mModule->GetDefaultTypedValue(targetType);
  8432. return;
  8433. }
  8434. if (mModule->mContext->mResolvingVarField)
  8435. {
  8436. mResult = mModule->GetDefaultTypedValue(targetType);
  8437. return;
  8438. }
  8439. mModule->AddDependency(targetType, mModule->mCurTypeInstance, BfDependencyMap::DependencyFlag_ExprTypeReference);
  8440. if (targetType->IsGenericParam())
  8441. {
  8442. wasGenericParamType = true;
  8443. //wasGenericParamType = false; // "was", not "is"
  8444. auto genericParamType = (BfGenericParamType*) targetType;
  8445. auto genericParam = mModule->GetGenericParamInstance(genericParamType);
  8446. auto typeConstraint = genericParam->mTypeConstraint;
  8447. if ((typeConstraint == NULL) && (genericParam->mGenericParamFlags & (BfGenericParamFlag_Class | BfGenericParamFlag_Interface)))
  8448. typeConstraint = mModule->mContext->mBfObjectType;
  8449. if ((typeConstraint == NULL) || (!typeConstraint->IsObject()))
  8450. {
  8451. 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",
  8452. genericParam->GetGenericParamDef()->mName.c_str()), dynCastExpr->mTypeRef);
  8453. return;
  8454. }
  8455. targetType = typeConstraint;
  8456. }
  8457. if ((!targetType->IsObjectOrInterface()) && (!targetType->IsNullable()))
  8458. {
  8459. mModule->Fail(StrFormat("The as operator must be used with a reference type or nullable type ('%s' is a non-nullable value type)",
  8460. mModule->TypeToString(origTargetType).c_str()), dynCastExpr->mTypeRef);
  8461. return;
  8462. }
  8463. if (targetValue.mType->IsGenericParam())
  8464. {
  8465. auto genericParamType = (BfGenericParamType*)targetValue.mType;
  8466. auto genericParam = mModule->GetGenericParamInstance(genericParamType);
  8467. auto typeConstraint = genericParam->mTypeConstraint;
  8468. if (typeConstraint == NULL)
  8469. typeConstraint = mModule->mContext->mBfObjectType;
  8470. if ((typeConstraint->IsDelegate()) && (typeConstraint == targetType))
  8471. {
  8472. // Delegate constraints may be matched by valueless method references, so this won't always match (don't warn)
  8473. mResult = mModule->GetDefaultTypedValue(targetType);
  8474. return;
  8475. }
  8476. targetValue = mModule->GetDefaultTypedValue(typeConstraint);
  8477. }
  8478. auto boolType = mModule->GetPrimitiveType(BfTypeCode_Boolean);
  8479. auto _CheckResult = [&]()
  8480. {
  8481. if ((mResult) && (origTargetType->IsGenericParam()))
  8482. mResult = mModule->GetDefaultTypedValue(origTargetType);
  8483. };
  8484. if ((targetValue.mType->IsNullable()) && (targetType->IsInterface()))
  8485. {
  8486. mResult = mModule->Cast(dynCastExpr, targetValue, targetType, BfCastFlags_SilentFail);
  8487. if (!mResult)
  8488. {
  8489. mModule->Warn(0, StrFormat("Conversion from '%s' to '%s' will always be null",
  8490. mModule->TypeToString(targetValue.mType).c_str(), mModule->TypeToString(origTargetType).c_str()), dynCastExpr->mAsToken);
  8491. mResult = BfTypedValue(mModule->GetDefaultValue(origTargetType), origTargetType);
  8492. }
  8493. _CheckResult();
  8494. return;
  8495. }
  8496. if (targetValue.mType->IsValueTypeOrValueTypePtr())
  8497. {
  8498. mModule->Warn(0, StrFormat("Type '%s' is not applicable for dynamic casting",
  8499. mModule->TypeToString(targetValue.mType).c_str()), dynCastExpr->mAsToken);
  8500. auto typeInstance = targetValue.mType->ToTypeInstance();
  8501. if (targetValue.mType->IsWrappableType())
  8502. typeInstance = mModule->GetWrappedStructType(targetValue.mType);
  8503. bool matches = (targetValue.mType == targetType) || (mModule->mContext->mBfObjectType == targetType);
  8504. if (targetType->IsNullable())
  8505. {
  8506. auto elementType = targetType->GetUnderlyingType();
  8507. if (elementType == targetValue.mType)
  8508. {
  8509. // We match nullable element
  8510. auto allocaInst = mModule->CreateAlloca(targetType);
  8511. auto hasValueAddr = mModule->mBfIRBuilder->CreateInBoundsGEP(allocaInst, 0, 1); // has_value
  8512. mModule->mBfIRBuilder->CreateStore(mModule->GetConstValue(1, boolType), hasValueAddr);
  8513. hasValueAddr = mModule->mBfIRBuilder->CreateInBoundsGEP(allocaInst, 0, 0); // value
  8514. mModule->mBfIRBuilder->CreateStore(targetValue.mValue, hasValueAddr);
  8515. mResult = BfTypedValue(allocaInst, targetType, true);
  8516. _CheckResult();
  8517. return;
  8518. }
  8519. }
  8520. if (!matches)
  8521. matches = mModule->TypeIsSubTypeOf(typeInstance, targetType->ToTypeInstance());
  8522. if (matches)
  8523. mResult = mModule->Cast(dynCastExpr, targetValue, targetType, BfCastFlags_Explicit);
  8524. else if (targetType->IsNullable())
  8525. {
  8526. auto allocaInst = mModule->CreateAlloca(targetType);
  8527. auto allocaBits = mModule->mBfIRBuilder->CreateBitCast(allocaInst, mModule->mBfIRBuilder->GetPrimitiveType(BfTypeCode_NullPtr));
  8528. mModule->mBfIRBuilder->CreateMemSet(allocaBits, mModule->GetConstValue(0, mModule->GetPrimitiveType(BfTypeCode_Int8)),
  8529. mModule->GetConstValue(targetType->mSize), targetType->mAlign);
  8530. mResult = BfTypedValue(allocaInst, targetType, true);
  8531. }
  8532. else
  8533. mResult = BfTypedValue(mModule->GetDefaultValue(targetType), targetType);
  8534. _CheckResult();
  8535. return;
  8536. }
  8537. if (targetType->IsNullable())
  8538. {
  8539. if (autoComplete != NULL)
  8540. {
  8541. mResult = mModule->GetDefaultTypedValue(targetType);
  8542. return;
  8543. }
  8544. auto elementType = targetType->GetUnderlyingType();
  8545. auto allocaInst = mModule->CreateAlloca(targetType);
  8546. auto hasValueAddr = mModule->mBfIRBuilder->CreateInBoundsGEP(allocaInst, 0, elementType->IsValuelessType() ? 1 : 2); // has_value
  8547. mModule->mBfIRBuilder->CreateStore(mModule->GetConstValue(0, boolType), hasValueAddr);
  8548. auto objectType = mModule->mContext->mBfObjectType;
  8549. auto prevBB = mModule->mBfIRBuilder->GetInsertBlock();
  8550. auto matchBB = mModule->mBfIRBuilder->CreateBlock("as.match");
  8551. auto endBB = mModule->mBfIRBuilder->CreateBlock("as.end");
  8552. mModule->EmitDynamicCastCheck(targetValue, elementType, matchBB, endBB);
  8553. BfBoxedType* boxedType = mModule->CreateBoxedType(elementType);
  8554. mModule->AddBasicBlock(matchBB);
  8555. if (elementType->IsValuelessType())
  8556. {
  8557. auto hasValueAddr = mModule->mBfIRBuilder->CreateInBoundsGEP(allocaInst, 0, 1); // has_value
  8558. mModule->mBfIRBuilder->CreateStore(mModule->GetConstValue(1, boolType), hasValueAddr);
  8559. }
  8560. else
  8561. {
  8562. auto hasValueAddr = mModule->mBfIRBuilder->CreateInBoundsGEP(allocaInst, 0, 2); // has_value
  8563. mModule->mBfIRBuilder->CreateStore(mModule->GetConstValue(1, boolType), hasValueAddr);
  8564. auto nullableValueAddr = mModule->mBfIRBuilder->CreateInBoundsGEP(allocaInst, 0, 1); // value
  8565. auto srcBoxedType = mModule->mBfIRBuilder->CreateBitCast(targetValue.mValue, mModule->mBfIRBuilder->MapType(boxedType, BfIRPopulateType_Full));
  8566. auto boxedValueAddr = mModule->mBfIRBuilder->CreateInBoundsGEP(srcBoxedType, 0, 1); // mValue
  8567. auto boxedValue = mModule->mBfIRBuilder->CreateLoad(boxedValueAddr);
  8568. mModule->mBfIRBuilder->CreateStore(boxedValue, nullableValueAddr);
  8569. }
  8570. mModule->mBfIRBuilder->CreateBr(endBB);
  8571. mModule->AddBasicBlock(endBB);
  8572. mResult = BfTypedValue(allocaInst, targetType, true);
  8573. _CheckResult();
  8574. return;
  8575. }
  8576. targetValue = mModule->LoadValue(targetValue);
  8577. if (targetType->IsValueType())
  8578. {
  8579. mModule->Fail("Invalid dynamic cast type", dynCastExpr->mTypeRef);
  8580. return;
  8581. }
  8582. BfTypeInstance* srcTypeInstance = targetValue.mType->ToTypeInstance();
  8583. BfTypeInstance* targetTypeInstance = targetType->ToTypeInstance();
  8584. if (mModule->TypeIsSubTypeOf(srcTypeInstance, targetTypeInstance))
  8585. {
  8586. // We don't give this warning when we have wasGenericParmType set because that indicates we had a generic type constraint,
  8587. // and a type constraint infers that the ACTUAL type used will be equal to or derived from that type and therefore
  8588. // it may be a "necessary cast" indeed
  8589. if ((!wasGenericParamType) && (mModule->mCurMethodState->mMixinState == NULL))
  8590. {
  8591. if (srcTypeInstance == targetType)
  8592. mModule->Warn(BfWarning_BF4203_UnnecessaryDynamicCast, StrFormat("Unnecessary cast, the value is already type '%s'",
  8593. mModule->TypeToString(srcTypeInstance).c_str()), dynCastExpr->mAsToken);
  8594. else
  8595. mModule->Warn(BfWarning_BF4203_UnnecessaryDynamicCast, StrFormat("Unnecessary cast, '%s' is a subtype of '%s'",
  8596. mModule->TypeToString(srcTypeInstance).c_str(), mModule->TypeToString(targetType).c_str()), dynCastExpr->mAsToken);
  8597. }
  8598. auto castedValue = mModule->mBfIRBuilder->CreateBitCast(targetValue.mValue, mModule->mBfIRBuilder->MapType(targetTypeInstance));
  8599. mResult = BfTypedValue(castedValue, targetTypeInstance);
  8600. _CheckResult();
  8601. return;
  8602. }
  8603. else if ((!targetType->IsInterface()) && (!mModule->TypeIsSubTypeOf(targetTypeInstance, srcTypeInstance)))
  8604. {
  8605. mModule->Fail(StrFormat("Cannot convert type '%s' to '%s' via any conversion",
  8606. mModule->TypeToString(targetValue.mType).c_str(), mModule->TypeToString(targetTypeInstance).c_str()), dynCastExpr->mAsToken);
  8607. }
  8608. if (autoComplete != NULL)
  8609. {
  8610. mResult = mModule->GetDefaultTypedValue(targetType);
  8611. _CheckResult();
  8612. return;
  8613. }
  8614. auto irb = mModule->mBfIRBuilder;
  8615. auto objectType = mModule->mContext->mBfObjectType;
  8616. mModule->PopulateType(objectType, BfPopulateType_Full);
  8617. auto prevBB = mModule->mBfIRBuilder->GetInsertBlock();
  8618. auto endBB = mModule->mBfIRBuilder->CreateBlock("as.end");
  8619. auto matchBlock = irb->CreateBlock("as.match");
  8620. BfIRValue targetVal = mModule->CreateAlloca(targetType);
  8621. irb->CreateStore(irb->CreateConstNull(irb->MapType(targetType)), targetVal);
  8622. mModule->EmitDynamicCastCheck(targetValue, targetType, matchBlock, endBB);
  8623. mModule->AddBasicBlock(matchBlock);
  8624. BfIRValue castedCallResult = mModule->mBfIRBuilder->CreateBitCast(targetValue.mValue, mModule->mBfIRBuilder->MapType(targetType));
  8625. irb->CreateStore(castedCallResult, targetVal);
  8626. irb->CreateBr(endBB);
  8627. mModule->AddBasicBlock(endBB);
  8628. mResult = BfTypedValue(irb->CreateLoad(targetVal), targetType);
  8629. _CheckResult();
  8630. }
  8631. void BfExprEvaluator::Visit(BfCastExpression* castExpr)
  8632. {
  8633. auto autoComplete = GetAutoComplete();
  8634. if ((autoComplete != NULL) && (castExpr->mTypeRef != NULL))
  8635. {
  8636. // 'mayBeIdentifier' because this may be a misidentified cast - it could be a parenthesized expression
  8637. autoComplete->CheckTypeRef(castExpr->mTypeRef, true, true);
  8638. }
  8639. BfType* resolvedType = NULL;
  8640. if ((BfNodeDynCastExact<BfDotTypeReference>(castExpr->mTypeRef) != NULL) && (mExpectingType != NULL))
  8641. {
  8642. //mModule->SetElementType(castExpr->mTypeRef, BfSourceElementType_TypeRef);
  8643. resolvedType = mExpectingType;
  8644. }
  8645. else
  8646. resolvedType = ResolveTypeRef(castExpr->mTypeRef);
  8647. if (resolvedType != NULL)
  8648. mModule->AddDependency(resolvedType, mModule->mCurTypeInstance, BfDependencyMap::DependencyFlag_LocalUsage);
  8649. // If resolvedType is NULL then that's okay- we just leave the following expression uncasted
  8650. if (castExpr->mExpression == NULL)
  8651. {
  8652. mModule->AssertErrorState();
  8653. return;
  8654. }
  8655. auto exprFlags = (BfEvalExprFlags)((mBfEvalExprFlags & BfEvalExprFlags_NoAutoComplete) | BfEvalExprFlags_ExplicitCast);
  8656. mResult = mModule->CreateValueFromExpression(castExpr->mExpression, resolvedType, exprFlags);
  8657. }
  8658. bool BfExprEvaluator::IsExactMethodMatch(BfMethodInstance* methodA, BfMethodInstance* methodB, bool ignoreImplicitParams)
  8659. {
  8660. if (methodA->mReturnType != methodB->mReturnType)
  8661. return false;
  8662. int implicitParamCountA = methodA->GetImplicitParamCount();
  8663. if (methodA->HasExplicitThis())
  8664. implicitParamCountA++;
  8665. int implicitParamCountB = methodB->GetImplicitParamCount();
  8666. if (methodB->HasExplicitThis())
  8667. implicitParamCountB++;
  8668. if (methodA->GetParamCount() - implicitParamCountA != methodB->GetParamCount() - implicitParamCountB)
  8669. return false;
  8670. for (int i = 0; i < (int)methodA->GetParamCount() - implicitParamCountA; i++)
  8671. {
  8672. auto paramA = methodA->GetParamType(i + implicitParamCountA);
  8673. auto paramB = methodB->GetParamType(i + implicitParamCountB);
  8674. if (paramA != paramB)
  8675. return false;
  8676. }
  8677. return true;
  8678. }
  8679. void BfExprEvaluator::ConstResolve(BfExpression* expr)
  8680. {
  8681. BfConstResolver constResolver(mModule);
  8682. constResolver.Resolve(expr);
  8683. mResult = constResolver.mResult;
  8684. }
  8685. BfTypeInstance* BfExprEvaluator::VerifyBaseDelegateType(BfTypeInstance* baseDelegateType)
  8686. {
  8687. mModule->PopulateType(baseDelegateType, BfPopulateType_DataAndMethods);
  8688. if (baseDelegateType->mFieldInstances.size() != 2)
  8689. {
  8690. mModule->AssertErrorState();
  8691. return NULL;
  8692. }
  8693. return baseDelegateType;
  8694. }
  8695. bool BfExprEvaluator::CanBindDelegate(BfDelegateBindExpression* delegateBindExpr, BfMethodInstance** boundMethod, BfType* origMethodExpectingType, BfTypeVector* methodGenericArgumentsSubstitute)
  8696. {
  8697. if ((mExpectingType == NULL) && (origMethodExpectingType == NULL))
  8698. {
  8699. return false;
  8700. }
  8701. bool isGenericMatch = mExpectingType == NULL;
  8702. auto expectingType = mExpectingType;
  8703. if (expectingType == NULL)
  8704. expectingType = origMethodExpectingType;
  8705. auto typeInstance = expectingType->ToTypeInstance();
  8706. if ((typeInstance == NULL) ||
  8707. ((!typeInstance->mTypeDef->mIsDelegate) && (!typeInstance->mTypeDef->mIsFunction)))
  8708. return false;
  8709. mModule->PopulateType(typeInstance, BfPopulateType_DataAndMethods);
  8710. auto methodInstance = mModule->GetRawMethodInstanceAtIdx(typeInstance, 0, "Invoke");
  8711. if (methodInstance == NULL)
  8712. {
  8713. BF_DBG_FATAL("Invoke not found");
  8714. return false;
  8715. }
  8716. if (delegateBindExpr->mTarget == NULL)
  8717. return false;
  8718. BfAutoParentNodeEntry autoParentNodeEntry(mModule, delegateBindExpr);
  8719. SizedArray<BfTypedValueExpression, 4> typedValueExprs;
  8720. typedValueExprs.resize(methodInstance->GetParamCount());
  8721. SizedArray<BfExpression*, 4> args;
  8722. args.resize(methodInstance->GetParamCount());
  8723. auto _FixType = [&](BfType* type)
  8724. {
  8725. if (!isGenericMatch)
  8726. return type;
  8727. auto fixedType = mModule->ResolveGenericType(type, NULL, methodGenericArgumentsSubstitute);
  8728. if (fixedType != NULL)
  8729. return fixedType;
  8730. return (BfType*)mModule->GetPrimitiveType(BfTypeCode_Var);
  8731. };
  8732. auto _TypeMatches = [&](BfType* lhs, BfType* rhs)
  8733. {
  8734. if (lhs == rhs)
  8735. return true;
  8736. return lhs->IsVar();
  8737. };
  8738. for (int i = 0; i < (int) methodInstance->GetParamCount(); i++)
  8739. {
  8740. auto typedValueExpr = &typedValueExprs[i];
  8741. typedValueExpr->mTypedValue.mValue = BfIRValue(BfIRValueFlags_Value, -1);
  8742. typedValueExpr->mTypedValue.mType = _FixType(methodInstance->GetParamType(i));
  8743. typedValueExpr->mRefNode = NULL;
  8744. args[i] = typedValueExpr;
  8745. }
  8746. BfSizedArray<ASTREF(BfTypeReference*)>* methodGenericArguments = NULL;
  8747. if (delegateBindExpr->mGenericArgs != NULL)
  8748. methodGenericArguments = &delegateBindExpr->mGenericArgs->mGenericArgs;
  8749. BfFunctionBindResult bindResult;
  8750. bindResult.mSkipMutCheck = true; // Allow operating on copies
  8751. bindResult.mBindType = expectingType;
  8752. mFunctionBindResult = &bindResult;
  8753. SetAndRestoreValue<bool> ignoreError(mModule->mIgnoreErrors, true);
  8754. DoInvocation(delegateBindExpr->mTarget, delegateBindExpr, args, methodGenericArguments);
  8755. mFunctionBindResult = NULL;
  8756. if (bindResult.mMethodInstance == NULL)
  8757. return false;
  8758. if (boundMethod != NULL)
  8759. *boundMethod = bindResult.mMethodInstance;
  8760. auto matchedMethod = bindResult.mMethodInstance;
  8761. if (!_TypeMatches(_FixType(methodInstance->mReturnType), matchedMethod->mReturnType))
  8762. return false;
  8763. int implicitParamCountA = methodInstance->GetImplicitParamCount();
  8764. int implicitParamCountB = matchedMethod->GetImplicitParamCount();
  8765. if (methodInstance->GetParamCount() - implicitParamCountA != matchedMethod->GetParamCount() - implicitParamCountB)
  8766. return false;
  8767. for (int i = 0; i < (int)methodInstance->GetParamCount() - implicitParamCountA; i++)
  8768. {
  8769. auto paramA = _FixType(methodInstance->GetParamType(i + implicitParamCountA));
  8770. auto paramB = _FixType(matchedMethod->GetParamType(i + implicitParamCountB));
  8771. if (!_TypeMatches(paramA, paramB))
  8772. return false;
  8773. }
  8774. return true;
  8775. }
  8776. BfTypedValue BfExprEvaluator::DoImplicitArgCapture(BfAstNode* refNode, BfIdentifierNode* identifierNode, int shadowIdx)
  8777. {
  8778. String findName = identifierNode->ToString();
  8779. if (mModule->mCurMethodState != NULL)
  8780. {
  8781. auto rootMethodState = mModule->mCurMethodState->GetRootMethodState();
  8782. auto checkMethodState = mModule->mCurMethodState;
  8783. bool isMixinOuterVariablePass = false;
  8784. int shadowSkip = shadowIdx;
  8785. while (checkMethodState != NULL)
  8786. {
  8787. BP_ZONE("LookupIdentifier:DoImplicitArgCapture");
  8788. BfTypeInstance* closureTypeInst = NULL;
  8789. BfClosureInstanceInfo* closureInstanceInfo = NULL;
  8790. if ((checkMethodState->mClosureState != NULL) && (checkMethodState->mClosureState->mClosureType != NULL) && (!checkMethodState->mClosureState->mCapturing))
  8791. {
  8792. closureTypeInst = mModule->mCurMethodState->mClosureState->mClosureType;
  8793. }
  8794. BfLocalVarEntry* entry;
  8795. if (checkMethodState->mLocalVarSet.TryGetWith<StringImpl&>(findName, &entry))
  8796. {
  8797. auto varDecl = entry->mLocalVar;
  8798. while (varDecl != NULL)
  8799. {
  8800. if (varDecl->mNameNode == identifierNode)
  8801. {
  8802. if (shadowSkip > 0)
  8803. {
  8804. shadowSkip--;
  8805. }
  8806. else
  8807. {
  8808. BfTypedValue localResult = LoadLocal(varDecl);
  8809. if (!isMixinOuterVariablePass)
  8810. {
  8811. mResultLocalVar = varDecl;
  8812. mResultFieldInstance = NULL;
  8813. mResultLocalVarRefNode = identifierNode;
  8814. }
  8815. return localResult;
  8816. }
  8817. }
  8818. varDecl = varDecl->mShadowedLocal;
  8819. }
  8820. }
  8821. // Check for the captured locals. It's important we do it here so we get local-first precedence still
  8822. if (closureTypeInst != NULL)
  8823. {
  8824. closureTypeInst->mTypeDef->PopulateMemberSets();
  8825. BfMemberSetEntry* memberSetEntry = NULL;
  8826. if (closureTypeInst->mTypeDef->mFieldSet.TryGetWith(findName, &memberSetEntry))
  8827. {
  8828. auto fieldDef = (BfFieldDef*)memberSetEntry->mMemberDef;
  8829. while (fieldDef != NULL)
  8830. {
  8831. BfIdentifierNode* fieldNameNode = NULL;
  8832. if (fieldDef->mIdx < (int)checkMethodState->mClosureState->mClosureInstanceInfo->mCaptureEntries.size())
  8833. fieldNameNode = checkMethodState->mClosureState->mClosureInstanceInfo->mCaptureEntries[fieldDef->mIdx].mNameNode;
  8834. if (fieldNameNode == identifierNode)
  8835. {
  8836. auto& field = closureTypeInst->mFieldInstances[fieldDef->mIdx];
  8837. if (!field.mResolvedType->IsValuelessType())
  8838. {
  8839. if (mModule->mCurMethodState->mClosureState->mCapturing)
  8840. {
  8841. mModule->mCurMethodState->mClosureState->mReferencedOuterClosureMembers.Add(&field);
  8842. return mModule->GetDefaultTypedValue(field.mResolvedType);
  8843. }
  8844. auto localVar = mModule->mCurMethodState->mLocals[0];
  8845. auto thisValue = localVar->mValue;
  8846. mModule->mBfIRBuilder->PopulateType(localVar->mResolvedType);
  8847. BfTypedValue result = BfTypedValue(mModule->mBfIRBuilder->CreateInBoundsGEP(thisValue, 0, field.mDataIdx), field.mResolvedType, true);
  8848. if (field.mResolvedType->IsRef())
  8849. {
  8850. auto refType = (BfRefType*)field.mResolvedType;
  8851. auto underlyingType = refType->GetUnderlyingType();
  8852. result = BfTypedValue(mModule->mBfIRBuilder->CreateLoad(result.mValue), underlyingType, true);
  8853. }
  8854. else if (fieldDef->mIsReadOnly)
  8855. result = mModule->LoadValue(result);
  8856. mResultLocalVar = localVar;
  8857. mResultFieldInstance = &field;
  8858. mResultLocalVarField = -(field.mMergedDataIdx + 1);
  8859. return result;
  8860. }
  8861. }
  8862. fieldDef = fieldDef->mNextWithSameName;
  8863. }
  8864. }
  8865. }
  8866. if ((checkMethodState->mClosureState != NULL) && (checkMethodState->mClosureState->mCapturing) /*&& (checkMethodState->mClosureState->mIsLocalMethod)*/)
  8867. {
  8868. checkMethodState = checkMethodState->mPrevMethodState;
  8869. continue;
  8870. }
  8871. // Allow local mixin to see outside variables during its processing -- since we don't actually "capture" those into params
  8872. bool isLocalMixinProcessing = false;
  8873. if ((checkMethodState->mClosureState != NULL) && (!checkMethodState->mClosureState->mCapturing) && (closureTypeInst == NULL) &&
  8874. (mModule->mCurMethodInstance->mMethodDef->mMethodType == BfMethodType_Mixin))
  8875. isLocalMixinProcessing = true;
  8876. if (!isLocalMixinProcessing)
  8877. break;
  8878. isMixinOuterVariablePass = true;
  8879. checkMethodState = checkMethodState->mPrevMethodState;
  8880. }
  8881. }
  8882. return BfTypedValue();
  8883. }
  8884. BfTypedValue BfExprEvaluator::DoImplicitArgCapture(BfAstNode* refNode, BfMethodInstance* methodInstance, int paramIdx, bool& failed, BfImplicitParamKind paramKind, const BfTypedValue& methodRefTarget)
  8885. {
  8886. if ((methodRefTarget) && (methodRefTarget.mValue.mId != BfIRValue::ID_IMPLICIT))
  8887. {
  8888. if (methodRefTarget.mType->IsMethodRef())
  8889. {
  8890. BfMethodRefType* methodRefType = (BfMethodRefType*)methodRefTarget.mType;
  8891. BfMethodInstance* methodRefMethodInst = methodRefType->mMethodRef;
  8892. BF_ASSERT(methodRefMethodInst == methodInstance);
  8893. auto paramType = methodInstance->GetParamType(paramIdx);
  8894. int dataIdx = methodRefType->GetDataIdxFromParamIdx(paramIdx);
  8895. if (dataIdx == -1)
  8896. {
  8897. BF_ASSERT(paramType->IsValuelessType());
  8898. return BfTypedValue(mModule->mBfIRBuilder->GetFakeVal(), paramType);
  8899. }
  8900. if (methodRefTarget.IsSplat())
  8901. {
  8902. if (methodRefType->WantsDataPassedAsSplat(dataIdx))
  8903. {
  8904. BF_ASSERT(paramIdx == -1);
  8905. return BfTypedValue(methodRefTarget.mValue, paramType, BfTypedValueKind_SplatHead);
  8906. }
  8907. else
  8908. {
  8909. int splatIdx = dataIdx;
  8910. if (dataIdx > 0)
  8911. {
  8912. if (methodRefType->WantsDataPassedAsSplat(0))
  8913. splatIdx += methodRefType->GetCaptureType(0)->GetSplatCount() - 1;
  8914. }
  8915. bool isAddr = false;
  8916. BfIRValue value = mModule->ExtractSplatValue(methodRefTarget, splatIdx, paramType, &isAddr);
  8917. // We moved the composite load from ExtractSplatValue to here. Hopefully this is correct.
  8918. // 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)
  8919. // if ((paramType->IsComposite()) && (mModule->IsTargetingBeefBackend()))
  8920. // value = mModule->mBfIRBuilder->CreateLoad(value);
  8921. auto lookupVal = BfTypedValue(value, paramType, isAddr);
  8922. if ((isAddr) && (!lookupVal.mType->IsComposite()))
  8923. lookupVal = mModule->LoadValue(lookupVal);
  8924. return lookupVal;
  8925. }
  8926. }
  8927. BF_ASSERT(methodRefTarget.IsAddr());
  8928. if (paramType->IsComposite())
  8929. return BfTypedValue(mModule->mBfIRBuilder->CreateInBoundsGEP(methodRefTarget.mValue, 0, dataIdx), paramType, true);
  8930. return BfTypedValue(mModule->ExtractValue(methodRefTarget, dataIdx), paramType);
  8931. }
  8932. }
  8933. // 'Default' implicit arg lookup, by identifier. May match field (for lambda), or local variable
  8934. if (paramKind == BfImplicitParamKind_General)
  8935. {
  8936. if (paramIdx == -1)
  8937. {
  8938. if (auto delegateBindExpr = BfNodeDynCast<BfDelegateBindExpression>(refNode))
  8939. {
  8940. BfAstNode* thisNode = NULL;
  8941. BfTypedValue thisValue;
  8942. if (auto memberReferenceExpr = BfNodeDynCast<BfMemberReferenceExpression>(delegateBindExpr->mTarget))
  8943. thisNode = memberReferenceExpr->mTarget;
  8944. else if (auto qualifiedNameNode = BfNodeDynCast<BfQualifiedNameNode>(delegateBindExpr->mTarget))
  8945. thisNode = qualifiedNameNode->mLeft;
  8946. else if (auto identifierNode = BfNodeDynCast<BfIdentifierNode>(delegateBindExpr->mTarget))
  8947. {
  8948. // Implicit
  8949. thisValue = mModule->GetThis();
  8950. }
  8951. if (auto thisExpr = BfNodeDynCast<BfExpression>(thisNode))
  8952. {
  8953. thisValue = mModule->CreateValueFromExpression(thisExpr);
  8954. if (!thisValue)
  8955. return BfTypedValue();
  8956. }
  8957. if (thisValue)
  8958. {
  8959. //TODO: handle 'mut', throw error if trying to capture from a non-mut, etc...
  8960. return thisValue;
  8961. }
  8962. }
  8963. }
  8964. String captureName = methodInstance->GetParamName(paramIdx);
  8965. BfIdentifierNode* identifierNode = methodInstance->GetParamNameNode(paramIdx);
  8966. BfTypedValue lookupVal;
  8967. if (identifierNode != NULL)
  8968. {
  8969. lookupVal = DoImplicitArgCapture(refNode, identifierNode, 0);
  8970. }
  8971. else
  8972. {
  8973. lookupVal = LookupIdentifier(NULL, captureName);
  8974. }
  8975. if (lookupVal)
  8976. {
  8977. auto paramType = methodInstance->GetParamType(paramIdx);
  8978. if (paramType->IsRef())
  8979. {
  8980. auto refType = (BfRefType*)paramType;
  8981. if (mResultLocalVar != NULL)
  8982. {
  8983. // When we are capturing, we need to note that we require capturing by reference here
  8984. auto localVar = mResultLocalVar;
  8985. localVar->mWrittenToId = mModule->mCurMethodState->GetRootMethodState()->mCurAccessId++;
  8986. }
  8987. bool isValid = false;
  8988. if ((refType->mRefKind == BfRefType::RefKind_Mut) && (lookupVal.mKind == BfTypedValueKind_MutableValue))
  8989. isValid = true;
  8990. if ((lookupVal.mType->IsRef()) || (lookupVal.IsAddr()))
  8991. isValid = true;
  8992. if (!isValid)
  8993. {
  8994. // Is there another way this can fail than to be in a lambda?
  8995. auto error = mModule->Fail(StrFormat("Method '%s' requires that '%s' be captured by reference. Consider adding by-reference capture specifier [&] to lambda.",
  8996. mModule->MethodToString(methodInstance).c_str(), captureName.c_str()), refNode, true);
  8997. if ((error != NULL) && (methodInstance->mMethodDef->mMethodDeclaration != NULL))
  8998. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("See method declaration"), methodInstance->mMethodDef->GetRefNode());
  8999. failed = true;
  9000. }
  9001. }
  9002. else
  9003. {
  9004. if (lookupVal.mType->IsRef())
  9005. lookupVal = mModule->RemoveRef(lookupVal);
  9006. if (!lookupVal.mType->IsComposite())
  9007. lookupVal = mModule->LoadValue(lookupVal);
  9008. }
  9009. return lookupVal;
  9010. }
  9011. else
  9012. {
  9013. mModule->Fail(StrFormat("Failed to lookup implicit capture '%s'", captureName.c_str()), refNode, true);
  9014. failed = true;
  9015. return BfTypedValue();
  9016. }
  9017. }
  9018. return BfTypedValue();
  9019. }
  9020. void BfExprEvaluator::Visit(BfDelegateBindExpression* delegateBindExpr)
  9021. {
  9022. BfAutoParentNodeEntry autoParentNodeEntry(mModule, delegateBindExpr);
  9023. if (mExpectingType == NULL)
  9024. {
  9025. mModule->Fail("Cannot infer delegate type", delegateBindExpr);
  9026. return;
  9027. }
  9028. BfTokenNode* newToken = NULL;
  9029. BfAllocTarget allocTarget = ResolveAllocTarget(delegateBindExpr->mNewToken, newToken);
  9030. SizedArray<BfTypedValueExpression, 4> typedValueExprs;
  9031. SizedArray<BfExpression*, 4> args;
  9032. BfTypeInstance* delegateTypeInstance = NULL;
  9033. BfMethodInstance* methodInstance = NULL;
  9034. const char* bindTypeName = NULL;
  9035. bool isMethodRefMatch = false;
  9036. if (mExpectingType->IsMethodRef())
  9037. {
  9038. auto methodRefType = (BfMethodRefType*)mExpectingType;
  9039. BF_ASSERT(delegateBindExpr->mNewToken == NULL);
  9040. methodInstance = methodRefType->mMethodRef;
  9041. isMethodRefMatch = true;
  9042. }
  9043. else
  9044. {
  9045. if (mExpectingType->IsGenericParam())
  9046. {
  9047. auto genericParamInstance = mModule->GetGenericParamInstance((BfGenericParamType*)mExpectingType);
  9048. if ((genericParamInstance->mTypeConstraint != NULL) && (genericParamInstance->mTypeConstraint->IsDelegate()))
  9049. {
  9050. delegateTypeInstance = genericParamInstance->mTypeConstraint->ToTypeInstance();
  9051. }
  9052. }
  9053. else
  9054. delegateTypeInstance = mExpectingType->ToTypeInstance();
  9055. if ((delegateTypeInstance == NULL) ||
  9056. ((!delegateTypeInstance->IsDelegate()) && (!delegateTypeInstance->IsFunction())))
  9057. {
  9058. mModule->Fail(StrFormat("Type '%s' cannot be used for method binding. Only delegate or function types are allowed.", mModule->TypeToString(mExpectingType).c_str()), delegateBindExpr);
  9059. return;
  9060. }
  9061. bindTypeName = (delegateTypeInstance->IsDelegate()) ? "delegate" : "function";
  9062. mModule->PopulateType(delegateTypeInstance, BfPopulateType_DataAndMethods);
  9063. methodInstance = mModule->GetRawMethodInstanceAtIdx(delegateTypeInstance, 0, "Invoke");
  9064. if (methodInstance == NULL)
  9065. {
  9066. BF_DBG_FATAL("Invoke not found");
  9067. return;
  9068. }
  9069. if (auto tokenNode = BfNodeDynCast<BfTokenNode>(delegateBindExpr->mNewToken))
  9070. {
  9071. if (delegateTypeInstance->IsFunction())
  9072. mModule->Fail("Function bindings are direct assignments, allocation specifier is not applicable", delegateBindExpr->mNewToken);
  9073. else if (tokenNode->GetToken() == BfToken_Append)
  9074. {
  9075. mModule->Fail("Append allocation on delegate bind not supported", delegateBindExpr->mNewToken);
  9076. }
  9077. }
  9078. }
  9079. int paramOffset = methodInstance->HasExplicitThis() ? 1 : 0;
  9080. typedValueExprs.resize(methodInstance->GetParamCount() - paramOffset);
  9081. args.resize(methodInstance->GetParamCount() - paramOffset);
  9082. for (int i = 0; i < (int)methodInstance->GetParamCount() - paramOffset; i++)
  9083. {
  9084. auto typedValueExpr = &typedValueExprs[i];
  9085. typedValueExpr->mTypedValue.mValue = BfIRValue(BfIRValueFlags_Value, -1);
  9086. typedValueExpr->mTypedValue.mType = methodInstance->GetParamType(i + paramOffset);
  9087. typedValueExpr->mRefNode = NULL;
  9088. args[i] = typedValueExpr;
  9089. }
  9090. BfSizedArray<ASTREF(BfTypeReference*)>* methodGenericArguments = NULL;
  9091. if (delegateBindExpr->mGenericArgs != NULL)
  9092. methodGenericArguments = &delegateBindExpr->mGenericArgs->mGenericArgs;
  9093. if (delegateBindExpr->mTarget == NULL)
  9094. {
  9095. mModule->AssertErrorState();
  9096. return;
  9097. }
  9098. auto autoComplete = GetAutoComplete();
  9099. if (autoComplete != NULL)
  9100. {
  9101. SetAndRestoreValue<bool> prevForceAllowNonStatic(autoComplete->mForceAllowNonStatic, methodInstance->mMethodDef->mHasExplicitThis);
  9102. GetAutoComplete()->CheckNode(delegateBindExpr->mTarget);
  9103. }
  9104. if ((!delegateBindExpr->mTarget->IsA<BfIdentifierNode>()) &&
  9105. (!delegateBindExpr->mTarget->IsA<BfMemberReferenceExpression>()))
  9106. {
  9107. mModule->Fail(StrFormat("Invalid %s binding target, %s can only bind to method references. Consider wrapping expression in a lambda.", bindTypeName, bindTypeName), delegateBindExpr->mTarget);
  9108. mModule->CreateValueFromExpression(delegateBindExpr->mTarget);
  9109. return;
  9110. }
  9111. BfFunctionBindResult bindResult;
  9112. bindResult.mSkipMutCheck = true; // Allow operating on copies
  9113. bindResult.mBindType = delegateTypeInstance;
  9114. //
  9115. {
  9116. SetAndRestoreValue<BfType*> prevExpectingType(mExpectingType, methodInstance->mReturnType);
  9117. mFunctionBindResult = &bindResult;
  9118. DoInvocation(delegateBindExpr->mTarget, delegateBindExpr, args, methodGenericArguments);
  9119. mFunctionBindResult = NULL;
  9120. }
  9121. SetMethodElementType(delegateBindExpr->mTarget);
  9122. if (bindResult.mMethodInstance == NULL)
  9123. {
  9124. mResult = BfTypedValue();
  9125. return;
  9126. }
  9127. auto bindMethodInstance = bindResult.mMethodInstance;
  9128. if (isMethodRefMatch)
  9129. {
  9130. // WTF- this was always false, what was it supposed to catch?
  9131. // if (bindMethodInstance != bindResult.mMethodInstance)
  9132. // {
  9133. // mResult = BfTypedValue();
  9134. // return;
  9135. // }
  9136. }
  9137. else
  9138. {
  9139. if (!IsExactMethodMatch(methodInstance, bindMethodInstance, true))
  9140. {
  9141. if (bindResult.mCheckedMultipleMethods)
  9142. {
  9143. mModule->Fail(StrFormat("No overload for '%s' matches %s '%s'", bindMethodInstance->mMethodDef->mName.c_str(), bindTypeName,
  9144. mModule->TypeToString(delegateTypeInstance).c_str()), delegateBindExpr->mTarget);
  9145. }
  9146. else
  9147. {
  9148. mModule->Fail(StrFormat("Method '%s' does not match %s '%s'", mModule->MethodToString(bindMethodInstance).c_str(), bindTypeName,
  9149. mModule->TypeToString(delegateTypeInstance).c_str()), delegateBindExpr->mTarget);
  9150. }
  9151. mResult = BfTypedValue();
  9152. return;
  9153. }
  9154. }
  9155. bool isDirectFunction = false;
  9156. if ((bindResult.mMethodInstance->GetOwner()->IsFunction()) && (bindResult.mFunc))
  9157. isDirectFunction = true;
  9158. if (bindMethodInstance->mIsIntrinsic)
  9159. {
  9160. 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);
  9161. mResult = BfTypedValue();
  9162. return;
  9163. }
  9164. bool hasIncompatibleCallingConventions = !mModule->mSystem->IsCompatibleCallingConvention(methodInstance->mCallingConvention, bindMethodInstance->mCallingConvention);
  9165. auto _GetInvokeMethodName = [&]()
  9166. {
  9167. String methodName = "Invoke$";
  9168. methodName += mModule->mCurMethodInstance->mMethodDef->mName;
  9169. int prevSepPos = (int)methodName.LastIndexOf('$');
  9170. if (prevSepPos > 6)
  9171. {
  9172. methodName.RemoveToEnd(prevSepPos);
  9173. }
  9174. auto rootMethodState = mModule->mCurMethodState->GetRootMethodState();
  9175. HashContext hashCtx;
  9176. if (mModule->mCurMethodInstance->mMethodDef->mDeclaringType->mPartialIdx != -1)
  9177. hashCtx.Mixin(mModule->mCurMethodInstance->mMethodDef->mDeclaringType->mPartialIdx);
  9178. if (delegateBindExpr->mFatArrowToken != NULL)
  9179. {
  9180. hashCtx.Mixin(delegateBindExpr->mFatArrowToken->GetStartCharId());
  9181. }
  9182. if (rootMethodState->mMethodInstance->mMethodInfoEx != NULL)
  9183. {
  9184. for (auto methodGenericArg : rootMethodState->mMethodInstance->mMethodInfoEx->mMethodGenericArguments)
  9185. {
  9186. StringT<128> genericTypeName;
  9187. BfMangler::Mangle(genericTypeName, mModule->mCompiler->GetMangleKind(), methodGenericArg);
  9188. hashCtx.MixinStr(genericTypeName);
  9189. }
  9190. }
  9191. Val128 hashVal = hashCtx.Finish128();
  9192. methodName += '$';
  9193. methodName += BfTypeUtils::HashEncode64(hashVal.mLow);
  9194. String mangledName;
  9195. BfMangler::MangleMethodName(mangledName, mModule->mCompiler->GetMangleKind(), mModule->mCurTypeInstance, methodName);
  9196. return mangledName;
  9197. };
  9198. if ((delegateBindExpr->mNewToken == NULL) || (delegateTypeInstance->IsFunction()))
  9199. {
  9200. if ((mModule->mCurMethodState != NULL) && (mModule->mCurMethodState->mHotDataReferenceBuilder != NULL))
  9201. {
  9202. BF_ASSERT(bindResult.mMethodInstance->mHotMethod != NULL);
  9203. mModule->mCurMethodState->mHotDataReferenceBuilder->mFunctionPtrs.Add(bindResult.mMethodInstance->mHotMethod);
  9204. }
  9205. if (isDirectFunction)
  9206. {
  9207. //if ((delegateTypeInstance != NULL) && (delegateTypeInstance->IsFunction()))
  9208. if (mExpectingType->IsFunction())
  9209. {
  9210. auto intPtrVal = mModule->mBfIRBuilder->CreatePtrToInt(bindResult.mFunc, BfTypeCode_IntPtr);
  9211. mResult = BfTypedValue(intPtrVal, mExpectingType);
  9212. return;
  9213. }
  9214. }
  9215. if (mExpectingType->IsFunction())
  9216. {
  9217. BfIRValue result;
  9218. if ((hasIncompatibleCallingConventions) && (mModule->HasCompiledOutput()))
  9219. {
  9220. //
  9221. {
  9222. SetAndRestoreValue<bool> prevIgnore(mModule->mBfIRBuilder->mIgnoreWrites, true);
  9223. result = mModule->CastToFunction(delegateBindExpr->mTarget, bindResult.mOrigTarget, bindResult.mMethodInstance, mExpectingType);
  9224. }
  9225. if (result)
  9226. {
  9227. String methodName = _GetInvokeMethodName();
  9228. SizedArray<BfIRType, 8> irParamTypes;
  9229. BfIRType irReturnType;
  9230. bindMethodInstance->GetIRFunctionInfo(mModule, irReturnType, irParamTypes);
  9231. auto prevActiveFunction = mModule->mBfIRBuilder->GetActiveFunction();
  9232. auto prevInsertBlock = mModule->mBfIRBuilder->GetInsertBlock();
  9233. mModule->mBfIRBuilder->SaveDebugLocation();
  9234. auto funcType = mModule->mBfIRBuilder->CreateFunctionType(irReturnType, irParamTypes);
  9235. auto funcValue = mModule->mBfIRBuilder->CreateFunction(funcType, BfIRLinkageType_External, methodName);
  9236. auto srcCallingConv = mModule->GetIRCallingConvention(methodInstance);
  9237. mModule->mBfIRBuilder->SetFuncCallingConv(funcValue, srcCallingConv);
  9238. mModule->mBfIRBuilder->SetActiveFunction(funcValue);
  9239. auto entryBlock = mModule->mBfIRBuilder->CreateBlock("entry", true);
  9240. mModule->mBfIRBuilder->SetInsertPoint(entryBlock);
  9241. SizedArray<BfIRValue, 8> irArgs;
  9242. for (int paramIdx = 0; paramIdx < irParamTypes.size(); paramIdx++)
  9243. {
  9244. irArgs.push_back(mModule->mBfIRBuilder->GetArgument(paramIdx));
  9245. }
  9246. auto bindFuncVal = bindResult.mFunc;
  9247. if (mModule->mCompiler->mOptions.mAllowHotSwapping)
  9248. bindFuncVal = mModule->mBfIRBuilder->RemapBindFunction(bindFuncVal);
  9249. auto callResult = mModule->mBfIRBuilder->CreateCall(bindFuncVal, irArgs);
  9250. auto destCallingConv = mModule->GetIRCallingConvention(bindMethodInstance);
  9251. if (destCallingConv != BfIRCallingConv_CDecl)
  9252. mModule->mBfIRBuilder->SetCallCallingConv(callResult, destCallingConv);
  9253. if (methodInstance->mReturnType->IsValuelessType())
  9254. mModule->mBfIRBuilder->CreateRetVoid();
  9255. else
  9256. mModule->mBfIRBuilder->CreateRet(callResult);
  9257. mModule->mBfIRBuilder->SetActiveFunction(prevActiveFunction);
  9258. mModule->mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  9259. mModule->mBfIRBuilder->RestoreDebugLocation();
  9260. result = mModule->mBfIRBuilder->CreatePtrToInt(funcValue, BfTypeCode_IntPtr);
  9261. }
  9262. }
  9263. else
  9264. {
  9265. result = mModule->CastToFunction(delegateBindExpr->mTarget, bindResult.mOrigTarget, bindResult.mMethodInstance, mExpectingType);
  9266. }
  9267. if (result)
  9268. mResult = BfTypedValue(result, mExpectingType);
  9269. return;
  9270. }
  9271. if (bindResult.mMethodInstance->mDisallowCalling)
  9272. {
  9273. BF_ASSERT(mModule->mBfIRBuilder->mIgnoreWrites);
  9274. mResult = mModule->GetDefaultTypedValue(mExpectingType, false, BfDefaultValueKind_Addr);
  9275. return;
  9276. }
  9277. auto methodRefType = mModule->CreateMethodRefType(bindResult.mMethodInstance);
  9278. mModule->AddDependency(methodRefType, mModule->mCurTypeInstance, BfDependencyMap::DependencyFlag_Calls);
  9279. mModule->AddCallDependency(bindResult.mMethodInstance);
  9280. if ((bindResult.mOrigTarget) && (bindResult.mOrigTarget.mType->IsMethodRef()))
  9281. {
  9282. mResult = bindResult.mOrigTarget;
  9283. }
  9284. else
  9285. {
  9286. if ((bindResult.mMethodInstance->mMethodDef->mIsLocalMethod) || (!bindResult.mTarget))
  9287. mResult = BfTypedValue(BfIRValue(BfIRValueFlags_Value, BfIRValue::ID_IMPLICIT), methodRefType);
  9288. else
  9289. {
  9290. auto methodRefPtr = mModule->CreateAlloca(methodRefType, "bindResult");
  9291. auto elemPtr = mModule->mBfIRBuilder->CreateInBoundsGEP(methodRefPtr, 0, 0);
  9292. BfTypedValue target;
  9293. if (bindResult.mTarget.IsSplat())
  9294. target = mModule->AggregateSplat(bindResult.mTarget, &bindResult.mIRArgs[0]);
  9295. else
  9296. target = mModule->LoadValue(bindResult.mTarget);
  9297. mModule->mBfIRBuilder->CreateStore(target.mValue, elemPtr);
  9298. mResult = BfTypedValue(methodRefPtr, methodRefType, true);
  9299. }
  9300. }
  9301. return;
  9302. }
  9303. int implicitParamCount = bindMethodInstance->GetImplicitParamCount();
  9304. BfTypeInstance* useTypeInstance = delegateTypeInstance;
  9305. BfClosureType* closureTypeInst = NULL;
  9306. auto origTarget = bindResult.mOrigTarget;
  9307. auto target = bindResult.mTarget;
  9308. BfTypedValue methodRefTarget;
  9309. if ((bindResult.mOrigTarget) && (bindResult.mOrigTarget.mType->IsMethodRef()))
  9310. methodRefTarget = bindResult.mOrigTarget;
  9311. bool isStructTarget = (target) && (target.mType->IsStruct());
  9312. bool bindCapturesThis = bindMethodInstance->HasThis() && !isStructTarget;
  9313. bool needsSplat = (isStructTarget) && (!bindMethodInstance->mMethodDef->mIsMutating) && (bindMethodInstance->AllowsSplatting());
  9314. bool captureThisByValue = isStructTarget;
  9315. if (bindMethodInstance->mMethodDef->mIsLocalMethod)
  9316. {
  9317. // Local method captures always capture 'this' by reference
  9318. captureThisByValue = false;
  9319. }
  9320. if ((origTarget.mType != NULL) &&
  9321. ((origTarget.mType->IsRef()) || (origTarget.mType->IsPointer())))
  9322. {
  9323. captureThisByValue = false;
  9324. }
  9325. if (methodRefTarget)
  9326. BF_ASSERT(methodRefTarget.mType->IsMethodRef());
  9327. if (target.IsSplat())
  9328. target = mModule->AggregateSplat(target, &bindResult.mIRArgs[0]);
  9329. bool hasCaptures = false;
  9330. // Do we need a special delegate type for this?
  9331. if (((captureThisByValue) || (needsSplat) || (implicitParamCount > 0) /*|| (hasIncompatibleCallingConventions)*/) &&
  9332. (mModule->HasCompiledOutput()))
  9333. {
  9334. hasCaptures = true;
  9335. auto curProject = mModule->mCurTypeInstance->mTypeDef->mProject;
  9336. if (captureThisByValue)
  9337. target = mModule->LoadValue(target);
  9338. String delegateTypeName = mModule->TypeToString(delegateTypeInstance);
  9339. HashContext hashCtx;
  9340. hashCtx.MixinStr(delegateTypeName);
  9341. // We mix in the project for reasons described in the lambda binding handler
  9342. hashCtx.MixinStr(curProject->mName);
  9343. String structTargetTypeName;
  9344. String structTargetName;
  9345. // Implicit param separator
  9346. for (int implicitParamIdx = bindMethodInstance->HasThis() ? - 1 : 0; implicitParamIdx < implicitParamCount; implicitParamIdx++)
  9347. {
  9348. auto paramType = bindResult.mMethodInstance->GetParamType(implicitParamIdx);
  9349. if ((implicitParamIdx == -1) && (captureThisByValue))
  9350. {
  9351. if (paramType->IsPointer())
  9352. paramType = paramType->GetUnderlyingType();
  9353. }
  9354. structTargetTypeName = mModule->TypeToString(paramType);
  9355. structTargetName = bindResult.mMethodInstance->GetParamName(implicitParamIdx);
  9356. hashCtx.MixinStr(structTargetTypeName);
  9357. hashCtx.MixinStr(structTargetName);
  9358. }
  9359. Val128 hash128 = hashCtx.Finish128();
  9360. BfClosureType* checkClosureType = new BfClosureType(delegateTypeInstance, hash128);
  9361. checkClosureType->mContext = mModule->mContext;
  9362. checkClosureType->mBaseType = delegateTypeInstance;
  9363. BfType* resolvedClosureType = mModule->ResolveType(checkClosureType, BfPopulateType_TypeDef);
  9364. closureTypeInst = (BfClosureType*)resolvedClosureType;
  9365. if (checkClosureType == resolvedClosureType)
  9366. {
  9367. // This is a new closure type
  9368. closureTypeInst->Init(curProject);
  9369. for (int implicitParamIdx = bindMethodInstance->HasThis() ? -1 : 0; implicitParamIdx < implicitParamCount; implicitParamIdx++)
  9370. {
  9371. String fieldName = bindResult.mMethodInstance->GetParamName(implicitParamIdx);
  9372. BfType* paramType = bindResult.mMethodInstance->GetParamType(implicitParamIdx);
  9373. if ((implicitParamIdx == -1) && (captureThisByValue))
  9374. {
  9375. if (paramType->IsPointer())
  9376. paramType = paramType->GetUnderlyingType();
  9377. }
  9378. if (fieldName == "this")
  9379. fieldName = "__this";
  9380. closureTypeInst->AddField(paramType, fieldName);
  9381. }
  9382. closureTypeInst->Finish();
  9383. mModule->PopulateType(resolvedClosureType, BfPopulateType_Declaration);
  9384. }
  9385. else
  9386. {
  9387. // Already had this entry
  9388. delete checkClosureType;
  9389. }
  9390. useTypeInstance = closureTypeInst;
  9391. }
  9392. mModule->PopulateType(useTypeInstance);
  9393. if (delegateBindExpr->mTarget == NULL)
  9394. {
  9395. mModule->AssertErrorState();
  9396. return;
  9397. }
  9398. mResult = BfTypedValue(mModule->AllocFromType(useTypeInstance, allocTarget, BfIRValue(), BfIRValue(), 0, BfAllocFlags_None), useTypeInstance);
  9399. // Do we need specialized calling code for this?
  9400. BfIRValue funcValue;
  9401. if (((needsSplat) || (implicitParamCount > 0) || (hasIncompatibleCallingConventions)) &&
  9402. (mModule->HasCompiledOutput()))
  9403. {
  9404. int fieldIdx = 0;
  9405. for (int implicitParamIdx = bindMethodInstance->HasThis() ? -1 : 0; implicitParamIdx < implicitParamCount; implicitParamIdx++)
  9406. {
  9407. auto fieldInst = &useTypeInstance->mFieldInstances[fieldIdx];
  9408. int gepIdx = fieldInst->mDataIdx;
  9409. auto fieldPtr = mModule->mBfIRBuilder->CreateInBoundsGEP(mResult.mValue, 0, gepIdx);
  9410. auto fieldType = bindMethodInstance->GetParamType(implicitParamIdx);
  9411. if ((implicitParamIdx == -1) && (captureThisByValue))
  9412. {
  9413. if (fieldType->IsPointer())
  9414. fieldType = fieldType->GetUnderlyingType();
  9415. }
  9416. bool failed = false;
  9417. BfTypedValue lookupVal;
  9418. if (implicitParamIdx == -1)
  9419. lookupVal = target;
  9420. else
  9421. lookupVal = DoImplicitArgCapture(delegateBindExpr->mTarget, bindResult.mMethodInstance, implicitParamIdx, failed, BfImplicitParamKind_General, methodRefTarget);
  9422. if (!lookupVal)
  9423. continue;
  9424. if ((fieldType->IsPointer()) && (lookupVal.mType != fieldType))
  9425. {
  9426. BF_ASSERT(fieldType->GetUnderlyingType() == lookupVal.mType);
  9427. BF_ASSERT(lookupVal.IsAddr());
  9428. }
  9429. else if (!fieldType->IsRef())
  9430. lookupVal = mModule->LoadOrAggregateValue(lookupVal);
  9431. if (lookupVal)
  9432. mModule->mBfIRBuilder->CreateStore(lookupVal.mValue, fieldPtr);
  9433. fieldIdx++;
  9434. }
  9435. String methodName = _GetInvokeMethodName();
  9436. SizedArray<BfIRType, 8> irParamTypes;
  9437. BfIRType irReturnType;
  9438. bool hasThis = false;
  9439. if (hasCaptures)
  9440. {
  9441. hasThis = true;
  9442. methodInstance->GetIRFunctionInfo(mModule, irReturnType, irParamTypes);
  9443. int thisIdx = 0;
  9444. if (methodInstance->GetStructRetIdx() == 0)
  9445. thisIdx = 1;
  9446. irParamTypes[thisIdx] = mModule->mBfIRBuilder->MapType(useTypeInstance);
  9447. }
  9448. else
  9449. {
  9450. BF_ASSERT(hasIncompatibleCallingConventions);
  9451. bindMethodInstance->GetIRFunctionInfo(mModule, irReturnType, irParamTypes);
  9452. hasThis = bindMethodInstance->HasThis();
  9453. }
  9454. auto prevActiveFunction = mModule->mBfIRBuilder->GetActiveFunction();
  9455. auto prevInsertBlock = mModule->mBfIRBuilder->GetInsertBlock();
  9456. mModule->mBfIRBuilder->SaveDebugLocation();
  9457. auto funcType = mModule->mBfIRBuilder->CreateFunctionType(irReturnType, irParamTypes);
  9458. funcValue = mModule->mBfIRBuilder->CreateFunction(funcType, BfIRLinkageType_External, methodName);
  9459. if (methodInstance->GetStructRetIdx() != -1)
  9460. {
  9461. mModule->mBfIRBuilder->Func_AddAttribute(funcValue, methodInstance->GetStructRetIdx() + 1, BfIRAttribute_NoAlias);
  9462. mModule->mBfIRBuilder->Func_AddAttribute(funcValue, methodInstance->GetStructRetIdx() + 1, BfIRAttribute_StructRet);
  9463. }
  9464. auto srcCallingConv = mModule->GetIRCallingConvention(methodInstance);
  9465. if ((!hasThis) && (methodInstance->mCallingConvention == BfCallingConvention_Stdcall))
  9466. srcCallingConv = BfIRCallingConv_StdCall;
  9467. else if (methodInstance->mCallingConvention == BfCallingConvention_Fastcall)
  9468. srcCallingConv = BfIRCallingConv_FastCall;
  9469. mModule->mBfIRBuilder->SetFuncCallingConv(funcValue, srcCallingConv);
  9470. mModule->mBfIRBuilder->SetActiveFunction(funcValue);
  9471. auto entryBlock = mModule->mBfIRBuilder->CreateBlock("entry", true);
  9472. mModule->mBfIRBuilder->SetInsertPoint(entryBlock);
  9473. fieldIdx = 0;
  9474. SizedArray<BfIRValue, 8> irArgs;
  9475. int argIdx = 0;
  9476. if (bindMethodInstance->GetStructRetIdx() == 0)
  9477. {
  9478. irArgs.push_back(mModule->mBfIRBuilder->GetArgument(methodInstance->GetStructRetIdx()));
  9479. argIdx++;
  9480. }
  9481. for (int implicitParamIdx = bindMethodInstance->HasThis() ? -1 : 0; implicitParamIdx < implicitParamCount; implicitParamIdx++)
  9482. {
  9483. auto fieldInst = &useTypeInstance->mFieldInstances[fieldIdx];
  9484. int gepIdx = fieldInst->mDataIdx;
  9485. auto fieldType = bindMethodInstance->GetParamType(implicitParamIdx);
  9486. bool disableSplat = false;
  9487. if ((implicitParamIdx == -1) && (captureThisByValue))
  9488. {
  9489. if (fieldType->IsPointer())
  9490. {
  9491. fieldType = fieldType->GetUnderlyingType();
  9492. disableSplat = true;
  9493. }
  9494. }
  9495. int thisIdx = 0;
  9496. if (methodInstance->GetStructRetIdx() == 0)
  9497. thisIdx = 1;
  9498. auto fieldPtr = mModule->mBfIRBuilder->CreateInBoundsGEP(mModule->mBfIRBuilder->GetArgument(thisIdx), 0, gepIdx);
  9499. BfTypedValue typedVal(fieldPtr, fieldType, true);
  9500. PushArg(typedVal, irArgs, disableSplat);
  9501. fieldIdx++;
  9502. }
  9503. if (hasThis)
  9504. argIdx++;
  9505. if (bindMethodInstance->GetStructRetIdx() == 1)
  9506. {
  9507. irArgs.push_back(mModule->mBfIRBuilder->GetArgument(methodInstance->GetStructRetIdx()));
  9508. argIdx++;
  9509. }
  9510. for (int paramIdx = 0; paramIdx < methodInstance->GetParamCount(); paramIdx++)
  9511. {
  9512. auto paramType = methodInstance->GetParamType(paramIdx);
  9513. if (paramType->IsSplattable())
  9514. {
  9515. BfTypeUtils::SplatIterate([&](BfType* checkType) { irArgs.push_back(mModule->mBfIRBuilder->GetArgument(argIdx++)); }, paramType);
  9516. }
  9517. else if (!paramType->IsValuelessType())
  9518. {
  9519. irArgs.push_back(mModule->mBfIRBuilder->GetArgument(argIdx++));
  9520. }
  9521. }
  9522. auto bindFuncVal = bindResult.mFunc;
  9523. if (mModule->mCompiler->mOptions.mAllowHotSwapping)
  9524. bindFuncVal = mModule->mBfIRBuilder->RemapBindFunction(bindFuncVal);
  9525. auto callInst = mModule->mBfIRBuilder->CreateCall(bindFuncVal, irArgs);
  9526. if (bindMethodInstance->GetStructRetIdx() != -1)
  9527. mModule->mBfIRBuilder->Call_AddAttribute(callInst, bindMethodInstance->GetStructRetIdx() + 1, BfIRAttribute_StructRet);
  9528. auto destCallingConv = mModule->GetIRCallingConvention(bindMethodInstance);
  9529. if (destCallingConv != BfIRCallingConv_CDecl)
  9530. mModule->mBfIRBuilder->SetCallCallingConv(callInst, destCallingConv);
  9531. if ((methodInstance->mReturnType->IsValuelessType()) || (methodInstance->GetStructRetIdx() != -1))
  9532. {
  9533. mModule->mBfIRBuilder->CreateRetVoid();
  9534. }
  9535. else
  9536. {
  9537. mModule->mBfIRBuilder->CreateRet(callInst);
  9538. }
  9539. mModule->mBfIRBuilder->SetActiveFunction(prevActiveFunction);
  9540. mModule->mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  9541. mModule->mBfIRBuilder->RestoreDebugLocation();
  9542. }
  9543. else if ((closureTypeInst != NULL) && (captureThisByValue))
  9544. {
  9545. // 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
  9546. auto fieldPtr = mModule->mBfIRBuilder->CreateInBoundsGEP(mResult.mValue, 0, 1);
  9547. target = mModule->LoadValue(target);
  9548. mModule->mBfIRBuilder->CreateStore(target.mValue, fieldPtr);
  9549. target = BfTypedValue(fieldPtr, target.mType, true);
  9550. }
  9551. BfResolvedArgs resolvedArgs;
  9552. MatchConstructor(delegateBindExpr, delegateBindExpr, mResult, useTypeInstance, resolvedArgs, false, false);
  9553. auto baseDelegateType = VerifyBaseDelegateType(delegateTypeInstance->mBaseType);
  9554. auto baseDelegate = mModule->mBfIRBuilder->CreateBitCast(mResult.mValue, mModule->mBfIRBuilder->MapType(baseDelegateType, BfIRPopulateType_Full));
  9555. // >> delegate.mTarget = bindResult.mTarget
  9556. BfIRValue valPtr;
  9557. if (mModule->HasCompiledOutput())
  9558. {
  9559. if ((implicitParamCount > 0) || (needsSplat)) // Point back to self, it contains capture data
  9560. valPtr = mModule->mBfIRBuilder->CreateBitCast(mResult.mValue, mModule->mBfIRBuilder->GetPrimitiveType(BfTypeCode_NullPtr));
  9561. else if (bindResult.mTarget)
  9562. valPtr = mModule->mBfIRBuilder->CreateBitCast(target.mValue, mModule->mBfIRBuilder->GetPrimitiveType(BfTypeCode_NullPtr));
  9563. else
  9564. valPtr = mModule->GetDefaultValue(mModule->GetPrimitiveType(BfTypeCode_NullPtr));
  9565. auto fieldPtr = mModule->mBfIRBuilder->CreateInBoundsGEP(baseDelegate, 0, 2);
  9566. mModule->mBfIRBuilder->CreateStore(valPtr, fieldPtr);
  9567. }
  9568. if (!funcValue)
  9569. {
  9570. funcValue = bindResult.mFunc;
  9571. if (!funcValue)
  9572. {
  9573. if ((mModule->HasCompiledOutput()) && (!mModule->mBfIRBuilder->mIgnoreWrites))
  9574. mModule->AssertErrorState();
  9575. return;
  9576. }
  9577. if ((mModule->mCompiler->mOptions.mAllowHotSwapping) && (!bindResult.mMethodInstance->mMethodDef->mIsVirtual))
  9578. {
  9579. funcValue = mModule->mBfIRBuilder->RemapBindFunction(funcValue);
  9580. }
  9581. }
  9582. // >> delegate.mFuncPtr = bindResult.mFunc
  9583. auto nullPtrType = mModule->GetPrimitiveType(BfTypeCode_NullPtr);
  9584. valPtr = mModule->mBfIRBuilder->CreateBitCast(funcValue, mModule->mBfIRBuilder->MapType(nullPtrType));
  9585. auto fieldPtr = mModule->mBfIRBuilder->CreateInBoundsGEP(baseDelegate, 0, 1);
  9586. mModule->mBfIRBuilder->CreateStore(valPtr, fieldPtr);
  9587. }
  9588. void BfExprEvaluator::VisitLambdaBodies(BfAstNode* body, BfFieldDtorDeclaration* fieldDtor)
  9589. {
  9590. if (auto blockBody = BfNodeDynCast<BfBlock>(body))
  9591. mModule->VisitChild(blockBody);
  9592. else if (auto bodyExpr = BfNodeDynCast<BfExpression>(body))
  9593. mModule->CreateValueFromExpression(bodyExpr);
  9594. while (fieldDtor != NULL)
  9595. {
  9596. mModule->VisitChild(fieldDtor->mBody);
  9597. fieldDtor = fieldDtor->mNextFieldDtor;
  9598. }
  9599. }
  9600. BfLambdaInstance* BfExprEvaluator::GetLambdaInstance(BfLambdaBindExpression* lambdaBindExpr, BfAllocTarget& allocTarget)
  9601. {
  9602. auto rootMethodState = mModule->mCurMethodState->GetRootMethodState();
  9603. BfAstNodeList cacheNodeList;
  9604. cacheNodeList.mList.Add(lambdaBindExpr);
  9605. ///
  9606. {
  9607. auto checkMethodState = mModule->mCurMethodState;
  9608. while (checkMethodState != NULL)
  9609. {
  9610. if (checkMethodState->mMixinState != NULL)
  9611. cacheNodeList.mList.Add(checkMethodState->mMixinState->mSource);
  9612. checkMethodState = checkMethodState->mPrevMethodState;
  9613. }
  9614. }
  9615. BfLambdaInstance* lambdaInstance = NULL;
  9616. if (rootMethodState->mLambdaCache.TryGetValue(cacheNodeList, &lambdaInstance))
  9617. return lambdaInstance;
  9618. static int sBindCount = 0;
  9619. sBindCount++;
  9620. bool isFunctionBind = false;
  9621. BfTypeInstance* delegateTypeInstance = NULL;
  9622. BfMethodInstance* invokeMethodInstance = NULL;
  9623. if (mExpectingType == NULL)
  9624. {
  9625. mModule->Fail("Cannot infer delegate type", lambdaBindExpr);
  9626. delegateTypeInstance = mModule->ResolveTypeDef(mModule->mCompiler->mActionTypeDef)->ToTypeInstance();
  9627. }
  9628. else
  9629. {
  9630. delegateTypeInstance = mExpectingType->ToTypeInstance();
  9631. if ((delegateTypeInstance == NULL) ||
  9632. ((!delegateTypeInstance->mTypeDef->mIsDelegate) && (!delegateTypeInstance->mTypeDef->mIsFunction)))
  9633. {
  9634. if (lambdaBindExpr->mFatArrowToken != NULL)
  9635. mModule->Fail("Can only bind lambdas to delegate types", lambdaBindExpr->mFatArrowToken);
  9636. delegateTypeInstance = mModule->ResolveTypeDef(mModule->mCompiler->mActionTypeDef)->ToTypeInstance();
  9637. }
  9638. else
  9639. {
  9640. invokeMethodInstance = mModule->GetRawMethodInstanceAtIdx(delegateTypeInstance, 0, "Invoke");
  9641. }
  9642. isFunctionBind = delegateTypeInstance->mTypeDef->mIsFunction;
  9643. }
  9644. if (auto tokenNode = BfNodeDynCast<BfTokenNode>(lambdaBindExpr->mNewToken))
  9645. {
  9646. if (isFunctionBind)
  9647. {
  9648. mModule->Fail("Function lambda binding does not require allocation", lambdaBindExpr->mNewToken);
  9649. }
  9650. else if (tokenNode->GetToken() == BfToken_Append)
  9651. {
  9652. mModule->Fail("Append allocation on delegate bind not supported", lambdaBindExpr->mNewToken);
  9653. }
  9654. }
  9655. if (invokeMethodInstance != NULL)
  9656. {
  9657. if ((int)lambdaBindExpr->mParams.size() < invokeMethodInstance->GetParamCount())
  9658. {
  9659. BfAstNode* refNode = lambdaBindExpr->mCloseParen;
  9660. if (refNode == NULL)
  9661. refNode = lambdaBindExpr;
  9662. mModule->Fail(StrFormat("Not enough parameters for delegate type '%s'. Expected %d more.",
  9663. mModule->TypeToString(delegateTypeInstance).c_str(), invokeMethodInstance->GetParamCount() - lambdaBindExpr->mParams.size()), refNode);
  9664. }
  9665. else if ((int)lambdaBindExpr->mParams.size() > invokeMethodInstance->GetParamCount())
  9666. {
  9667. BfAstNode* refNode = lambdaBindExpr->mParams[invokeMethodInstance->GetParamCount()];
  9668. mModule->Fail(StrFormat("Too many parameters for delegate type '%s'. Expected %d fewer.",
  9669. mModule->TypeToString(delegateTypeInstance).c_str(), lambdaBindExpr->mParams.size() - invokeMethodInstance->GetParamCount()), refNode);
  9670. }
  9671. }
  9672. auto autoComplete = GetAutoComplete();
  9673. bool wasCapturingMethodInfo = false;
  9674. if ((autoComplete != NULL) && (invokeMethodInstance != NULL))
  9675. {
  9676. wasCapturingMethodInfo = autoComplete->mIsCapturingMethodMatchInfo;
  9677. autoComplete->CheckInvocation(lambdaBindExpr, lambdaBindExpr->mOpenParen, lambdaBindExpr->mCloseParen, lambdaBindExpr->mCommas);
  9678. if (autoComplete->mIsCapturingMethodMatchInfo)
  9679. {
  9680. autoComplete->mMethodMatchInfo->mInstanceList.Clear();
  9681. auto methodMatchInfo = autoComplete->mMethodMatchInfo;
  9682. BfAutoComplete::MethodMatchEntry methodMatchEntry;
  9683. methodMatchEntry.mTypeInstance = invokeMethodInstance->GetOwner();
  9684. methodMatchEntry.mCurMethodInstance = mModule->mCurMethodInstance;
  9685. methodMatchEntry.mMethodDef = invokeMethodInstance->mMethodDef;
  9686. autoComplete->mMethodMatchInfo->mInstanceList.push_back(methodMatchEntry);
  9687. methodMatchInfo->mBestIdx = 0;
  9688. methodMatchInfo->mMostParamsMatched = 0;
  9689. int cursorIdx = lambdaBindExpr->GetParser()->mCursorIdx;
  9690. if ((lambdaBindExpr->mCloseParen == NULL) || (cursorIdx <= lambdaBindExpr->mCloseParen->GetSrcStart()))
  9691. {
  9692. int paramIdx = 0;
  9693. for (int commaIdx = 0; commaIdx < (int)lambdaBindExpr->mCommas.size(); commaIdx++)
  9694. {
  9695. auto commaNode = lambdaBindExpr->mCommas[commaIdx];
  9696. if ((commaNode != NULL) && (cursorIdx >= commaNode->GetSrcStart()))
  9697. paramIdx = commaIdx + 1;
  9698. }
  9699. bool isEmpty = true;
  9700. if (paramIdx < (int)lambdaBindExpr->mParams.size())
  9701. {
  9702. auto paramNode = lambdaBindExpr->mParams[paramIdx];
  9703. if (paramNode != NULL)
  9704. isEmpty = false;
  9705. }
  9706. if (isEmpty)
  9707. {
  9708. if (paramIdx < (int)invokeMethodInstance->GetParamCount())
  9709. {
  9710. String paramName = invokeMethodInstance->GetParamName(paramIdx);
  9711. autoComplete->mEntriesSet.Clear();
  9712. if (paramName.IsEmpty())
  9713. paramName += StrFormat("val%d", paramIdx + 1);
  9714. autoComplete->AddEntry(AutoCompleteEntry("paramName", paramName));
  9715. autoComplete->mInsertStartIdx = cursorIdx;
  9716. autoComplete->mInsertEndIdx = cursorIdx;
  9717. if ((paramIdx == 0) && (lambdaBindExpr->mParams.IsEmpty()))
  9718. {
  9719. String totalNames;
  9720. for (int checkIdx = 0; checkIdx < (int)invokeMethodInstance->GetParamCount(); checkIdx++)
  9721. {
  9722. if (!totalNames.IsEmpty())
  9723. totalNames += ", ";
  9724. String paramName = invokeMethodInstance->GetParamName(checkIdx);
  9725. if (paramName.IsEmpty())
  9726. paramName += StrFormat("val%d", checkIdx + 1);
  9727. totalNames += paramName;
  9728. }
  9729. autoComplete->AddEntry(AutoCompleteEntry("paramNames", totalNames));
  9730. }
  9731. }
  9732. }
  9733. }
  9734. }
  9735. }
  9736. defer
  9737. (
  9738. {
  9739. if (autoComplete != NULL)
  9740. autoComplete->mIsCapturingMethodMatchInfo = (wasCapturingMethodInfo) && (!autoComplete->mIsCapturingMethodMatchInfo);
  9741. }
  9742. );
  9743. if (lambdaBindExpr->mBody == NULL)
  9744. {
  9745. mModule->AssertErrorState();
  9746. return NULL;
  9747. }
  9748. if ((lambdaBindExpr->mNewToken == NULL) || (isFunctionBind))
  9749. {
  9750. if ((lambdaBindExpr->mNewToken != NULL) && (isFunctionBind))
  9751. mModule->Fail("Binds to functions should do not require allocations.", lambdaBindExpr->mNewToken);
  9752. if (lambdaBindExpr->mDtor != NULL)
  9753. {
  9754. mModule->Fail("Valueless method reference cannot contain destructor. Consider either removing destructor or using an allocated lambda.", lambdaBindExpr->mDtor->mTildeToken);
  9755. // Eat it
  9756. auto fieldDtor = lambdaBindExpr->mDtor;
  9757. while (fieldDtor != NULL)
  9758. {
  9759. mModule->VisitEmbeddedStatement(fieldDtor->mBody);
  9760. fieldDtor = fieldDtor->mNextFieldDtor;
  9761. }
  9762. }
  9763. if (invokeMethodInstance != NULL)
  9764. {
  9765. BfLocalMethod* localMethod = new BfLocalMethod();
  9766. localMethod->mMethodName = "anon";
  9767. localMethod->mSystem = mModule->mSystem;
  9768. localMethod->mModule = mModule;
  9769. localMethod->mExpectedFullName = mModule->GetLocalMethodName(localMethod->mMethodName, lambdaBindExpr->mFatArrowToken, mModule->mCurMethodState, mModule->mCurMethodState->mMixinState);
  9770. localMethod->mLambdaInvokeMethodInstance = invokeMethodInstance;
  9771. localMethod->mLambdaBindExpr = lambdaBindExpr;
  9772. localMethod->mDeclMethodState = mModule->mCurMethodState;
  9773. mModule->mContext->mLocalMethodGraveyard.push_back(localMethod);
  9774. auto moduleMethodInstance = mModule->GetLocalMethodInstance(localMethod, BfTypeVector());
  9775. if (moduleMethodInstance.mMethodInstance->mDisallowCalling)
  9776. {
  9777. mResult = mModule->GetDefaultTypedValue(mExpectingType, false, BfDefaultValueKind_Addr);
  9778. return NULL;
  9779. }
  9780. auto methodRefType = mModule->CreateMethodRefType(moduleMethodInstance.mMethodInstance);
  9781. mModule->AddDependency(methodRefType, mModule->mCurTypeInstance, BfDependencyMap::DependencyFlag_Calls);
  9782. mModule->AddCallDependency(moduleMethodInstance.mMethodInstance);
  9783. mResult = BfTypedValue(BfIRValue(BfIRValueFlags_Value, BfIRValue::ID_IMPLICIT), methodRefType);
  9784. return NULL;
  9785. }
  9786. }
  9787. //SetAndRestoreValue<bool> prevIgnoreIRWrites(mModule->mBfIRBuilder->mIgnoreWrites, mModule->mWantsIRIgnoreWrites);
  9788. SetAndRestoreValue<bool> prevIgnoreIRWrites(mModule->mBfIRBuilder->mIgnoreWrites, mModule->mWantsIRIgnoreWrites || mModule->mCurMethodInstance->mIsUnspecialized);
  9789. BfTypeInstance* outerClosure = NULL;
  9790. if ((mModule->mCurMethodState->mClosureState != NULL) && (!mModule->mCurMethodState->mClosureState->mCapturing))
  9791. outerClosure = mModule->mCurMethodState->mClosureState->mClosureType;
  9792. Val128 val128(delegateTypeInstance->mTypeId);
  9793. BfMethodState methodState;
  9794. methodState.mPrevMethodState = mModule->mCurMethodState;
  9795. BfIRFunctionType funcType;
  9796. auto voidType = mModule->GetPrimitiveType(BfTypeCode_None);
  9797. SizedArray<BfIRType, 0> paramTypes;
  9798. funcType = mModule->mBfIRBuilder->CreateFunctionType(mModule->mBfIRBuilder->MapType(voidType), paramTypes, false);
  9799. auto prevInsertBlock = mModule->mBfIRBuilder->GetInsertBlock();
  9800. BF_ASSERT(prevInsertBlock);
  9801. auto prevActiveFunction = mModule->mBfIRBuilder->GetActiveFunction();
  9802. mModule->mBfIRBuilder->SaveDebugLocation();
  9803. SetAndRestoreValue<bool> prevIgnoreWrites(mModule->mBfIRBuilder->mIgnoreWrites, true);
  9804. BfDeferredLocalAssignData deferredLocalAssignData;
  9805. if (mModule->mCurMethodState->mDeferredLocalAssignData != NULL)
  9806. deferredLocalAssignData.ExtendFrom(mModule->mCurMethodState->mDeferredLocalAssignData);
  9807. SetAndRestoreValue<BfMethodState*> prevMethodState(mModule->mCurMethodState, &methodState);
  9808. methodState.mIRHeadBlock = mModule->mBfIRBuilder->CreateBlock("head", true);
  9809. methodState.mIRInitBlock = mModule->mBfIRBuilder->CreateBlock("init", true);
  9810. methodState.mIREntryBlock = mModule->mBfIRBuilder->CreateBlock("entry", true);
  9811. methodState.mCurScope->mDIScope = prevMethodState.mPrevVal->mCurScope->mDIScope;//invokeMethodInstance->mDIFunction;
  9812. methodState.mCurLocalVarId = -1;
  9813. methodState.mIRFunction = prevMethodState.mPrevVal->mIRFunction;
  9814. methodState.mDeferredLocalAssignData = &deferredLocalAssignData;
  9815. mModule->mBfIRBuilder->SetInsertPoint(methodState.mIREntryBlock);
  9816. BfClosureState closureState;
  9817. if (delegateTypeInstance->IsDelegate())
  9818. closureState.mReturnType = mModule->GetDelegateReturnType(delegateTypeInstance);
  9819. else
  9820. closureState.mReturnType = mModule->mContext->mBfObjectType;
  9821. closureState.mCapturing = true;
  9822. closureState.mDeclaringMethodIsMutating = mModule->mCurMethodInstance->mMethodDef->mIsMutating;
  9823. methodState.mClosureState = &closureState;
  9824. closureState.mClosureType = outerClosure;
  9825. BF_ASSERT(methodState.mCurLocalVarId == -1);
  9826. int outerLocalsCount = (int)methodState.mLocals.size();
  9827. // static int sItrCount = 0;
  9828. // ++sItrCount;
  9829. // int itrCount = sItrCount;
  9830. // if ((itrCount == 8) || (itrCount == 10))
  9831. // {
  9832. // NOP;
  9833. // }
  9834. String delegateTypeName = mModule->TypeToString(delegateTypeInstance);
  9835. HashContext hashCtx;
  9836. hashCtx.MixinStr(delegateTypeName);
  9837. BfSource* bfSource = delegateTypeInstance->mTypeDef->mSource;
  9838. BfMethodDef* methodDef = new BfMethodDef();
  9839. methodDef->mDeclaringType = mModule->mCurMethodInstance->mMethodDef->mDeclaringType;
  9840. Val128 closureMethodHash;
  9841. OwnedVector<BfParameterDeclaration> tempParamDecls;
  9842. if ((autoComplete != NULL) && (autoComplete->mMethodMatchInfo != NULL) && (autoComplete->IsAutocompleteNode(lambdaBindExpr->mBody)))
  9843. {
  9844. // Don't show outer method match info when our cursor is inside a lambda expression (being passed as a parameter)
  9845. autoComplete->RemoveMethodMatchInfo();
  9846. }
  9847. if (invokeMethodInstance != NULL)
  9848. {
  9849. for (int paramIdx = 0; paramIdx < (int)invokeMethodInstance->mMethodDef->mParams.size(); paramIdx++)
  9850. {
  9851. auto invokeParamDef = invokeMethodInstance->mMethodDef->mParams[paramIdx];
  9852. BfParameterDef* paramDef = new BfParameterDef();
  9853. paramDef->mParamDeclaration = tempParamDecls.Alloc();
  9854. BfAstNode::Zero(paramDef->mParamDeclaration);
  9855. BfLocalVariable* localVar = new BfLocalVariable();
  9856. if (paramIdx < (int)lambdaBindExpr->mParams.size())
  9857. {
  9858. localVar->mName = lambdaBindExpr->mParams[paramIdx]->ToString();
  9859. localVar->mNameNode = lambdaBindExpr->mParams[paramIdx];
  9860. paramDef->mParamDeclaration->mNameNode = lambdaBindExpr->mParams[paramIdx];
  9861. }
  9862. else
  9863. {
  9864. mModule->AssertErrorState();
  9865. localVar->mName = invokeParamDef->mName;
  9866. paramDef->mParamDeclaration->mNameNode = NULL;
  9867. }
  9868. paramDef->mName = localVar->mName;
  9869. methodDef->mParams.push_back(paramDef);
  9870. localVar->mResolvedType = invokeMethodInstance->GetParamType(paramIdx);
  9871. localVar->mAssignedKind = BfLocalVarAssignKind_Unconditional;
  9872. localVar->mReadFromId = 0;
  9873. auto rootMethodState = methodState.GetRootMethodState();
  9874. localVar->mLocalVarId = rootMethodState->mCurLocalVarId++;
  9875. mModule->DoAddLocalVariable(localVar);
  9876. if (autoComplete != NULL)
  9877. autoComplete->CheckLocalDef(BfNodeDynCast<BfIdentifierNode>(paramDef->mParamDeclaration->mNameNode), methodState.mLocals.back());
  9878. auto resolvePassData = mModule->mCompiler->mResolvePassData;
  9879. if (resolvePassData != NULL)
  9880. resolvePassData->HandleLocalReference(BfNodeDynCast<BfIdentifierNode>(paramDef->mParamDeclaration->mNameNode), mModule->mCurTypeInstance->mTypeDef,
  9881. mModule->mCurMethodInstance->mMethodDef, localVar->mLocalVarId);
  9882. }
  9883. }
  9884. bool isAutocomplete = mModule->mCompiler->IsAutocomplete();
  9885. methodDef->mIdx = mModule->mCurMethodInstance->mMethodDef->mIdx;
  9886. methodDef->mBody = lambdaBindExpr->mBody;
  9887. ///
  9888. auto varMethodState = methodState.mPrevMethodState;
  9889. bool hasExplicitCaptureNames = false;
  9890. for (auto& captureEntry : allocTarget.mCaptureInfo.mCaptures)
  9891. {
  9892. if (captureEntry.mNameNode == NULL)
  9893. {
  9894. hasExplicitCaptureNames = false;
  9895. break;
  9896. }
  9897. hasExplicitCaptureNames = true;
  9898. }
  9899. auto _SetNotCapturedFlag = [&](bool notCaptured)
  9900. {
  9901. auto varMethodState = methodState.mPrevMethodState;
  9902. while (varMethodState != NULL)
  9903. {
  9904. for (int localIdx = 0; localIdx < varMethodState->mLocals.size(); localIdx++)
  9905. {
  9906. auto localVar = varMethodState->mLocals[localIdx];
  9907. localVar->mNotCaptured = notCaptured;
  9908. }
  9909. varMethodState = varMethodState->mPrevMethodState;
  9910. if (varMethodState == NULL)
  9911. break;
  9912. if (varMethodState->mMixinState != NULL)
  9913. break;
  9914. if (varMethodState->mClosureState != NULL)
  9915. {
  9916. if (!varMethodState->mClosureState->mCapturing)
  9917. break;
  9918. }
  9919. }
  9920. };
  9921. if (hasExplicitCaptureNames)
  9922. {
  9923. _SetNotCapturedFlag(true);
  9924. auto varMethodState = methodState.mPrevMethodState;
  9925. while (varMethodState != NULL)
  9926. {
  9927. for (auto& captureEntry : allocTarget.mCaptureInfo.mCaptures)
  9928. {
  9929. if (captureEntry.mNameNode != NULL)
  9930. {
  9931. StringT<64> captureName;
  9932. captureEntry.mNameNode->ToString(captureName);
  9933. BfLocalVarEntry* entry;
  9934. if (varMethodState->mLocalVarSet.TryGetWith<StringImpl&>(captureName, &entry))
  9935. {
  9936. auto localVar = entry->mLocalVar;
  9937. while (localVar != NULL)
  9938. {
  9939. if (autoComplete != NULL)
  9940. autoComplete->CheckLocalRef(captureEntry.mNameNode, localVar);
  9941. if (((mModule->mCurMethodState->mClosureState == NULL) || (mModule->mCurMethodState->mClosureState->mCapturing)) &&
  9942. (mModule->mCompiler->mResolvePassData != NULL) && (mModule->mCurMethodInstance != NULL))
  9943. mModule->mCompiler->mResolvePassData->HandleLocalReference(captureEntry.mNameNode, localVar->mNameNode, mModule->mCurTypeInstance->mTypeDef, rootMethodState->mMethodInstance->mMethodDef, localVar->mLocalVarId);
  9944. localVar->mNotCaptured = false;
  9945. localVar = localVar->mShadowedLocal;
  9946. }
  9947. }
  9948. }
  9949. }
  9950. varMethodState = varMethodState->mPrevMethodState;
  9951. if (varMethodState == NULL)
  9952. break;
  9953. if (varMethodState->mMixinState != NULL)
  9954. break;
  9955. if (varMethodState->mClosureState != NULL)
  9956. {
  9957. if (!varMethodState->mClosureState->mCapturing)
  9958. break;
  9959. }
  9960. }
  9961. }
  9962. BfClosureInstanceInfo* closureInstanceInfo = new BfClosureInstanceInfo();
  9963. auto checkInsertBlock = mModule->mBfIRBuilder->GetInsertBlock();
  9964. closureState.mCaptureStartAccessId = methodState.mPrevMethodState->GetRootMethodState()->mCurAccessId;
  9965. closureState.mCaptureVisitingBody = true;
  9966. closureState.mClosureInstanceInfo = closureInstanceInfo;
  9967. VisitLambdaBodies(lambdaBindExpr->mBody, lambdaBindExpr->mDtor);
  9968. if (hasExplicitCaptureNames)
  9969. _SetNotCapturedFlag(false);
  9970. // If we ended up being called by a method with a lower captureStartAccessId, propagate that to whoever is calling us, too...
  9971. if ((methodState.mPrevMethodState->mClosureState != NULL) && (methodState.mPrevMethodState->mClosureState->mCapturing))
  9972. {
  9973. auto prevClosureState = methodState.mPrevMethodState->mClosureState;
  9974. if (closureState.mCaptureStartAccessId < prevClosureState->mCaptureStartAccessId)
  9975. prevClosureState->mCaptureStartAccessId = closureState.mCaptureStartAccessId;
  9976. }
  9977. if (mModule->mCurMethodInstance->mIsUnspecialized)
  9978. {
  9979. prevIgnoreWrites.Restore();
  9980. mModule->mBfIRBuilder->RestoreDebugLocation();
  9981. mResult = mModule->GetDefaultTypedValue(delegateTypeInstance);
  9982. mModule->mBfIRBuilder->SetActiveFunction(prevActiveFunction);
  9983. if (!prevInsertBlock.IsFake())
  9984. mModule->mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  9985. delete methodDef;
  9986. delete closureInstanceInfo;
  9987. return NULL;
  9988. }
  9989. closureState.mCaptureVisitingBody = false;
  9990. prevIgnoreWrites.Restore();
  9991. mModule->mBfIRBuilder->RestoreDebugLocation();
  9992. auto _GetCaptureType = [&](const StringImpl& str)
  9993. {
  9994. if (allocTarget.mCaptureInfo.mCaptures.IsEmpty())
  9995. return BfCaptureType_Copy;
  9996. for (auto& captureEntry : allocTarget.mCaptureInfo.mCaptures)
  9997. {
  9998. if ((captureEntry.mNameNode == NULL) || (captureEntry.mNameNode->Equals(str)))
  9999. {
  10000. captureEntry.mUsed = true;
  10001. return captureEntry.mCaptureType;
  10002. }
  10003. }
  10004. return BfCaptureType_None;
  10005. };
  10006. Array<BfClosureCapturedEntry> capturedEntries;
  10007. bool copyOuterCaptures = false;
  10008. //
  10009. {
  10010. auto varMethodState = methodState.mPrevMethodState;
  10011. while (varMethodState != NULL)
  10012. {
  10013. for (int localIdx = 0; localIdx < varMethodState->mLocals.size(); localIdx++)
  10014. {
  10015. auto localVar = varMethodState->mLocals[localIdx];
  10016. if ((localVar->mReadFromId >= closureState.mCaptureStartAccessId) || (localVar->mWrittenToId >= closureState.mCaptureStartAccessId))
  10017. {
  10018. if ((localVar->mIsThis) && (outerClosure != NULL))
  10019. {
  10020. continue;
  10021. }
  10022. auto outerLocal = localVar;
  10023. if ((localVar->mConstValue) || (localVar->mResolvedType->IsValuelessType()))
  10024. {
  10025. closureState.mConstLocals.push_back(*outerLocal);
  10026. continue;
  10027. }
  10028. BfClosureCapturedEntry capturedEntry;
  10029. auto capturedType = outerLocal->mResolvedType;
  10030. bool captureByRef = false;
  10031. auto captureType = _GetCaptureType(localVar->mName);
  10032. if (captureType == BfCaptureType_None)
  10033. {
  10034. continue;
  10035. }
  10036. if (!capturedType->IsRef())
  10037. {
  10038. if (captureType == BfCaptureType_Reference)
  10039. {
  10040. if (outerLocal->mIsThis)
  10041. {
  10042. if ((outerLocal->mResolvedType->IsValueType()) && (mModule->mCurMethodInstance->mMethodDef->HasNoThisSplat()))
  10043. captureByRef = true;
  10044. }
  10045. else if ((!localVar->mIsReadOnly) && (localVar->mWrittenToId >= closureState.mCaptureStartAccessId))
  10046. captureByRef = true;
  10047. }
  10048. }
  10049. else
  10050. {
  10051. if ((captureType != BfCaptureType_Reference) || (localVar->mWrittenToId < closureState.mCaptureStartAccessId))
  10052. {
  10053. capturedType = ((BfRefType*)capturedType)->mElementType;
  10054. }
  10055. }
  10056. if (captureByRef)
  10057. {
  10058. capturedType = mModule->CreateRefType(capturedType);
  10059. }
  10060. if (captureType == BfCaptureType_Reference)
  10061. capturedEntry.mExplicitlyByReference = true;
  10062. capturedEntry.mType = capturedType;
  10063. capturedEntry.mNameNode = outerLocal->mNameNode;
  10064. if (outerLocal->mName == "this")
  10065. capturedEntry.mName = "__this";
  10066. else
  10067. {
  10068. capturedEntry.mName = outerLocal->mName;
  10069. BfLocalVarEntry* entry = NULL;
  10070. if (varMethodState->mLocalVarSet.TryGetWith<StringImpl&>(capturedEntry.mName, &entry))
  10071. {
  10072. auto startCheckVar = entry->mLocalVar;
  10073. int shadowIdx = 0;
  10074. auto checkVar = startCheckVar;
  10075. while (checkVar != NULL)
  10076. {
  10077. if (checkVar == outerLocal)
  10078. {
  10079. // We only use mShadowIdx when we have duplicate name nodes (ie: in the case of for looks with iterator vs value)
  10080. auto shadowCheckVar = startCheckVar;
  10081. while (shadowCheckVar != checkVar)
  10082. {
  10083. if (shadowCheckVar->mNameNode == checkVar->mNameNode)
  10084. capturedEntry.mShadowIdx++;
  10085. shadowCheckVar = shadowCheckVar->mShadowedLocal;
  10086. }
  10087. for (int i = 0; i < shadowIdx; i++)
  10088. capturedEntry.mName.Insert(0, '@');
  10089. break;
  10090. }
  10091. shadowIdx++;
  10092. checkVar = checkVar->mShadowedLocal;
  10093. }
  10094. }
  10095. }
  10096. capturedEntries.Add(capturedEntry);
  10097. }
  10098. }
  10099. varMethodState = varMethodState->mPrevMethodState;
  10100. if (varMethodState == NULL)
  10101. break;
  10102. if (varMethodState->mMixinState != NULL)
  10103. break;
  10104. if (varMethodState->mClosureState != NULL)
  10105. {
  10106. if (!varMethodState->mClosureState->mCapturing)
  10107. break;
  10108. }
  10109. }
  10110. }
  10111. for (auto& captureEntry : allocTarget.mCaptureInfo.mCaptures)
  10112. {
  10113. if ((!captureEntry.mUsed) && (captureEntry.mNameNode != NULL))
  10114. mModule->Warn(0, "Capture specifier not used", captureEntry.mNameNode);
  10115. }
  10116. for (auto copyField : closureState.mReferencedOuterClosureMembers)
  10117. {
  10118. auto fieldDef = copyField->GetFieldDef();
  10119. auto captureType = _GetCaptureType(fieldDef->mName);
  10120. BfClosureCapturedEntry capturedEntry;
  10121. capturedEntry.mName = fieldDef->mName;
  10122. capturedEntry.mType = copyField->mResolvedType;
  10123. if ((captureType == BfCaptureType_Reference) && (capturedEntry.mType->IsRef()))
  10124. {
  10125. capturedEntry.mExplicitlyByReference = true;
  10126. }
  10127. else if ((captureType != BfCaptureType_Reference) && (capturedEntry.mType->IsRef()))
  10128. {
  10129. auto refType = (BfRefType*)capturedEntry.mType;
  10130. capturedEntry.mType = refType->mElementType;
  10131. }
  10132. else if ((captureType == BfCaptureType_Reference) && (!capturedEntry.mType->IsRef()) && (!fieldDef->mIsReadOnly))
  10133. {
  10134. capturedEntry.mType = mModule->CreateRefType(capturedEntry.mType);
  10135. }
  10136. }
  10137. std::sort(capturedEntries.begin(), capturedEntries.end());
  10138. bool hasCapture = false;
  10139. BfMethodInstanceGroup methodInstanceGroup;
  10140. methodInstanceGroup.mOwner = mModule->mCurTypeInstance;
  10141. methodInstanceGroup.mOnDemandKind = BfMethodOnDemandKind_AlwaysInclude;
  10142. BfMethodInstance* methodInstance = new BfMethodInstance();
  10143. methodInstance->mMethodInstanceGroup = &methodInstanceGroup;
  10144. methodInstance->GetMethodInfoEx()->mClosureInstanceInfo = closureInstanceInfo;
  10145. if (invokeMethodInstance != NULL)
  10146. methodInstance->mParams = invokeMethodInstance->mParams;
  10147. methodInstance->mIsClosure = true;
  10148. // We want the closure ID to match between hot reloads -- otherwise we wouldn't be able to modify them,
  10149. // so we use the charId from the 'fat arrow' token
  10150. int closureId = 0;
  10151. if (lambdaBindExpr->mFatArrowToken != NULL)
  10152. closureId = lambdaBindExpr->mFatArrowToken->GetStartCharId();
  10153. auto curProject = mModule->mCurTypeInstance->mTypeDef->mProject;
  10154. BF_ASSERT(curProject != NULL);
  10155. // We need to make these per-project even though you'd think we might not because we
  10156. // insert generic type specializations in the generic definition's project,
  10157. // BECAUSE: we would need to scan the captured fields the same way we scan the
  10158. // generic arguments to determine if each project can see it or not in the vdata
  10159. BfTypeInstance* useTypeInstance = delegateTypeInstance;
  10160. BfClosureType* closureTypeInst = NULL;
  10161. if ((capturedEntries.size() != 0) || (lambdaBindExpr->mDtor != NULL) || (copyOuterCaptures))
  10162. {
  10163. hashCtx.MixinStr(curProject->mName);
  10164. if (copyOuterCaptures)
  10165. {
  10166. // String typeName = mModule->DoTypeToString(outerClosure, BfTypeNameFlag_DisambiguateDups);
  10167. // hashCtx.MixinStr(typeName);
  10168. hashCtx.Mixin(outerClosure->mTypeId);
  10169. }
  10170. for (auto& capturedEntry : capturedEntries)
  10171. {
  10172. // String typeName = mModule->DoTypeToString(capturedEntry.mType, BfTypeNameFlag_DisambiguateDups);
  10173. // hashCtx.MixinStr(typeName);
  10174. hashCtx.Mixin(capturedEntry.mType->mTypeId);
  10175. hashCtx.MixinStr(capturedEntry.mName);
  10176. hashCtx.Mixin(capturedEntry.mExplicitlyByReference);
  10177. }
  10178. if (lambdaBindExpr->mDtor != NULL)
  10179. {
  10180. // Has DTOR thunk
  10181. bool hasDtorThunk = true;
  10182. hashCtx.Mixin(hasDtorThunk);
  10183. }
  10184. Val128 hash128 = hashCtx.Finish128();
  10185. BfClosureType* checkClosureType = new BfClosureType(delegateTypeInstance, hash128);
  10186. checkClosureType->mContext = mModule->mContext;
  10187. checkClosureType->mBaseType = delegateTypeInstance;
  10188. BfType* resolvedClosureType = mModule->ResolveType(checkClosureType, BfPopulateType_TypeDef);
  10189. closureTypeInst = (BfClosureType*)resolvedClosureType;
  10190. if (checkClosureType == resolvedClosureType)
  10191. {
  10192. // This is a new closure type
  10193. closureTypeInst->Init(curProject);
  10194. closureTypeInst->mTypeDef->mProject = curProject;
  10195. if (copyOuterCaptures)
  10196. {
  10197. for (auto& fieldInstance : outerClosure->mFieldInstances)
  10198. {
  10199. BfFieldDef* origFieldDef = fieldInstance.GetFieldDef();
  10200. BfFieldDef* fieldDef = closureTypeInst->AddField(fieldInstance.mResolvedType, origFieldDef->mName);
  10201. fieldDef->mIsReadOnly = origFieldDef->mIsReadOnly;
  10202. }
  10203. }
  10204. for (auto& capturedEntry : capturedEntries)
  10205. {
  10206. BfFieldDef* fieldDef = closureTypeInst->AddField(capturedEntry.mType, capturedEntry.mName);
  10207. if (!capturedEntry.mExplicitlyByReference)
  10208. fieldDef->mIsReadOnly = true;
  10209. }
  10210. if (lambdaBindExpr->mDtor != NULL)
  10211. {
  10212. auto dtorDef = closureTypeInst->AddDtor();
  10213. auto voidType = mModule->GetPrimitiveType(BfTypeCode_None);
  10214. auto voidPtrType = mModule->CreatePointerType(voidType);
  10215. closureTypeInst->AddField(voidPtrType, "__dtorThunk");
  10216. }
  10217. closureTypeInst->Finish();
  10218. }
  10219. else
  10220. {
  10221. // Already had this entry
  10222. delete checkClosureType;
  10223. }
  10224. useTypeInstance = closureTypeInst;
  10225. }
  10226. mModule->mBfIRBuilder->PopulateType(useTypeInstance);
  10227. mModule->PopulateType(useTypeInstance);
  10228. // If we are allowing hot swapping, we need to always mangle the name to non-static because if we add a capture
  10229. // later then we need to have the mangled names match
  10230. methodDef->mIsStatic = (closureTypeInst == NULL) && (!mModule->mCompiler->mOptions.mAllowHotSwapping);
  10231. SizedArray<BfIRType, 8> origParamTypes;
  10232. BfIRType origReturnType;
  10233. bool forceStatic = false;
  10234. if (invokeMethodInstance != NULL)
  10235. {
  10236. forceStatic = methodDef->mIsStatic;
  10237. auto invokeFunctionType = mModule->mBfIRBuilder->MapMethod(invokeMethodInstance);
  10238. invokeMethodInstance->GetIRFunctionInfo(mModule, origReturnType, origParamTypes, forceStatic);
  10239. }
  10240. else
  10241. {
  10242. origReturnType = mModule->mBfIRBuilder->MapType(mModule->GetPrimitiveType(BfTypeCode_None));
  10243. }
  10244. SizedArray<BfIRType, 3> newTypes;
  10245. if ((invokeMethodInstance != NULL) && (invokeMethodInstance->GetStructRetIdx(forceStatic) == 0))
  10246. newTypes.push_back(origParamTypes[0]);
  10247. if (!methodDef->mIsStatic)
  10248. newTypes.push_back(mModule->mBfIRBuilder->MapType(useTypeInstance));
  10249. if ((invokeMethodInstance != NULL) && (invokeMethodInstance->GetStructRetIdx(forceStatic) == 1))
  10250. newTypes.push_back(origParamTypes[1]);
  10251. int paramStartIdx = 0;
  10252. if ((invokeMethodInstance != NULL) && (invokeMethodInstance->GetStructRetIdx(forceStatic) != -1))
  10253. paramStartIdx++;
  10254. if (!methodDef->mIsStatic)
  10255. paramStartIdx++;
  10256. for (int i = paramStartIdx; i < (int)origParamTypes.size(); i++)
  10257. newTypes.push_back(origParamTypes[i]);
  10258. auto closureFuncType = mModule->mBfIRBuilder->CreateFunctionType(origReturnType, newTypes, false);
  10259. prevMethodState.Restore();
  10260. mModule->mBfIRBuilder->SetActiveFunction(prevActiveFunction);
  10261. if (!prevInsertBlock.IsFake())
  10262. mModule->mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  10263. // Just a check
  10264. mModule->mBfIRBuilder->GetInsertBlock();
  10265. //auto rootMethodState = mModule->mCurMethodState;
  10266. HashContext closureHashCtx;
  10267. closureHashCtx.Mixin(closureId);
  10268. // When we're a nested lambda, strip off the outer hash and closureTypeInst markers
  10269. methodDef->mName = mModule->mCurMethodInstance->mMethodDef->mName;
  10270. int prevSepPos = (int)methodDef->mName.LastIndexOf('$');
  10271. if (prevSepPos != -1)
  10272. {
  10273. closureHashCtx.Mixin(methodDef->mName.c_str() + prevSepPos, (int)methodDef->mName.length() - prevSepPos);
  10274. methodDef->mName.RemoveToEnd(prevSepPos);
  10275. }
  10276. // Mix in this because this can be emitted multiple times when there's multiple ctors and field initializers with lambdas
  10277. if (mModule->mCurMethodInstance->mMethodDef->mMethodType == BfMethodType_Ctor)
  10278. {
  10279. if (auto ctorDecl = BfNodeDynCast<BfConstructorDeclaration>(mModule->mCurMethodInstance->mMethodDef->mMethodDeclaration))
  10280. {
  10281. if (ctorDecl->mThisToken != NULL)
  10282. closureHashCtx.Mixin(ctorDecl->mThisToken->GetStartCharId());
  10283. }
  10284. }
  10285. auto checkMethodState = mModule->mCurMethodState;
  10286. while (checkMethodState != NULL)
  10287. {
  10288. if (checkMethodState->mMethodInstance != NULL)
  10289. {
  10290. if (checkMethodState->mMethodInstance->mMethodInfoEx != NULL)
  10291. {
  10292. for (auto methodGenericArg : checkMethodState->mMethodInstance->mMethodInfoEx->mMethodGenericArguments)
  10293. {
  10294. StringT<128> genericTypeName;
  10295. BfMangler::Mangle(genericTypeName, mModule->mCompiler->GetMangleKind(), methodGenericArg);
  10296. closureHashCtx.MixinStr(genericTypeName);
  10297. }
  10298. }
  10299. }
  10300. checkMethodState = checkMethodState->mPrevMethodState;
  10301. }
  10302. uint64 closureHash = closureHashCtx.Finish64();
  10303. methodDef->mName += "$";
  10304. methodDef->mName += BfTypeUtils::HashEncode64(closureHash);
  10305. methodInstance->mMethodDef = methodDef;
  10306. if (invokeMethodInstance != NULL)
  10307. {
  10308. methodInstance->mParams = invokeMethodInstance->mParams;
  10309. methodInstance->mReturnType = invokeMethodInstance->mReturnType;
  10310. }
  10311. else
  10312. methodInstance->mReturnType = mModule->GetPrimitiveType(BfTypeCode_None);
  10313. StringT<128> closureFuncName;
  10314. BfMangler::Mangle(closureFuncName, mModule->mCompiler->GetMangleKind(), methodInstance);
  10315. auto closureFunc = mModule->mBfIRBuilder->CreateFunction(closureFuncType, BfIRLinkageType_External, closureFuncName);
  10316. methodInstance->mIRFunction = closureFunc;
  10317. if (methodInstance->mIsReified)
  10318. mModule->CheckHotMethod(methodInstance, closureFuncName);
  10319. if ((methodInstance->mHotMethod != NULL) && (mModule->mCurMethodState->mHotDataReferenceBuilder))
  10320. mModule->mCurMethodState->mHotDataReferenceBuilder->mInnerMethods.Add(methodInstance->mHotMethod);
  10321. methodState.Reset();
  10322. lambdaInstance = new BfLambdaInstance();
  10323. rootMethodState->mLambdaCache[cacheNodeList] = lambdaInstance;
  10324. lambdaInstance->mDelegateTypeInstance = delegateTypeInstance;
  10325. lambdaInstance->mUseTypeInstance = useTypeInstance;
  10326. lambdaInstance->mClosureTypeInstance = closureTypeInst;
  10327. lambdaInstance->mOuterClosure = outerClosure;
  10328. lambdaInstance->mCopyOuterCaptures = copyOuterCaptures;
  10329. lambdaInstance->mDeclaringMethodIsMutating = mModule->mCurMethodInstance->mMethodDef->mIsMutating;
  10330. lambdaInstance->mIsStatic = methodDef->mIsStatic;
  10331. lambdaInstance->mClosureFunc = closureFunc;
  10332. lambdaInstance->mMethodInstance = methodInstance;
  10333. lambdaInstance->mConstLocals = closureState.mConstLocals;
  10334. lambdaInstance->mParamDecls = tempParamDecls;
  10335. lambdaInstance->mDeclMixinState = mModule->mCurMethodState->mMixinState;
  10336. if (lambdaInstance->mDeclMixinState != NULL)
  10337. lambdaInstance->mDeclMixinState->mHasDeferredUsage = true;
  10338. tempParamDecls.ClearWithoutDeleting();
  10339. closureState.mCapturing = false;
  10340. closureState.mClosureType = useTypeInstance;
  10341. closureInstanceInfo->mThisOverride = useTypeInstance;
  10342. mModule->mIncompleteMethodCount++;
  10343. SetAndRestoreValue<BfClosureState*> prevClosureState(mModule->mCurMethodState->mClosureState, &closureState);
  10344. if (mModule->HasCompiledOutput())
  10345. mModule->SetupIRMethod(methodInstance, methodInstance->mIRFunction, methodInstance->mAlwaysInline);
  10346. // This keeps us from giving errors twice. ProcessMethod can give errors when we capture by value but needed to
  10347. // capture by reference, so we still need to do it for resolve-only
  10348. bool processMethods = (mModule->mCompiler->GetAutoComplete() == NULL) && !mModule->mHadBuildError;
  10349. mModule->mBfIRBuilder->SaveDebugLocation();
  10350. //
  10351. {
  10352. BfGetSymbolReferenceKind prevSymbolRefKind = BfGetSymbolReferenceKind_None;
  10353. if (mModule->mCompiler->mResolvePassData != NULL)
  10354. {
  10355. prevSymbolRefKind = mModule->mCompiler->mResolvePassData->mGetSymbolReferenceKind;
  10356. mModule->mCompiler->mResolvePassData->mGetSymbolReferenceKind = BfGetSymbolReferenceKind_None;
  10357. }
  10358. if (processMethods)
  10359. {
  10360. // If we are in an always-ignored block, we will have mIgnoreWrites set
  10361. // SetAndRestoreValue<bool> prevWantsIgnoreWrite(mModule->mWantsIRIgnoreWrites, mModule->mBfIRBuilder->mIgnoreWrites);
  10362. // mModule->ProcessMethod(methodInstance);
  10363. }
  10364. if (mModule->mCompiler->mResolvePassData != NULL)
  10365. mModule->mCompiler->mResolvePassData->mGetSymbolReferenceKind = prevSymbolRefKind;
  10366. }
  10367. mModule->mBfIRBuilder->RestoreDebugLocation();
  10368. if (mModule->IsSkippingExtraResolveChecks())
  10369. closureFunc = BfIRFunction();
  10370. BfIRFunction dtorFunc;
  10371. if (lambdaBindExpr->mDtor != NULL)
  10372. {
  10373. SizedArray<BfIRType, 1> newTypes;
  10374. newTypes.push_back(mModule->mBfIRBuilder->MapType(useTypeInstance));
  10375. auto voidType = mModule->GetPrimitiveType(BfTypeCode_None);
  10376. auto dtorFuncType = mModule->mBfIRBuilder->CreateFunctionType(mModule->mBfIRBuilder->MapType(voidType), newTypes, false);
  10377. BfMethodDef* dtorMethodDef = new BfMethodDef();
  10378. dtorMethodDef->mDeclaringType = mModule->mCurMethodInstance->mMethodDef->mDeclaringType;
  10379. dtorMethodDef->mName = "~this$";
  10380. dtorMethodDef->mName += methodDef->mName;
  10381. dtorMethodDef->mMethodType = BfMethodType_Normal;
  10382. dtorMethodDef->mBody = lambdaBindExpr->mDtor;
  10383. dtorMethodDef->mIdx = mModule->mCurMethodInstance->mMethodDef->mIdx;
  10384. BfMethodInstance* dtorMethodInstance = new BfMethodInstance();
  10385. dtorMethodInstance->mMethodDef = dtorMethodDef;
  10386. dtorMethodInstance->mReturnType = mModule->GetPrimitiveType(BfTypeCode_None);
  10387. dtorMethodInstance->mMethodInstanceGroup = &methodInstanceGroup;
  10388. StringT<128> dtorMangledName;
  10389. BfMangler::Mangle(dtorMangledName, mModule->mCompiler->GetMangleKind(), dtorMethodInstance);
  10390. dtorFunc = mModule->mBfIRBuilder->CreateFunction(dtorFuncType, BfIRLinkageType_External, dtorMangledName);
  10391. mModule->SetupIRMethod(NULL, dtorFunc, false);
  10392. dtorMethodInstance->mIRFunction = dtorFunc;
  10393. mModule->mIncompleteMethodCount++;
  10394. mModule->mBfIRBuilder->SaveDebugLocation();
  10395. //
  10396. if (processMethods)
  10397. {
  10398. // If we are in an always-ignored block, we will have mIgnoreWrites set
  10399. // SetAndRestoreValue<bool> prevWantsIgnoreWrite(mModule->mWantsIRIgnoreWrites, mModule->mBfIRBuilder->mIgnoreWrites);
  10400. // mModule->ProcessMethod(dtorMethodInstance);
  10401. }
  10402. mModule->mBfIRBuilder->RestoreDebugLocation();
  10403. if (mModule->IsSkippingExtraResolveChecks())
  10404. dtorFunc = BfIRFunction();
  10405. if (dtorMethodInstance->mIsReified)
  10406. mModule->CheckHotMethod(dtorMethodInstance, dtorMangledName);
  10407. if ((dtorMethodInstance->mHotMethod != NULL) && (mModule->mCurMethodState->mHotDataReferenceBuilder))
  10408. mModule->mCurMethodState->mHotDataReferenceBuilder->mInnerMethods.Add(dtorMethodInstance->mHotMethod);
  10409. lambdaInstance->mDtorMethodInstance = dtorMethodInstance;
  10410. lambdaInstance->mDtorFunc = dtorFunc;
  10411. }
  10412. prevClosureState.Restore();
  10413. if (!prevInsertBlock.IsFake())
  10414. mModule->mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  10415. for (auto& capturedEntry : capturedEntries)
  10416. {
  10417. BfLambdaCaptureInfo lambdaCapture;
  10418. if (capturedEntry.mName == "__this")
  10419. lambdaCapture.mName = "this";
  10420. else
  10421. lambdaCapture.mName = capturedEntry.mName;
  10422. lambdaInstance->mCaptures.Add(lambdaCapture);
  10423. closureInstanceInfo->mCaptureEntries.Add(capturedEntry);
  10424. }
  10425. if (processMethods)
  10426. rootMethodState->mDeferredLambdaInstances.Add(lambdaInstance);
  10427. methodInstance->mMethodInstanceGroup = NULL;
  10428. return lambdaInstance;
  10429. }
  10430. void BfExprEvaluator::Visit(BfLambdaBindExpression* lambdaBindExpr)
  10431. {
  10432. BfTokenNode* newToken = NULL;
  10433. BfAllocTarget allocTarget = ResolveAllocTarget(lambdaBindExpr->mNewToken, newToken);
  10434. if ((mModule->mCurMethodState != NULL) && (mModule->mCurMethodState->mClosureState != NULL) && (mModule->mCurMethodState->mClosureState->mBlindCapturing))
  10435. {
  10436. // We're just capturing. We just need to visit the bodies here. This helps infinite recursion with local methods containing lambdas calling each other
  10437. if (lambdaBindExpr->mBody != NULL)
  10438. mModule->VisitChild(lambdaBindExpr->mBody);
  10439. if ((lambdaBindExpr->mDtor != NULL) && (lambdaBindExpr->mDtor->mBody != NULL))
  10440. mModule->VisitChild(lambdaBindExpr->mDtor->mBody);
  10441. return;
  10442. }
  10443. BfLambdaInstance* lambdaInstance = GetLambdaInstance(lambdaBindExpr, allocTarget);
  10444. if (lambdaInstance == NULL)
  10445. return;
  10446. BfTypeInstance* delegateTypeInstance = lambdaInstance->mDelegateTypeInstance;
  10447. BfTypeInstance* useTypeInstance = lambdaInstance->mUseTypeInstance;
  10448. BfTypeInstance* closureTypeInst = lambdaInstance->mClosureTypeInstance;
  10449. mResult = BfTypedValue(mModule->AllocFromType(useTypeInstance, allocTarget, BfIRValue(), BfIRValue(), 0, BfAllocFlags_None), useTypeInstance);
  10450. if (!delegateTypeInstance->IsDelegate())
  10451. {
  10452. mModule->AssertErrorState();
  10453. return;
  10454. }
  10455. auto baseDelegateType = VerifyBaseDelegateType(delegateTypeInstance->mBaseType);
  10456. if (baseDelegateType == NULL)
  10457. {
  10458. mModule->Fail("Invalid delegate type", lambdaBindExpr);
  10459. return;
  10460. }
  10461. auto baseDelegate = mModule->mBfIRBuilder->CreateBitCast(mResult.mValue, mModule->mBfIRBuilder->MapType(baseDelegateType));
  10462. // >> delegate.mTarget = bindResult.mTarget
  10463. auto nullPtrType = mModule->GetPrimitiveType(BfTypeCode_NullPtr);
  10464. BfIRValue valPtr;
  10465. if (!lambdaInstance->mIsStatic)
  10466. valPtr = mModule->mBfIRBuilder->CreateBitCast(mResult.mValue, mModule->mBfIRBuilder->MapType(nullPtrType));
  10467. else
  10468. valPtr = mModule->GetDefaultValue(nullPtrType);
  10469. auto fieldPtr = mModule->mBfIRBuilder->CreateInBoundsGEP(baseDelegate, 0, 2);
  10470. mModule->mBfIRBuilder->CreateStore(valPtr, fieldPtr);
  10471. // >> delegate.mFuncPtr = bindResult.mFunc
  10472. if (lambdaInstance->mClosureFunc)
  10473. {
  10474. auto nullPtrType = mModule->GetPrimitiveType(BfTypeCode_NullPtr);
  10475. auto valPtr = mModule->mBfIRBuilder->CreateBitCast(lambdaInstance->mClosureFunc, mModule->mBfIRBuilder->MapType(nullPtrType));
  10476. auto fieldPtr = mModule->mBfIRBuilder->CreateInBoundsGEP(baseDelegate, 0, 1);
  10477. mModule->mBfIRBuilder->CreateStore(valPtr, fieldPtr);
  10478. }
  10479. mModule->AddDependency(useTypeInstance, mModule->mCurTypeInstance, BfDependencyMap::DependencyFlag_Calls);
  10480. // Copy captures into the delegate
  10481. if (lambdaInstance->mClosureTypeInstance != NULL)
  10482. {
  10483. int fieldIdx = 0;
  10484. if (lambdaInstance->mCopyOuterCaptures)
  10485. {
  10486. for (auto& fieldInstance : lambdaInstance->mOuterClosure->mFieldInstances)
  10487. {
  10488. if (!fieldInstance.mResolvedType->IsValuelessType())
  10489. {
  10490. BF_ASSERT(fieldInstance.mDataIdx == fieldIdx + 1);
  10491. auto localVar = mModule->mCurMethodState->mLocals[0];
  10492. auto capturedValue = mModule->mBfIRBuilder->CreateInBoundsGEP(localVar->mValue, 0, fieldInstance.mDataIdx);
  10493. capturedValue = mModule->mBfIRBuilder->CreateLoad(capturedValue);
  10494. auto fieldPtr = mModule->mBfIRBuilder->CreateInBoundsGEP(mResult.mValue, 0, fieldInstance.mDataIdx);
  10495. mModule->mBfIRBuilder->CreateStore(capturedValue, fieldPtr);
  10496. fieldIdx++;
  10497. }
  10498. }
  10499. }
  10500. int captureIdx = 0;
  10501. for (int captureIdx = 0; captureIdx < (int)lambdaInstance->mCaptures.size(); captureIdx++)
  10502. {
  10503. auto& capturedEntry = lambdaInstance->mCaptures[captureIdx];
  10504. auto& closureCaptureEntry = lambdaInstance->mMethodInstance->mMethodInfoEx->mClosureInstanceInfo->mCaptureEntries[captureIdx];
  10505. BfIdentifierNode* identifierNode = closureCaptureEntry.mNameNode;
  10506. BfIRValue capturedValue;
  10507. auto fieldInstance = &closureTypeInst->mFieldInstances[fieldIdx];
  10508. BfTypedValue capturedTypedVal;
  10509. if (identifierNode != NULL)
  10510. capturedTypedVal = DoImplicitArgCapture(NULL, identifierNode, closureCaptureEntry.mShadowIdx);
  10511. else
  10512. capturedTypedVal = LookupIdentifier(NULL, capturedEntry.mName);
  10513. if (!fieldInstance->mResolvedType->IsRef())
  10514. capturedTypedVal = mModule->LoadOrAggregateValue(capturedTypedVal);
  10515. else if (!capturedTypedVal.IsAddr())
  10516. {
  10517. mModule->Fail(StrFormat("Unable to capture '%s' by reference", capturedEntry.mName.c_str()), lambdaBindExpr);
  10518. break;
  10519. }
  10520. capturedValue = capturedTypedVal.mValue;
  10521. if (capturedValue)
  10522. {
  10523. if (!capturedTypedVal.mType->IsVar())
  10524. {
  10525. auto fieldPtr = mModule->mBfIRBuilder->CreateInBoundsGEP(mResult.mValue, 0, fieldInstance->mDataIdx);
  10526. mModule->mBfIRBuilder->CreateStore(capturedValue, fieldPtr);
  10527. }
  10528. }
  10529. else
  10530. {
  10531. mModule->Fail(StrFormat("Unable to capture '%s'", capturedEntry.mName.c_str()), lambdaBindExpr);
  10532. mModule->AssertErrorState();
  10533. }
  10534. fieldIdx++;
  10535. }
  10536. if (lambdaInstance->mDtorFunc)
  10537. {
  10538. auto fieldPtr = mModule->mBfIRBuilder->CreateInBoundsGEP(mResult.mValue, 0, closureTypeInst->mFieldInstances[fieldIdx].mDataIdx);
  10539. auto voidType = mModule->GetPrimitiveType(BfTypeCode_None);
  10540. auto voidPtrType = mModule->CreatePointerType(voidType);
  10541. auto dtorThunk = mModule->mBfIRBuilder->CreateBitCast(lambdaInstance->mDtorFunc, mModule->mBfIRBuilder->MapType(voidPtrType));
  10542. mModule->mBfIRBuilder->CreateStore(dtorThunk, fieldPtr);
  10543. fieldIdx++;
  10544. }
  10545. }
  10546. }
  10547. void BfExprEvaluator::ProcessArrayInitializer(BfTokenNode* openToken, const BfSizedArray<BfExpression*>& valueExprs, const BfSizedArray<BfTokenNode*>& commas, BfTokenNode* closeToken, int dimensions, SizedArrayImpl<int64>& dimLengths, int dim, bool& hasFailed)
  10548. {
  10549. bool setSize = false;
  10550. if (dim == dimLengths.size())
  10551. {
  10552. dimLengths.push_back((int)valueExprs.size());
  10553. setSize = true;
  10554. }
  10555. else if (dimLengths[dim] == -1)
  10556. {
  10557. dimLengths[dim] = (int)valueExprs.size();
  10558. setSize = true;
  10559. }
  10560. int64 initCountDiff = (int)valueExprs.size() - dimLengths[dim];
  10561. if ((dimLengths[dim] != -1) && (initCountDiff != 0) && (!hasFailed))
  10562. {
  10563. if (initCountDiff > 0)
  10564. {
  10565. mModule->Fail(StrFormat("Too many initializers, expected %d fewer", initCountDiff), valueExprs[(int)dimLengths[dim]]);
  10566. hasFailed = true;
  10567. }
  10568. else
  10569. {
  10570. // If it ends with ", ?) or ",)" then allow unsized
  10571. if (((valueExprs.size() == 0) || (BfNodeDynCast<BfUninitializedExpression>(valueExprs.back()) == NULL)) &&
  10572. (commas.size() < valueExprs.size()))
  10573. {
  10574. BfAstNode* refNode = closeToken;
  10575. if ((refNode == NULL) && (mModule->mParentNodeEntry != NULL))
  10576. refNode = mModule->mParentNodeEntry->mNode;
  10577. mModule->Fail(StrFormat("Too few initializer, expected %d more", -initCountDiff), refNode);
  10578. hasFailed = true;
  10579. }
  10580. }
  10581. }
  10582. for (int i = 0; i < (int)valueExprs.size(); i++)
  10583. {
  10584. BfExpression* expr = valueExprs[i];
  10585. if (auto uninitExpr = BfNodeDynCast<BfUninitializedExpression>(expr))
  10586. {
  10587. continue;
  10588. }
  10589. auto innerInitExpr = BfNodeDynCast<BfCollectionInitializerExpression>(expr);
  10590. if (dim < dimensions - 1)
  10591. {
  10592. if (innerInitExpr == NULL)
  10593. {
  10594. if (auto innerTupleExpr = BfNodeDynCast<BfTupleExpression>(expr))
  10595. {
  10596. ProcessArrayInitializer(innerTupleExpr->mOpenParen, innerTupleExpr->mValues, innerTupleExpr->mCommas, innerTupleExpr->mCloseParen, dimensions, dimLengths, dim + 1, hasFailed);
  10597. }
  10598. else if (auto parenExpr = BfNodeDynCast<BfParenthesizedExpression>(expr))
  10599. {
  10600. SizedArray<BfExpression*, 1> values;
  10601. values.Add(parenExpr->mExpression);
  10602. SizedArray<BfTokenNode*, 1> commas;
  10603. ProcessArrayInitializer(parenExpr->mOpenParen, values, commas, parenExpr->mCloseParen, dimensions, dimLengths, dim + 1, hasFailed);
  10604. }
  10605. else
  10606. {
  10607. hasFailed = true;
  10608. mModule->Fail("A nested array initializer is expected", expr);
  10609. continue;
  10610. }
  10611. }
  10612. else
  10613. ProcessArrayInitializer(innerInitExpr->mOpenBrace, innerInitExpr->mValues, innerInitExpr->mCommas, innerInitExpr->mCloseBrace, dimensions, dimLengths, dim + 1, hasFailed);
  10614. }
  10615. else if (innerInitExpr != NULL)
  10616. {
  10617. hasFailed = true;
  10618. mModule->Fail("Unexpected nested initializer", expr);
  10619. ProcessArrayInitializer(innerInitExpr->mOpenBrace, innerInitExpr->mValues, innerInitExpr->mCommas, innerInitExpr->mCloseBrace, dimensions, dimLengths, dim + 1, hasFailed);
  10620. }
  10621. else
  10622. {
  10623. //mModule->Fail("Expected initializer", )
  10624. }
  10625. }
  10626. }
  10627. void BfExprEvaluator::CheckObjectCreateTypeRef(BfType* expectingType, BfAstNode* afterNode)
  10628. {
  10629. auto autoComplete = GetAutoComplete();
  10630. if ((autoComplete != NULL) && (afterNode != NULL) && (autoComplete->mIsAutoComplete) &&
  10631. (afterNode->IsFromParser(mModule->mCompiler->mResolvePassData->mParser)) &&
  10632. (afterNode->GetParser()->mCursorIdx == afterNode->GetSrcEnd() + 1))
  10633. {
  10634. BfType* expectingType = mExpectingType;
  10635. BfTypeInstance* expectingTypeInst = NULL;
  10636. if (mExpectingType != NULL)
  10637. {
  10638. expectingTypeInst = mExpectingType->ToTypeInstance();
  10639. }
  10640. if ((mExpectingType != NULL) && (((expectingTypeInst == NULL) || (!expectingTypeInst->mTypeDef->mIsDelegate))))
  10641. {
  10642. // Why were we doing this? It floods the autocomplete with every possible type
  10643. //autoComplete->AddTopLevelTypes(NULL);
  10644. autoComplete->mInsertStartIdx = afterNode->GetSourceData()->ToParser()->mCursorIdx;
  10645. BF_ASSERT(autoComplete->mInsertStartIdx != -1);
  10646. auto expectingType = mExpectingType;
  10647. while (expectingType->IsArray())
  10648. {
  10649. auto arrayType = (BfArrayType*)expectingType;
  10650. expectingType = arrayType->mGenericTypeInfo->mTypeGenericArguments[0];
  10651. }
  10652. auto expectingTypeInst = expectingType->ToTypeInstance();
  10653. if (expectingTypeInst != NULL)
  10654. {
  10655. autoComplete->AddTypeInstanceEntry(expectingTypeInst);
  10656. }
  10657. else
  10658. autoComplete->mDefaultSelection = mModule->TypeToString(expectingType);
  10659. }
  10660. }
  10661. }
  10662. void BfExprEvaluator::Visit(BfObjectCreateExpression* objCreateExpr)
  10663. {
  10664. CreateObject(objCreateExpr, objCreateExpr->mNewNode, NULL);
  10665. }
  10666. void BfExprEvaluator::CreateObject(BfObjectCreateExpression* objCreateExpr, BfAstNode* allocNode, BfType* wantAllocType)
  10667. {
  10668. auto autoComplete = GetAutoComplete();
  10669. if ((autoComplete != NULL) && (objCreateExpr != NULL) && (objCreateExpr->mTypeRef != NULL))
  10670. {
  10671. autoComplete->CheckTypeRef(objCreateExpr->mTypeRef, false, true);
  10672. }
  10673. if ((autoComplete != NULL) && (objCreateExpr != NULL) && (objCreateExpr->mOpenToken != NULL) && (objCreateExpr->mCloseToken != NULL) &&
  10674. (objCreateExpr->mOpenToken->mToken == BfToken_LBrace) && (autoComplete->CheckFixit(objCreateExpr->mOpenToken)))
  10675. {
  10676. auto refNode = objCreateExpr->mOpenToken;
  10677. BfParserData* parser = refNode->GetSourceData()->ToParserData();
  10678. if (parser != NULL)
  10679. {
  10680. autoComplete->AddEntry(AutoCompleteEntry("fixit", StrFormat("Change initializer braces to parentheses\treformat|%s|%d-1|(\x01|%s|%d-1|)",
  10681. parser->mFileName.c_str(), refNode->mSrcStart,
  10682. parser->mFileName.c_str(), objCreateExpr->mCloseToken->mSrcStart).c_str()));
  10683. }
  10684. }
  10685. CheckObjectCreateTypeRef(mExpectingType, allocNode);
  10686. BfAttributeState attributeState;
  10687. attributeState.mTarget = BfAttributeTargets_Alloc;
  10688. SetAndRestoreValue<BfAttributeState*> prevAttributeState(mModule->mAttributeState, &attributeState);
  10689. BfTokenNode* newToken = NULL;
  10690. BfAllocTarget allocTarget = ResolveAllocTarget(allocNode, newToken, &attributeState.mCustomAttributes);
  10691. bool isScopeAlloc = newToken->GetToken() == BfToken_Scope;
  10692. bool isAppendAlloc = newToken->GetToken() == BfToken_Append;
  10693. bool isStackAlloc = (newToken->GetToken() == BfToken_Stack) || (isScopeAlloc);
  10694. bool isArrayAlloc = false;// (objCreateExpr->mArraySizeSpecifier != NULL);
  10695. bool isRawArrayAlloc = (objCreateExpr != NULL) && (objCreateExpr->mStarToken != NULL);
  10696. if (isScopeAlloc)
  10697. {
  10698. if ((mBfEvalExprFlags & BfEvalExprFlags_FieldInitializer) != 0)
  10699. {
  10700. mModule->Warn(0, "This allocation will only be in scope during the constructor. Consider using a longer-term allocation such as 'new'", allocNode);
  10701. }
  10702. if (allocNode == newToken) // Scope, no target specified
  10703. {
  10704. if (mModule->mParentNodeEntry != NULL)
  10705. {
  10706. if (auto assignExpr = BfNodeDynCastExact<BfAssignmentExpression>(mModule->mParentNodeEntry->mNode))
  10707. {
  10708. if (mModule->mCurMethodState->mCurScope->mCloseNode == NULL)
  10709. {
  10710. // 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
  10711. if ((mBfEvalExprFlags & BfEvalExprFlags_PendingPropSet) == 0)
  10712. mModule->Warn(0, "This allocation will immediately go out of scope. Consider specifying a wider scope target such as 'scope::'", allocNode);
  10713. }
  10714. }
  10715. }
  10716. }
  10717. }
  10718. BfAutoParentNodeEntry autoParentNodeEntry(mModule, objCreateExpr);
  10719. SizedArray<BfAstNode*, 2> dimLengthRefs;
  10720. SizedArray<BfIRValue, 2> dimLengthVals;
  10721. BfArrayType* arrayType = NULL;
  10722. BfType* unresolvedTypeRef = NULL;
  10723. BfType* resolvedTypeRef = NULL;
  10724. if (wantAllocType != NULL)
  10725. {
  10726. unresolvedTypeRef = wantAllocType;
  10727. resolvedTypeRef = wantAllocType;
  10728. }
  10729. else if (objCreateExpr->mTypeRef == NULL)
  10730. {
  10731. if ((!mExpectingType) || (!mExpectingType->IsArray()))
  10732. {
  10733. mModule->Fail("Cannot imply array type. Explicitly state array type or use array in an assignment to an array type.", objCreateExpr);
  10734. resolvedTypeRef = mModule->mContext->mBfObjectType;
  10735. unresolvedTypeRef = resolvedTypeRef;
  10736. }
  10737. else
  10738. {
  10739. auto arrayType = (BfArrayType*)mExpectingType;
  10740. unresolvedTypeRef = arrayType->GetUnderlyingType();
  10741. resolvedTypeRef = unresolvedTypeRef;
  10742. }
  10743. }
  10744. else
  10745. {
  10746. if ((objCreateExpr->mTypeRef->IsExact<BfDotTypeReference>()) && (mExpectingType != NULL))
  10747. {
  10748. //mModule->SetElementType(objCreateExpr->mTypeRef, BfSourceElementType_TypeRef);
  10749. if ((mExpectingType->IsObject()) || (mExpectingType->IsGenericParam()))
  10750. {
  10751. unresolvedTypeRef = mExpectingType;
  10752. if (unresolvedTypeRef->IsArray())
  10753. {
  10754. arrayType = (BfArrayType*)unresolvedTypeRef;
  10755. unresolvedTypeRef = unresolvedTypeRef->GetUnderlyingType();
  10756. isArrayAlloc = true;
  10757. }
  10758. }
  10759. else if (mExpectingType->IsPointer())
  10760. {
  10761. unresolvedTypeRef = mExpectingType->GetUnderlyingType();
  10762. }
  10763. }
  10764. if (unresolvedTypeRef == NULL)
  10765. {
  10766. if (auto arrayTypeRef = BfNodeDynCast<BfArrayTypeRef>(objCreateExpr->mTypeRef))
  10767. {
  10768. isArrayAlloc = true;
  10769. if (auto dotTypeRef = BfNodeDynCast<BfDotTypeReference>(arrayTypeRef->mElementType))
  10770. {
  10771. if ((mExpectingType != NULL) &&
  10772. ((mExpectingType->IsArray()) || (mExpectingType->IsPointer()) || (mExpectingType->IsSizedArray())))
  10773. unresolvedTypeRef = mExpectingType->GetUnderlyingType();
  10774. }
  10775. if (unresolvedTypeRef == NULL)
  10776. unresolvedTypeRef = mModule->ResolveTypeRef(arrayTypeRef->mElementType);
  10777. if (unresolvedTypeRef == NULL)
  10778. unresolvedTypeRef = mModule->mContext->mBfObjectType;
  10779. int dimensions = 1;
  10780. bool commaExpected = false;
  10781. if (arrayTypeRef->mParams.size() != 0)
  10782. {
  10783. auto intType = mModule->ResolveTypeDef(mModule->mSystem->mTypeIntPtr);
  10784. for (auto arg : arrayTypeRef->mParams)
  10785. {
  10786. if (auto tokenNode = BfNodeDynCastExact<BfTokenNode>(arg))
  10787. {
  10788. if (tokenNode->GetToken() == BfToken_Comma)
  10789. {
  10790. if (isRawArrayAlloc)
  10791. {
  10792. mModule->Fail("Sized arrays cannot be multidimensional.", tokenNode);
  10793. continue;
  10794. }
  10795. dimensions++;
  10796. if (dimensions == 5)
  10797. {
  10798. mModule->Fail("Too many array dimensions, consider using a jagged array.", tokenNode);
  10799. }
  10800. commaExpected = false;
  10801. continue;
  10802. }
  10803. }
  10804. auto expr = BfNodeDynCast<BfExpression>(arg);
  10805. if ((isRawArrayAlloc) && (!dimLengthVals.IsEmpty()))
  10806. {
  10807. mModule->CreateValueFromExpression(expr, intType);
  10808. continue;
  10809. }
  10810. dimLengthRefs.Add(expr);
  10811. BfTypedValue dimLength;
  10812. if (expr == NULL)
  10813. {
  10814. // Not specified
  10815. dimLengthVals.push_back(BfIRValue());
  10816. continue;
  10817. }
  10818. if (arg != NULL)
  10819. {
  10820. dimLength = mModule->CreateValueFromExpression(expr, intType, BfEvalExprFlags_NoCast);
  10821. BfCastFlags castFlags = BfCastFlags_None;
  10822. if ((dimLength) && (dimLength.mType->IsInteger()))
  10823. {
  10824. // Allow uint for size - just force to int
  10825. if (!((BfPrimitiveType*)dimLength.mType)->IsSigned())
  10826. castFlags = BfCastFlags_Explicit;
  10827. }
  10828. if (dimLength)
  10829. dimLength = mModule->Cast(expr, dimLength, intType, castFlags);
  10830. }
  10831. if (commaExpected)
  10832. {
  10833. mModule->AssertErrorState();
  10834. continue;
  10835. }
  10836. if (!dimLength)
  10837. {
  10838. dimLength = mModule->GetDefaultTypedValue(intType);
  10839. }
  10840. dimLengthVals.push_back(dimLength.mValue);
  10841. commaExpected = true;
  10842. }
  10843. }
  10844. if ((arrayTypeRef->mParams.size() == 0) && (objCreateExpr->mOpenToken == NULL))
  10845. mModule->Fail("Array size or array initializer expected", arrayTypeRef->mOpenBracket);
  10846. if (dimensions > 4)
  10847. dimensions = 4;
  10848. if (!isRawArrayAlloc)
  10849. arrayType = mModule->CreateArrayType(unresolvedTypeRef, dimensions);
  10850. }
  10851. if (unresolvedTypeRef == NULL)
  10852. {
  10853. unresolvedTypeRef = ResolveTypeRef(objCreateExpr->mTypeRef, BfPopulateType_Declaration, BfResolveTypeRefFlag_NoResolveGenericParam);
  10854. }
  10855. }
  10856. resolvedTypeRef = unresolvedTypeRef;
  10857. if ((resolvedTypeRef != NULL) && (resolvedTypeRef->IsVar()))
  10858. resolvedTypeRef = unresolvedTypeRef;
  10859. }
  10860. if (resolvedTypeRef == NULL)
  10861. {
  10862. unresolvedTypeRef = mModule->GetPrimitiveType(BfTypeCode_Var);
  10863. resolvedTypeRef = unresolvedTypeRef;
  10864. }
  10865. auto resultType = resolvedTypeRef;
  10866. if ((resolvedTypeRef->IsInterface()) && (!isArrayAlloc))
  10867. {
  10868. mModule->Fail("Cannot create an instance of an interface", objCreateExpr->mTypeRef);
  10869. resolvedTypeRef = mModule->mContext->mBfObjectType;
  10870. }
  10871. BfTypeInstance* typeInstance = resolvedTypeRef->ToTypeInstance();
  10872. int elementSize = resolvedTypeRef->mSize;
  10873. int elementAlign = resolvedTypeRef->mAlign;
  10874. BfIRType allocType = mModule->mBfIRBuilder->MapType(resolvedTypeRef);
  10875. if (typeInstance != NULL)
  10876. {
  10877. if (!mModule->mCurTypeInstance->mResolvingVarField)
  10878. mModule->PopulateType(typeInstance);
  10879. if ((typeInstance->mTypeDef->mIsDelegate) && (!isArrayAlloc))
  10880. mModule->Fail("Delegates must be constructed through delegate binding", objCreateExpr->mTypeRef);
  10881. elementSize = BF_MAX(0, typeInstance->mInstSize);
  10882. elementAlign = typeInstance->mInstAlign;
  10883. allocType = mModule->mBfIRBuilder->MapTypeInst(typeInstance);
  10884. }
  10885. if (isAppendAlloc)
  10886. {
  10887. if (!mModule->mCurTypeInstance->IsObject())
  10888. {
  10889. mModule->Fail("Append allocations are only allowed in classes", allocNode);
  10890. isAppendAlloc = false;
  10891. }
  10892. else if ((mBfEvalExprFlags & BfEvalExprFlags_VariableDeclaration) == 0)
  10893. {
  10894. mModule->Fail("Append allocations are only allowed as local variable initializers in constructor body", allocNode);
  10895. isAppendAlloc = false;
  10896. }
  10897. else
  10898. {
  10899. auto methodDef = mModule->mCurMethodInstance->mMethodDef;
  10900. if (methodDef->mMethodType == BfMethodType_CtorCalcAppend)
  10901. {
  10902. mModule->Fail("Append allocations are only allowed as local variable declarations in the main method body", allocNode);
  10903. isAppendAlloc = false;
  10904. }
  10905. else if (!methodDef->mHasAppend)
  10906. {
  10907. mModule->Fail("Append allocations can only be used on constructors with [AllowAppend] specified", allocNode);
  10908. isAppendAlloc = false;
  10909. }
  10910. else if (methodDef->mMethodType != BfMethodType_Ctor)
  10911. {
  10912. mModule->Fail("Append allocations are only allowed in constructors", allocNode);
  10913. isAppendAlloc = false;
  10914. }
  10915. else if (methodDef->mIsStatic)
  10916. {
  10917. mModule->Fail("Append allocations are only allowed in non-static constructors", allocNode);
  10918. isAppendAlloc = false;
  10919. }
  10920. }
  10921. }
  10922. if (isArrayAlloc)
  10923. {
  10924. const int MAX_DIMENSIONS = 2;
  10925. int dimensions = 1;
  10926. if (arrayType != NULL)
  10927. {
  10928. dimensions = arrayType->mDimensions;
  10929. mModule->AddDependency(arrayType, mModule->mCurTypeInstance, BfDependencyMap::DependencyFlag_Calls);
  10930. }
  10931. bool zeroMemory = true;
  10932. if (objCreateExpr->mOpenToken != NULL)
  10933. {
  10934. if ((objCreateExpr->mArguments.size() == 1) &&
  10935. (BfNodeDynCastExact<BfUninitializedExpression>(objCreateExpr->mArguments[0]) != NULL))
  10936. {
  10937. // Special case for a single "{ ? }"
  10938. zeroMemory = false;
  10939. }
  10940. else
  10941. {
  10942. SizedArray<int64, 2> dimLengths;
  10943. if (dimLengthVals.size() != 0)
  10944. {
  10945. for (int dim = 0; dim < dimensions; dim++)
  10946. {
  10947. BfIRValue dimLengthVal;
  10948. if (dim < (int)dimLengthVals.size())
  10949. dimLengthVal = dimLengthVals[dim];
  10950. if (!dimLengthVal)
  10951. {
  10952. dimLengths.push_back(-1);
  10953. continue;
  10954. }
  10955. auto constant = mModule->mBfIRBuilder->GetConstant(dimLengthVal);
  10956. if ((constant != NULL) && (mModule->mBfIRBuilder->IsInt(constant->mTypeCode)))
  10957. {
  10958. int64 dimLength = constant->mInt64;
  10959. dimLengths.push_back(dimLength);
  10960. }
  10961. else
  10962. {
  10963. mModule->Fail("A constant length is required when using an initializer", dimLengthRefs[dim]);
  10964. dimLengths.push_back(-1);
  10965. }
  10966. }
  10967. }
  10968. // Ending in an ", )" means we need to zero-fill ending
  10969. zeroMemory = objCreateExpr->mCommas.size() >= objCreateExpr->mArguments.size();
  10970. bool hasFailed = false;
  10971. ProcessArrayInitializer(objCreateExpr->mOpenToken, objCreateExpr->mArguments, objCreateExpr->mCommas, objCreateExpr->mCloseToken, dimensions, dimLengths, 0, hasFailed);
  10972. dimLengthVals.resize(dimLengths.size());
  10973. for (int i = 0; i < (int)dimLengthVals.size(); i++)
  10974. {
  10975. if (!dimLengthVals[i])
  10976. {
  10977. auto intType = mModule->GetPrimitiveType(BfTypeCode_IntPtr);
  10978. dimLengthVals[i] = mModule->GetConstValue(dimLengths[i], intType);
  10979. }
  10980. }
  10981. }
  10982. }
  10983. while ((int)dimLengthVals.size() < dimensions)
  10984. dimLengthVals.push_back(mModule->GetConstValue(0));
  10985. BfTypedValue arrayValue;
  10986. BfIRValue arraySize;
  10987. for (BfIRValue dimSize : dimLengthVals)
  10988. {
  10989. if (!arraySize)
  10990. arraySize = dimSize;
  10991. else
  10992. arraySize = mModule->mBfIRBuilder->CreateMul(arraySize, dimSize);
  10993. }
  10994. BfAllocFlags allocFlags = BfAllocFlags_None;
  10995. if (isRawArrayAlloc)
  10996. allocFlags = (BfAllocFlags)(allocFlags | BfAllocFlags_RawArray);
  10997. int writeIdx = 0;
  10998. struct BfInitContext
  10999. {
  11000. public:
  11001. BfModule* mModule;
  11002. BfType* resultType;
  11003. int dimensions;
  11004. SizedArray<BfIRValue, 2>& dimLengthVals;
  11005. BfIRValue arraySize;
  11006. int& writeIdx;
  11007. BfInitContext(BfModule* module, BfType* resultType, int dimensions, SizedArray<BfIRValue, 2>& dimLengthVals, BfIRValue arraySize, int& writeIdx) :
  11008. mModule(module), resultType(resultType), dimensions(dimensions), dimLengthVals(dimLengthVals), arraySize(arraySize), writeIdx(writeIdx)
  11009. {
  11010. }
  11011. void Handle(BfIRValue addr, int curDim, const BfSizedArray<BfExpression*>& valueExprs)
  11012. {
  11013. int exprIdx = 0;
  11014. int dimWriteIdx = 0;
  11015. bool isUninit = false;
  11016. int dimLength = -1;
  11017. if (dimLengthVals[curDim].IsConst())
  11018. {
  11019. auto constant = mModule->mBfIRBuilder->GetConstant(dimLengthVals[curDim]);
  11020. dimLength = constant->mInt32;
  11021. }
  11022. while (exprIdx < (int)valueExprs.size())
  11023. {
  11024. auto initExpr = valueExprs[exprIdx];
  11025. exprIdx++;
  11026. if (!initExpr)
  11027. break;
  11028. if (auto unintExpr = BfNodeDynCastExact<BfUninitializedExpression>(initExpr))
  11029. {
  11030. isUninit = true;
  11031. break;
  11032. }
  11033. if (exprIdx > dimLength)
  11034. break;
  11035. if (curDim < dimensions - 1)
  11036. {
  11037. if (auto innerTupleExpr = BfNodeDynCast<BfTupleExpression>(initExpr))
  11038. {
  11039. Handle(addr, curDim + 1, innerTupleExpr->mValues);
  11040. }
  11041. else if (auto parenExpr = BfNodeDynCast<BfParenthesizedExpression>(initExpr))
  11042. {
  11043. SizedArray<BfExpression*, 1> values;
  11044. values.Add(parenExpr->mExpression);
  11045. Handle(addr, curDim + 1, values);
  11046. }
  11047. else if (auto innerInitExpr = BfNodeDynCast<BfCollectionInitializerExpression>(initExpr))
  11048. {
  11049. Handle(addr, curDim + 1, innerInitExpr->mValues);
  11050. }
  11051. dimWriteIdx++;
  11052. continue;
  11053. }
  11054. BfIRValue elemAddr;
  11055. if (!resultType->IsValuelessType())
  11056. elemAddr = mModule->CreateIndexedValue(resultType, addr, writeIdx);
  11057. else
  11058. elemAddr = mModule->mBfIRBuilder->GetFakeVal();
  11059. writeIdx++;
  11060. dimWriteIdx++;
  11061. BfTypedValue elemPtrTypedVal = BfTypedValue(elemAddr, resultType, BfTypedValueKind_Addr);
  11062. BfExprEvaluator exprEvaluator(mModule);
  11063. exprEvaluator.mExpectingType = resultType;
  11064. exprEvaluator.mReceivingValue = &elemPtrTypedVal;
  11065. exprEvaluator.Evaluate(initExpr);
  11066. exprEvaluator.GetResult();
  11067. if (exprEvaluator.mReceivingValue == NULL)
  11068. {
  11069. // We wrote directly to the array in-place, we're done with this element
  11070. continue;
  11071. }
  11072. auto storeValue = exprEvaluator.mResult;
  11073. if (!storeValue)
  11074. continue;
  11075. storeValue = mModule->Cast(initExpr, storeValue, resultType);
  11076. if (!storeValue)
  11077. continue;
  11078. if (!resultType->IsValuelessType())
  11079. {
  11080. storeValue = mModule->LoadValue(storeValue);
  11081. mModule->mBfIRBuilder->CreateStore(storeValue.mValue, elemAddr);
  11082. }
  11083. }
  11084. int clearFromIdx = writeIdx;
  11085. int sectionElemCount = 1;
  11086. BfIRValue numElemsLeft = arraySize;
  11087. if (dimLength != -1)
  11088. {
  11089. int clearCount = dimLength - dimWriteIdx;
  11090. if (clearCount > 0)
  11091. {
  11092. for (int checkDim = curDim + 1; checkDim < (int)dimLengthVals.size(); checkDim++)
  11093. {
  11094. if (dimLengthVals[checkDim].IsConst())
  11095. {
  11096. auto constant = mModule->mBfIRBuilder->GetConstant(dimLengthVals[checkDim]);
  11097. clearCount *= constant->mInt32;
  11098. sectionElemCount *= constant->mInt32;
  11099. }
  11100. }
  11101. }
  11102. writeIdx += clearCount;
  11103. numElemsLeft = mModule->GetConstValue(clearCount);
  11104. }
  11105. // Actually leave it alone?
  11106. if ((isUninit) &&
  11107. ((mModule->IsOptimized()) || (mModule->mIsConstModule) || (mModule->mBfIRBuilder->mIgnoreWrites)))
  11108. return;
  11109. bool doClear = true;
  11110. if (numElemsLeft.IsConst())
  11111. {
  11112. auto constant = mModule->mBfIRBuilder->GetConstant(numElemsLeft);
  11113. doClear = constant->mInt64 > 0;
  11114. }
  11115. if (doClear)
  11116. {
  11117. // We multiply by GetStride. This relies on the fact that we over-allocate on the array allocation -- the last
  11118. // element doesn't need to be padded out to the element alignment, but we do anyway. Otherwise this would be
  11119. // a more complicated computation
  11120. auto clearBytes = mModule->mBfIRBuilder->CreateMul(numElemsLeft, mModule->GetConstValue(resultType->GetStride()));
  11121. if (isUninit)
  11122. {
  11123. // Limit to a reasonable number of bytes to stomp with 0xCC
  11124. int maxStompBytes = BF_MIN(128, resultType->GetStride() * sectionElemCount);
  11125. if (clearBytes.IsConst())
  11126. {
  11127. auto constant = mModule->mBfIRBuilder->GetConstant(clearBytes);
  11128. if (constant->mInt64 > maxStompBytes)
  11129. clearBytes = mModule->GetConstValue(maxStompBytes);
  11130. }
  11131. else
  11132. {
  11133. auto insertBlock = mModule->mBfIRBuilder->GetInsertBlock();
  11134. auto gtBlock = mModule->mBfIRBuilder->CreateBlock("unint.gt");
  11135. auto contBlock = mModule->mBfIRBuilder->CreateBlock("unint.cont");
  11136. auto cmp = mModule->mBfIRBuilder->CreateCmpLTE(clearBytes, mModule->GetConstValue(maxStompBytes), true);
  11137. mModule->mBfIRBuilder->CreateCondBr(cmp, contBlock, gtBlock);
  11138. mModule->mBfIRBuilder->AddBlock(gtBlock);
  11139. mModule->mBfIRBuilder->SetInsertPoint(gtBlock);
  11140. mModule->mBfIRBuilder->CreateBr(contBlock);
  11141. mModule->mBfIRBuilder->AddBlock(contBlock);
  11142. mModule->mBfIRBuilder->SetInsertPoint(contBlock);
  11143. auto phi = mModule->mBfIRBuilder->CreatePhi(mModule->mBfIRBuilder->MapType(mModule->GetPrimitiveType(BfTypeCode_IntPtr)), 2);
  11144. mModule->mBfIRBuilder->AddPhiIncoming(phi, clearBytes, insertBlock);
  11145. mModule->mBfIRBuilder->AddPhiIncoming(phi, mModule->GetConstValue(maxStompBytes), gtBlock);
  11146. clearBytes = phi;
  11147. }
  11148. }
  11149. mModule->mBfIRBuilder->PopulateType(resultType);
  11150. if (!resultType->IsValuelessType())
  11151. {
  11152. mModule->mBfIRBuilder->CreateMemSet(mModule->CreateIndexedValue(resultType, addr, clearFromIdx),
  11153. mModule->mBfIRBuilder->CreateConst(BfTypeCode_Int8, isUninit ? 0xCC : 0), clearBytes, resultType->mAlign);
  11154. }
  11155. }
  11156. }
  11157. };
  11158. BfInitContext initContext(mModule, resultType, dimensions, dimLengthVals, arraySize, writeIdx);
  11159. if (resultType->IsVar())
  11160. {
  11161. SetAndRestoreValue<bool> prevIgnoreWrites(mModule->mBfIRBuilder->mIgnoreWrites, true);
  11162. mResult = BfTypedValue(BfTypedValue(mModule->mBfIRBuilder->GetFakeVal(), mModule->GetPrimitiveType(BfTypeCode_Var)));
  11163. initContext.Handle(mResult.mValue, 0, objCreateExpr->mArguments);
  11164. return;
  11165. }
  11166. if (isRawArrayAlloc)
  11167. {
  11168. // 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
  11169. BfType* ptrType = mModule->CreatePointerType(resultType);
  11170. if (isAppendAlloc)
  11171. arrayValue = BfTypedValue(mModule->AppendAllocFromType(resultType, BfIRValue(), 0, arraySize, (int)dimLengthVals.size(), isRawArrayAlloc, false), ptrType);
  11172. else
  11173. {
  11174. arrayValue = BfTypedValue(mModule->AllocFromType(resultType, allocTarget, BfIRValue(), arraySize, (int)dimLengthVals.size(), allocFlags, allocTarget.mAlignOverride), ptrType);
  11175. }
  11176. initContext.Handle(arrayValue.mValue, 0, objCreateExpr->mArguments);
  11177. mResult = arrayValue;
  11178. return;
  11179. }
  11180. if (dimLengthVals.size() > 4)
  11181. {
  11182. dimLengthVals.RemoveRange(4, dimLengthVals.size() - 4);
  11183. mModule->Fail("Too many array dimensions, consider using a jagged array.", objCreateExpr);
  11184. }
  11185. if (isAppendAlloc)
  11186. arrayValue = BfTypedValue(mModule->AppendAllocFromType(resultType, BfIRValue(), 0, arraySize, (int)dimLengthVals.size(), isRawArrayAlloc, zeroMemory), arrayType);
  11187. else
  11188. {
  11189. arrayValue = BfTypedValue(mModule->AllocFromType(resultType, allocTarget, BfIRValue(), arraySize, (int)dimLengthVals.size(), allocFlags, allocTarget.mAlignOverride), arrayType);
  11190. if (isScopeAlloc)
  11191. {
  11192. // See notes below on "general" SkipObjectAccessCheck usage on why we can do this
  11193. mModule->SkipObjectAccessCheck(arrayValue);
  11194. }
  11195. }
  11196. //mModule->InitTypeInst(arrayValue, scopeData);
  11197. BfAstNode* refNode = objCreateExpr->mTypeRef;
  11198. while (true)
  11199. {
  11200. if (auto arrayRef = BfNodeDynCast<BfElementedTypeRef>(refNode))
  11201. {
  11202. refNode = arrayRef->mElementType;
  11203. continue;
  11204. }
  11205. break;
  11206. }
  11207. BfResolvedArgs resolvedArgs;
  11208. auto rawAutoComplete = mModule->mCompiler->GetAutoComplete();
  11209. if (rawAutoComplete != NULL)
  11210. {
  11211. SetAndRestoreValue<bool> prevCapturing(rawAutoComplete->mIsCapturingMethodMatchInfo, false);
  11212. MatchConstructor(refNode, objCreateExpr, arrayValue, arrayType, resolvedArgs, false, false);
  11213. }
  11214. else
  11215. {
  11216. MatchConstructor(refNode, objCreateExpr, arrayValue, arrayType, resolvedArgs, false, false);
  11217. }
  11218. //TODO: Assert 'length' var is at slot 1
  11219. mModule->PopulateType(arrayType->mBaseType, BfPopulateType_DataAndMethods);
  11220. mModule->mBfIRBuilder->PopulateType(arrayType);
  11221. auto arrayBits = mModule->mBfIRBuilder->CreateBitCast(arrayValue.mValue, mModule->mBfIRBuilder->MapTypeInstPtr(arrayType->mBaseType));
  11222. int arrayLengthBitCount = arrayType->GetLengthBitCount();
  11223. if (arrayLengthBitCount == 0)
  11224. {
  11225. mModule->Fail("INTERNAL ERROR: Unable to find array 'length' field", objCreateExpr);
  11226. return;
  11227. }
  11228. mResult = arrayValue;
  11229. auto lengthFieldInstance = mModule->GetFieldByName(arrayType->mBaseType->ToTypeInstance(), "mLength");
  11230. if (lengthFieldInstance == NULL)
  11231. return;
  11232. auto firstElementFieldInstance = mModule->GetFieldByName(arrayType->ToTypeInstance(), "mFirstElement");
  11233. if (firstElementFieldInstance == NULL)
  11234. return;
  11235. auto addr = mModule->mBfIRBuilder->CreateInBoundsGEP(arrayBits, 0, lengthFieldInstance->mDataIdx);
  11236. if (arrayLengthBitCount == 64)
  11237. mModule->mBfIRBuilder->CreateAlignedStore(arraySize, addr, 8);
  11238. else
  11239. {
  11240. auto arraySize32 = mModule->mBfIRBuilder->CreateNumericCast(arraySize, true, BfTypeCode_Int32);
  11241. mModule->mBfIRBuilder->CreateAlignedStore(arraySize32, addr, 4);
  11242. }
  11243. for (int lowerDim = 1; lowerDim < (int)dimLengthVals.size(); lowerDim++)
  11244. {
  11245. auto length1FieldInstance = mModule->GetFieldByName(arrayType->ToTypeInstance(), "mLength1");
  11246. if (length1FieldInstance == NULL)
  11247. return;
  11248. addr = mModule->mBfIRBuilder->CreateInBoundsGEP(arrayValue.mValue, 0, length1FieldInstance->mDataIdx + lowerDim - 1);
  11249. auto lowerDimVal = mModule->mBfIRBuilder->CreateNumericCast(dimLengthVals[lowerDim], true, (arrayLengthBitCount == 64) ? BfTypeCode_Int64 : BfTypeCode_Int32);
  11250. mModule->mBfIRBuilder->CreateStore(lowerDimVal, addr);
  11251. }
  11252. if (resultType->IsValuelessType())
  11253. addr = mModule->mBfIRBuilder->GetFakeVal();
  11254. else
  11255. addr = mModule->mBfIRBuilder->CreateInBoundsGEP(arrayValue.mValue, 0, firstElementFieldInstance->mDataIdx);
  11256. initContext.Handle(addr, 0, objCreateExpr->mArguments);
  11257. return;
  11258. }
  11259. else
  11260. {
  11261. if (resolvedTypeRef->IsVar())
  11262. {
  11263. // Leave as a var
  11264. }
  11265. else if ((!resolvedTypeRef->IsObjectOrInterface()) && (!resolvedTypeRef->IsGenericParam()))
  11266. {
  11267. resultType = mModule->CreatePointerType(resolvedTypeRef);
  11268. }
  11269. }
  11270. if ((isStackAlloc) && (mModule->mCurMethodState == NULL))
  11271. {
  11272. mModule->Fail("Cannot use 'stack' here", allocNode);
  11273. isStackAlloc = false;
  11274. isScopeAlloc = false;
  11275. }
  11276. bool isGenericParam = unresolvedTypeRef->IsGenericParam();
  11277. if (resolvedTypeRef->IsGenericParam())
  11278. {
  11279. auto genericParam = mModule->GetGenericParamInstance((BfGenericParamType*)resolvedTypeRef);
  11280. if (genericParam->mTypeConstraint == NULL)
  11281. {
  11282. if ((genericParam->mGenericParamFlags & BfGenericParamFlag_New) == 0)
  11283. {
  11284. mModule->Fail(StrFormat("Must add 'where %s : new' constraint to generic parameter to instantiate type", genericParam->GetName().c_str()), objCreateExpr->mTypeRef);
  11285. }
  11286. if (objCreateExpr->mArguments.size() != 0)
  11287. {
  11288. mModule->Fail(StrFormat("Only default parameterless constructors can be called on generic argument '%s'", genericParam->GetName().c_str()), objCreateExpr->mTypeRef);
  11289. }
  11290. }
  11291. if (((genericParam->mTypeConstraint != NULL) && (genericParam->mTypeConstraint->IsValueType())) ||
  11292. ((genericParam->mGenericParamFlags & (BfGenericParamFlag_Struct | BfGenericParamFlag_StructPtr)) != 0))
  11293. {
  11294. resultType = mModule->CreatePointerType(resolvedTypeRef);
  11295. }
  11296. else if (((genericParam->mTypeConstraint != NULL) && (!genericParam->mTypeConstraint->IsValueType())) ||
  11297. ((genericParam->mGenericParamFlags & (BfGenericParamFlag_Class)) != 0))
  11298. {
  11299. // Leave as 'T'
  11300. resultType = resolvedTypeRef;
  11301. }
  11302. else
  11303. resultType = mModule->CreateModifiedTypeType(resolvedTypeRef, BfToken_AllocType);
  11304. mResult.mType = resultType;
  11305. if (typeInstance == NULL)
  11306. {
  11307. mResult = mModule->GetDefaultTypedValue(resultType);
  11308. return;
  11309. }
  11310. }
  11311. else if (resolvedTypeRef->IsSizedArray())
  11312. {
  11313. // Handle the case of "int[3]* val = new .(1, 2, 3)"
  11314. if (auto dotTypeRef = BfNodeDynCastExact<BfDotTypeReference>(objCreateExpr->mTypeRef))
  11315. {
  11316. BfIRValue allocValue;
  11317. if (isAppendAlloc)
  11318. allocValue = mModule->AppendAllocFromType(resolvedTypeRef, BfIRValue(), 0, BfIRValue(), 0, false, false);
  11319. else
  11320. allocValue = mModule->AllocFromType(resolvedTypeRef, allocTarget, BfIRValue(), BfIRValue(), 0, BfAllocFlags_None);
  11321. auto result = BfTypedValue(allocValue, resolvedTypeRef, BfTypedValueKind_Addr);
  11322. InitializedSizedArray((BfSizedArrayType*)resolvedTypeRef, objCreateExpr->mOpenToken, objCreateExpr->mArguments, objCreateExpr->mCommas, objCreateExpr->mCloseToken, &result);
  11323. // Turn from an addr of a sized array to pointer of sized array
  11324. mResult = BfTypedValue(mResult.mValue, resultType);
  11325. return;
  11326. }
  11327. }
  11328. SetAndRestoreValue<bool> prevNoBind(mNoBind, mNoBind || isGenericParam);
  11329. if ((typeInstance != NULL) && (typeInstance->mTypeDef->mIsAbstract))
  11330. {
  11331. mModule->Fail("Cannot create an instance of an abstract class", objCreateExpr->mTypeRef);
  11332. return;
  11333. }
  11334. BfFunctionBindResult bindResult;
  11335. bindResult.mSkipThis = true;
  11336. bindResult.mWantsArgs = true;
  11337. SetAndRestoreValue<BfFunctionBindResult*> prevBindResult(mFunctionBindResult, &bindResult);
  11338. BfIRValue appendSizeValue;
  11339. BfTypedValue emtpyThis(mModule->mBfIRBuilder->GetFakeVal(), resolvedTypeRef, resolvedTypeRef->IsStruct());
  11340. BfResolvedArgs argValues;
  11341. if (objCreateExpr != NULL)
  11342. {
  11343. argValues.Init(objCreateExpr->mOpenToken, &objCreateExpr->mArguments, &objCreateExpr->mCommas, objCreateExpr->mCloseToken);
  11344. ResolveArgValues(argValues, BfResolveArgFlag_DeferParamEval); ////
  11345. }
  11346. if (typeInstance == NULL)
  11347. {
  11348. // No CTOR needed
  11349. if (objCreateExpr->mArguments.size() != 0)
  11350. {
  11351. mModule->Fail(StrFormat("Only default parameterless constructors can be called on primitive type '%s'", mModule->TypeToString(resolvedTypeRef).c_str()), objCreateExpr->mTypeRef);
  11352. }
  11353. }
  11354. else if ((autoComplete != NULL) && (objCreateExpr != NULL) && (objCreateExpr->mOpenToken != NULL))
  11355. {
  11356. auto wasCapturingMethodInfo = autoComplete->mIsCapturingMethodMatchInfo;
  11357. autoComplete->CheckInvocation(objCreateExpr, objCreateExpr->mOpenToken, objCreateExpr->mCloseToken, objCreateExpr->mCommas);
  11358. MatchConstructor(objCreateExpr->mTypeRef, objCreateExpr, emtpyThis, typeInstance, argValues, false, true);
  11359. if ((wasCapturingMethodInfo) && (!autoComplete->mIsCapturingMethodMatchInfo))
  11360. {
  11361. if (autoComplete->mMethodMatchInfo != NULL)
  11362. autoComplete->mIsCapturingMethodMatchInfo = true;
  11363. }
  11364. else
  11365. autoComplete->mIsCapturingMethodMatchInfo = false;
  11366. }
  11367. else if (!resolvedTypeRef->IsFunction())
  11368. {
  11369. auto refNode = allocNode;
  11370. if (objCreateExpr != NULL)
  11371. refNode = objCreateExpr->mTypeRef;
  11372. MatchConstructor(refNode, objCreateExpr, emtpyThis, typeInstance, argValues, false, true);
  11373. }
  11374. if (objCreateExpr != NULL)
  11375. mModule->ValidateAllocation(typeInstance, objCreateExpr->mTypeRef);
  11376. prevBindResult.Restore();
  11377. int allocAlign = resolvedTypeRef->mAlign;
  11378. if (typeInstance != NULL)
  11379. allocAlign = typeInstance->mInstAlign;
  11380. int appendAllocAlign = 0;
  11381. if ((bindResult.mMethodInstance != NULL) && (bindResult.mMethodInstance->mMethodDef->mHasAppend))
  11382. {
  11383. if (!bindResult.mFunc)
  11384. {
  11385. BF_ASSERT((!mModule->HasCompiledOutput()) || (mModule->mBfIRBuilder->mIgnoreWrites));
  11386. appendSizeValue = mModule->GetConstValue(0);
  11387. }
  11388. else
  11389. {
  11390. auto calcAppendMethodModule = mModule->GetMethodInstanceAtIdx(bindResult.mMethodInstance->GetOwner(), bindResult.mMethodInstance->mMethodDef->mIdx + 1, BF_METHODNAME_CALCAPPEND);
  11391. SizedArray<BfIRValue, 2> irArgs;
  11392. if (bindResult.mIRArgs.size() > 1)
  11393. irArgs.Insert(0, &bindResult.mIRArgs[1], bindResult.mIRArgs.size() - 1);
  11394. BfTypedValue appendSizeTypedValue = mModule->TryConstCalcAppend(calcAppendMethodModule.mMethodInstance, irArgs);
  11395. if (!appendSizeTypedValue)
  11396. {
  11397. BF_ASSERT(calcAppendMethodModule.mFunc);
  11398. appendSizeTypedValue = CreateCall(objCreateExpr, calcAppendMethodModule.mMethodInstance, calcAppendMethodModule.mFunc, false, irArgs);
  11399. BF_ASSERT(appendSizeTypedValue.mType == mModule->GetPrimitiveType(BfTypeCode_IntPtr));
  11400. }
  11401. appendSizeValue = appendSizeTypedValue.mValue;
  11402. allocAlign = BF_MAX(allocAlign, calcAppendMethodModule.mMethodInstance->mAppendAllocAlign);
  11403. appendAllocAlign = calcAppendMethodModule.mMethodInstance->mAppendAllocAlign;
  11404. }
  11405. if (appendAllocAlign != 0)
  11406. {
  11407. int endingAlign = typeInstance->GetEndingInstanceAlignment();
  11408. if (endingAlign % appendAllocAlign != 0)
  11409. {
  11410. int extraSize = appendAllocAlign - (endingAlign % appendAllocAlign);
  11411. appendSizeValue = mModule->mBfIRBuilder->CreateAdd(appendSizeValue, mModule->GetConstValue(extraSize));
  11412. }
  11413. }
  11414. }
  11415. // WTF? I'm not even sure this is correct - add more tests
  11416. appendAllocAlign = BF_MAX(appendAllocAlign, allocAlign);
  11417. BfIRValue allocValue;
  11418. if (resolvedTypeRef->IsVar())
  11419. {
  11420. mResult = mModule->GetDefaultTypedValue(resultType);
  11421. return;
  11422. }
  11423. else
  11424. {
  11425. if (isAppendAlloc)
  11426. allocValue = mModule->AppendAllocFromType(resolvedTypeRef, appendSizeValue, appendAllocAlign);
  11427. else
  11428. {
  11429. allocValue = mModule->AllocFromType(resolvedTypeRef, allocTarget, appendSizeValue, BfIRValue(), 0, BfAllocFlags_None, allocAlign);
  11430. }
  11431. mResult = BfTypedValue(allocValue, resultType);
  11432. }
  11433. if (isScopeAlloc)
  11434. {
  11435. // This allows readonly (ie: 'let') local usage to not require an access check. No matter what scope the alloc is tied to, the
  11436. // lifetime of the local variable will be no longer than that of the allocated value
  11437. mModule->SkipObjectAccessCheck(mResult);
  11438. }
  11439. /*if (typeInstance != NULL)
  11440. {
  11441. mModule->InitTypeInst(mResult, scopeData, true);
  11442. }
  11443. if (isStackAlloc)
  11444. {
  11445. mModule->AddStackAlloc(mResult, objCreateExpr, scopeData);
  11446. }*/
  11447. if (mResult)
  11448. {
  11449. if (bindResult.mMethodInstance == NULL)
  11450. {
  11451. // Why did we have this? It was already zeroed right?
  11452. // Zero
  11453. //mModule->mBfIRBuilder->CreateMemSet(mResult.mValue, mModule->GetConstValue8(0), mModule->GetConstValue(resolvedTypeRef->mSize), resolvedTypeRef->mAlign);
  11454. }
  11455. else if (bindResult.mFunc)
  11456. {
  11457. if (typeInstance->IsObject())
  11458. {
  11459. bool wantsCtorClear = true;
  11460. if (mModule->mCompiler->mOptions.mEnableRealtimeLeakCheck)
  11461. {
  11462. // Dbg_ObjectAlloc clears internally so we don't need to call CtorClear for those
  11463. if ((!isStackAlloc) && (!allocTarget.mCustomAllocator) && (allocTarget.mScopedInvocationTarget == NULL))
  11464. wantsCtorClear = false;
  11465. }
  11466. if (wantsCtorClear)
  11467. {
  11468. auto ctorClear = mModule->GetMethodByName(typeInstance, "__BfCtorClear");
  11469. if (!ctorClear)
  11470. {
  11471. mModule->AssertErrorState();
  11472. }
  11473. else
  11474. {
  11475. SizedArray<BfIRValue, 1> irArgs;
  11476. irArgs.push_back(mResult.mValue);
  11477. CreateCall(objCreateExpr, ctorClear.mMethodInstance, ctorClear.mFunc, false, irArgs);
  11478. }
  11479. }
  11480. if ((isStackAlloc) && (mModule->mCompiler->mOptions.mEnableRealtimeLeakCheck))
  11481. {
  11482. BfMethodInstance* markMethod = mModule->GetRawMethodByName(mModule->mContext->mBfObjectType, "GCMarkMembers");
  11483. BF_ASSERT(markMethod != NULL);
  11484. if (markMethod != NULL)
  11485. {
  11486. auto& vtableEntry = typeInstance->mVirtualMethodTable[markMethod->mVirtualTableIdx];
  11487. if (vtableEntry.mImplementingMethod.mTypeInstance != mModule->mContext->mBfObjectType)
  11488. {
  11489. auto impMethodInstance = (BfMethodInstance*)vtableEntry.mImplementingMethod;
  11490. bool needsCall = false;
  11491. if (impMethodInstance != NULL)
  11492. {
  11493. needsCall = impMethodInstance->mMethodDef->mBody != NULL;
  11494. }
  11495. else
  11496. {
  11497. needsCall = true;
  11498. BF_ASSERT(vtableEntry.mImplementingMethod.mKind == BfMethodRefKind_AmbiguousRef);
  11499. }
  11500. if (needsCall)
  11501. {
  11502. SizedArray<BfIRValue, 1> irArgs;
  11503. irArgs.push_back(mModule->mBfIRBuilder->CreateBitCast(mResult.mValue, mModule->mBfIRBuilder->MapType(mModule->mContext->mBfObjectType)));
  11504. auto gcType = mModule->ResolveTypeDef(mModule->mCompiler->mGCTypeDef);
  11505. BF_ASSERT(gcType != NULL);
  11506. if (gcType != NULL)
  11507. {
  11508. auto addStackObjMethod = mModule->GetMethodByName(gcType->ToTypeInstance(), "AddStackMarkableObject", 1);
  11509. BF_ASSERT(addStackObjMethod);
  11510. if (addStackObjMethod)
  11511. {
  11512. mModule->mBfIRBuilder->CreateCall(addStackObjMethod.mFunc, irArgs);
  11513. }
  11514. auto removeStackObjMethod = mModule->GetMethodByName(gcType->ToTypeInstance(), "RemoveStackMarkableObject", 1);
  11515. BF_ASSERT(removeStackObjMethod);
  11516. if (removeStackObjMethod)
  11517. {
  11518. mModule->AddDeferredCall(removeStackObjMethod, irArgs, allocTarget.mScopeData, allocNode);
  11519. }
  11520. }
  11521. }
  11522. }
  11523. }
  11524. }
  11525. }
  11526. if ((bindResult.mMethodInstance->mMethodDef->mHasAppend) && (mResult.mType->IsObject()))
  11527. {
  11528. BF_ASSERT(bindResult.mIRArgs[0].IsFake());
  11529. auto typeInst = mResult.mType->ToTypeInstance();
  11530. auto intPtrType = mModule->GetPrimitiveType(BfTypeCode_IntPtr);
  11531. auto thisVal = mResult;
  11532. BfIRValue intPtrVal = mModule->CreateAlloca(intPtrType);
  11533. auto intPtrThisVal = mModule->mBfIRBuilder->CreatePtrToInt(thisVal.mValue, (intPtrType->mSize == 4) ? BfTypeCode_Int32 : BfTypeCode_Int64);
  11534. auto curValPtr = mModule->mBfIRBuilder->CreateAdd(intPtrThisVal, mModule->GetConstValue(typeInst->mInstSize, intPtrType));
  11535. mModule->mBfIRBuilder->CreateStore(curValPtr, intPtrVal);
  11536. bindResult.mIRArgs[0] = intPtrVal;
  11537. }
  11538. if (!typeInstance->IsValuelessType())
  11539. bindResult.mIRArgs.Insert(0, mResult.mValue);
  11540. CreateCall(objCreateExpr, bindResult.mMethodInstance, bindResult.mFunc, false, bindResult.mIRArgs);
  11541. }
  11542. }
  11543. }
  11544. void BfExprEvaluator::Visit(BfBoxExpression* boxExpr)
  11545. {
  11546. /*if ((boxExpr->mAllocNode == NULL) || (boxExpr->mExpression == NULL))
  11547. {
  11548. mModule->AssertErrorState();
  11549. return;
  11550. }*/
  11551. BfTokenNode* newToken = NULL;
  11552. BfAllocTarget allocTarget = ResolveAllocTarget(boxExpr->mAllocNode, newToken);
  11553. if ((boxExpr->mAllocNode != NULL) && (boxExpr->mAllocNode->mToken == BfToken_Scope))
  11554. {
  11555. if ((mBfEvalExprFlags & BfEvalExprFlags_FieldInitializer) != 0)
  11556. {
  11557. mModule->Warn(0, "This allocation will only be in scope during the constructor. Consider using a longer-term allocation such as 'new'", boxExpr->mAllocNode);
  11558. }
  11559. }
  11560. if (boxExpr->mExpression == NULL)
  11561. {
  11562. mModule->AssertErrorState();
  11563. return;
  11564. }
  11565. auto exprValue = mModule->CreateValueFromExpression(boxExpr->mExpression);
  11566. if (exprValue)
  11567. {
  11568. bool doFail = false;
  11569. bool doWarn = false;
  11570. if (exprValue.mType->IsGenericParam())
  11571. {
  11572. BF_ASSERT(mModule->mCurMethodInstance->mIsUnspecialized);
  11573. auto genericParamTarget = (BfGenericParamType*)exprValue.mType;
  11574. auto genericParamInstance = mModule->GetGenericParamInstance(genericParamTarget);
  11575. if ((genericParamInstance->mGenericParamFlags & (BfGenericParamFlag_Struct | BfGenericParamFlag_StructPtr | BfGenericParamFlag_Class)) == BfGenericParamFlag_Class)
  11576. doWarn = true;
  11577. if ((genericParamInstance->mTypeConstraint != NULL) && (genericParamInstance->mTypeConstraint->IsObjectOrInterface()))
  11578. doWarn = true;
  11579. }
  11580. else
  11581. {
  11582. doFail = !exprValue.mType->IsValueTypeOrValueTypePtr();
  11583. doWarn = exprValue.mType->IsObjectOrInterface();
  11584. }
  11585. if (doWarn)
  11586. {
  11587. mModule->Warn(0, StrFormat("Boxing is unnecessary since type '%s' is already a reference type.", mModule->TypeToString(exprValue.mType).c_str()), boxExpr->mExpression);
  11588. mResult = exprValue;
  11589. return;
  11590. }
  11591. if (doFail)
  11592. {
  11593. 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);
  11594. return;
  11595. }
  11596. BfType* boxedType = mModule->CreateBoxedType(exprValue.mType);
  11597. if (boxedType == NULL)
  11598. boxedType = mModule->mContext->mBfObjectType;
  11599. mResult = mModule->BoxValue(boxExpr->mExpression, exprValue, boxedType, allocTarget);
  11600. if (!mResult)
  11601. {
  11602. mModule->Fail(StrFormat("Type '%s' is not boxable", mModule->TypeToString(exprValue.mType).c_str()), boxExpr->mExpression);
  11603. return;
  11604. }
  11605. }
  11606. }
  11607. BfAllocTarget BfExprEvaluator::ResolveAllocTarget(BfAstNode* allocNode, BfTokenNode*& newToken, BfCustomAttributes** outCustomAttributes)
  11608. {
  11609. auto autoComplete = GetAutoComplete();
  11610. BfAttributeDirective* attributeDirective = NULL;
  11611. BfAllocTarget allocTarget;
  11612. allocTarget.mRefNode = allocNode;
  11613. newToken = BfNodeDynCast<BfTokenNode>(allocNode);
  11614. if (newToken == NULL)
  11615. {
  11616. if (auto scopeNode = BfNodeDynCast<BfScopeNode>(allocNode))
  11617. {
  11618. newToken = scopeNode->mScopeToken;
  11619. allocTarget.mScopeData = mModule->FindScope(scopeNode->mTargetNode, true);
  11620. if (autoComplete != NULL)
  11621. {
  11622. auto targetIdentifier = BfNodeDynCast<BfIdentifierNode>(scopeNode->mTargetNode);
  11623. if ((scopeNode->mTargetNode == NULL) || (targetIdentifier != NULL))
  11624. autoComplete->CheckLabel(targetIdentifier, scopeNode->mColonToken, allocTarget.mScopeData);
  11625. }
  11626. attributeDirective = scopeNode->mAttributes;
  11627. }
  11628. if (auto newNode = BfNodeDynCast<BfNewNode>(allocNode))
  11629. {
  11630. newToken = newNode->mNewToken;
  11631. if (auto allocExpr = BfNodeDynCast<BfExpression>(newNode->mAllocNode))
  11632. {
  11633. allocTarget.mCustomAllocator = mModule->CreateValueFromExpression(allocExpr);
  11634. allocTarget.mRefNode = allocExpr;
  11635. }
  11636. else if (auto scopedInvocationTarget = BfNodeDynCast<BfScopedInvocationTarget>(newNode->mAllocNode))
  11637. {
  11638. allocTarget.mScopedInvocationTarget = scopedInvocationTarget;
  11639. }
  11640. attributeDirective = newNode->mAttributes;
  11641. }
  11642. }
  11643. else if (newToken->GetToken() == BfToken_Scope)
  11644. {
  11645. if (mModule->mCurMethodState != NULL)
  11646. allocTarget.mScopeData = mModule->mCurMethodState->mCurScope->GetTargetable();
  11647. }
  11648. else if (newToken->GetToken() == BfToken_Stack)
  11649. {
  11650. if (mModule->mCurMethodState != NULL)
  11651. allocTarget.mScopeData = &mModule->mCurMethodState->mHeadScope;
  11652. }
  11653. if (attributeDirective != NULL)
  11654. {
  11655. auto customAttrs = mModule->GetCustomAttributes(attributeDirective, BfAttributeTargets_Alloc, true, &allocTarget.mCaptureInfo);
  11656. if (customAttrs != NULL)
  11657. {
  11658. for (auto& attrib : customAttrs->mAttributes)
  11659. {
  11660. if (attrib.mType->mTypeDef == mModule->mCompiler->mAlignAttributeTypeDef)
  11661. {
  11662. allocTarget.mAlignOverride = 16; // System conservative default
  11663. if (!attrib.mCtorArgs.IsEmpty())
  11664. {
  11665. BfIRConstHolder* constHolder = mModule->mCurTypeInstance->mConstHolder;
  11666. auto constant = constHolder->GetConstant(attrib.mCtorArgs[0]);
  11667. if (constant != NULL)
  11668. {
  11669. int alignOverride = (int)BF_MAX(1, constant->mInt64);
  11670. if ((alignOverride & (alignOverride - 1)) == 0)
  11671. allocTarget.mAlignOverride = alignOverride;
  11672. else
  11673. mModule->Fail("Alignment must be a power of 2", attrib.GetRefNode());
  11674. }
  11675. }
  11676. }
  11677. else if (attrib.mType->mTypeDef == mModule->mCompiler->mFriendAttributeTypeDef)
  11678. allocTarget.mIsFriend = true;
  11679. }
  11680. if (outCustomAttributes != NULL)
  11681. *outCustomAttributes = customAttrs;
  11682. else
  11683. delete customAttrs;
  11684. }
  11685. }
  11686. return allocTarget;
  11687. }
  11688. BfTypedValue BfExprEvaluator::MakeCallableTarget(BfAstNode* targetSrc, BfTypedValue target)
  11689. {
  11690. if ((target.mType->IsRef()) || (target.mType->IsPointer()))
  11691. {
  11692. auto underlying = target.mType->GetUnderlyingType();
  11693. bool underlyingIsStruct = underlying->IsStruct();
  11694. // if (underlying->IsGenericParam())
  11695. // {
  11696. // auto genericParam = mModule->GetGenericParamInstance((BfGenericParamType*)underlying);
  11697. // if (((genericParam->mTypeConstraint != NULL) && (genericParam->mTypeConstraint->IsValueType())) ||
  11698. // ((genericParam->mGenericParamFlags & (BfGenericParamFlag_Struct)) != 0))
  11699. // underlyingIsStruct = true;
  11700. // }
  11701. if (underlyingIsStruct)
  11702. {
  11703. auto pointerType = (BfPointerType*)target.mType;
  11704. target = mModule->LoadValue(target);
  11705. target.mType = pointerType->mElementType;
  11706. target.mKind = BfTypedValueKind_Addr;
  11707. }
  11708. }
  11709. if ((target.mType->IsStruct()) && (!target.IsAddr()))
  11710. {
  11711. target = mModule->MakeAddressable(target);
  11712. }
  11713. if (target.mType->IsVar())
  11714. {
  11715. target.mType = mModule->mContext->mBfObjectType;
  11716. return target;
  11717. }
  11718. if ((target.mType->IsPointer()) && (target.mType->GetUnderlyingType()->IsObjectOrInterface()))
  11719. {
  11720. mModule->Fail(StrFormat("Methods cannot be called on type '%s' because the type is a pointer to a reference type (ie: a double-reference).",
  11721. mModule->TypeToString(target.mType).c_str()), targetSrc);
  11722. target.mType = mModule->mContext->mBfObjectType;
  11723. return target;
  11724. }
  11725. if (target.mType->IsWrappableType())
  11726. {
  11727. auto primStructType = mModule->GetWrappedStructType(target.mType);
  11728. if (primStructType != NULL)
  11729. {
  11730. mModule->PopulateType(primStructType);
  11731. if (primStructType->IsTypedPrimitive())
  11732. {
  11733. // Type is already the same
  11734. target.mType = primStructType;
  11735. }
  11736. else if (target.IsAddr())
  11737. {
  11738. auto ptrType = mModule->CreatePointerType(primStructType);
  11739. target = BfTypedValue(mModule->mBfIRBuilder->CreateBitCast(target.mValue, mModule->mBfIRBuilder->MapType(ptrType)), primStructType, true);
  11740. }
  11741. else if ((primStructType->IsSplattable()) && (target.IsSplat()))
  11742. {
  11743. target.mType = primStructType;
  11744. target.mKind = BfTypedValueKind_SplatHead;
  11745. }
  11746. else
  11747. {
  11748. auto allocPtr = mModule->CreateAlloca(primStructType);
  11749. auto srcPtrType = mModule->mBfIRBuilder->CreateBitCast(allocPtr, mModule->mBfIRBuilder->GetPointerTo(mModule->mBfIRBuilder->MapType(target.mType)));
  11750. mModule->mBfIRBuilder->CreateStore(target.mValue, srcPtrType);
  11751. target = BfTypedValue(allocPtr, primStructType, true);
  11752. }
  11753. }
  11754. return target;
  11755. }
  11756. if (target.mType->IsGenericParam())
  11757. {
  11758. target.mType = mModule->mContext->mBfObjectType;
  11759. return target;
  11760. }
  11761. if ((!target.mType->IsTypeInstance()) && (!target.mType->IsConcreteInterfaceType()))
  11762. {
  11763. mModule->Fail(StrFormat("Methods cannot be called on type '%s'", mModule->TypeToString(target.mType).c_str()), targetSrc);
  11764. return BfTypedValue();
  11765. }
  11766. return target;
  11767. }
  11768. int BfExprEvaluator::GetMixinVariable()
  11769. {
  11770. auto curMethodState = mModule->mCurMethodState;
  11771. for (int localIdx = (int)curMethodState->mLocals.size() - 1; localIdx >= 0; localIdx--)
  11772. {
  11773. auto varDecl = curMethodState->mLocals[localIdx];
  11774. if (varDecl->mName == "mixin")
  11775. return localIdx;
  11776. }
  11777. return -1;
  11778. }
  11779. BfModuleMethodInstance BfExprEvaluator::GetSelectedMethod(BfAstNode* targetSrc, BfTypeInstance* curTypeInst, BfMethodDef* methodDef, BfMethodMatcher& methodMatcher)
  11780. {
  11781. bool failed = false;
  11782. BfTypeVector resolvedGenericArguments;
  11783. BfMethodState* rootMethodState = NULL;
  11784. if (mModule->mCurMethodState != NULL)
  11785. rootMethodState = mModule->mCurMethodState->GetRootMethodState();
  11786. int localInferrableGenericArgCount = -1;
  11787. if ((methodMatcher.mBestMethodGenericArguments.size() == 0) && (!methodMatcher.mExplicitMethodGenericArguments.IsEmpty()))
  11788. {
  11789. int uniqueGenericStartIdx = mModule->GetLocalInferrableGenericArgCount(methodDef);
  11790. int64 genericArgCountDiff = (int)methodMatcher.mExplicitMethodGenericArguments.size() + uniqueGenericStartIdx - (int)methodDef->mGenericParams.size();
  11791. BfInvocationExpression* invocationExpr = NULL;
  11792. if (mModule->mParentNodeEntry != NULL)
  11793. {
  11794. invocationExpr = BfNodeDynCast<BfInvocationExpression>(mModule->mParentNodeEntry->mNode);
  11795. }
  11796. if (genericArgCountDiff > 0)
  11797. {
  11798. BfAstNode* errorNode = targetSrc;
  11799. if ((invocationExpr != NULL) && (invocationExpr->mGenericArgs != NULL))
  11800. {
  11801. errorNode = invocationExpr->mGenericArgs->mGenericArgs[(int)methodDef->mGenericParams.size()];
  11802. if (errorNode == NULL)
  11803. invocationExpr->mGenericArgs->mCommas.GetSafe((int)methodDef->mGenericParams.size() - 1, errorNode);
  11804. if (errorNode == NULL)
  11805. errorNode = targetSrc;
  11806. }
  11807. mModule->Fail(StrFormat("Too many generic arguments, expected %d fewer", genericArgCountDiff), errorNode);
  11808. }
  11809. else if (genericArgCountDiff < 0)
  11810. {
  11811. BfAstNode* errorNode = targetSrc;
  11812. if ((invocationExpr != NULL) && (invocationExpr->mGenericArgs != NULL) && (invocationExpr->mGenericArgs->mCloseChevron != NULL))
  11813. errorNode = invocationExpr->mGenericArgs->mCloseChevron;
  11814. mModule->Fail(StrFormat("Too few generic arguments, expected %d more", -genericArgCountDiff), errorNode);
  11815. }
  11816. methodMatcher.mBestMethodGenericArguments.resize(methodDef->mGenericParams.size());
  11817. for (int i = 0; i < std::min(methodDef->mGenericParams.size() - uniqueGenericStartIdx, methodMatcher.mExplicitMethodGenericArguments.size()); i++)
  11818. {
  11819. methodMatcher.mBestMethodGenericArguments[i + uniqueGenericStartIdx] = methodMatcher.mExplicitMethodGenericArguments[i];
  11820. }
  11821. }
  11822. BfMethodInstance* unspecializedMethod = NULL;
  11823. bool hasVarGenerics = false;
  11824. for (int checkGenericIdx = 0; checkGenericIdx < (int)methodMatcher.mBestMethodGenericArguments.size(); checkGenericIdx++)
  11825. {
  11826. BfMethodInstance* outerMethodInstance = NULL;
  11827. auto& genericArg = methodMatcher.mBestMethodGenericArguments[checkGenericIdx];
  11828. if (genericArg == NULL)
  11829. {
  11830. if ((methodDef->mIsLocalMethod) && (checkGenericIdx < mModule->mCurMethodInstance->GetNumGenericArguments()))
  11831. {
  11832. // If the root method is generic and we need that param then use that...
  11833. auto rootMethodInstance = rootMethodState->mMethodInstance;
  11834. if ((rootMethodInstance->mMethodInfoEx != NULL) && (checkGenericIdx < rootMethodInstance->mMethodInfoEx->mMethodGenericArguments.size()))
  11835. {
  11836. genericArg = rootMethodInstance->mMethodInfoEx->mMethodGenericArguments[checkGenericIdx];
  11837. }
  11838. else
  11839. {
  11840. if (localInferrableGenericArgCount == -1)
  11841. localInferrableGenericArgCount = mModule->GetLocalInferrableGenericArgCount(methodDef);
  11842. // Otherwise we can only infer generics at the level that the called method was contained
  11843. if (checkGenericIdx < localInferrableGenericArgCount)
  11844. genericArg = mModule->mCurMethodInstance->mMethodInfoEx->mMethodGenericArguments[checkGenericIdx];
  11845. }
  11846. }
  11847. }
  11848. if (genericArg == NULL)
  11849. {
  11850. if (unspecializedMethod == NULL)
  11851. unspecializedMethod = mModule->GetRawMethodInstance(curTypeInst, methodDef);
  11852. auto genericParam = unspecializedMethod->mMethodInfoEx->mGenericParams[checkGenericIdx];
  11853. if ((genericParam->mTypeConstraint != NULL) && (genericParam->mTypeConstraint->IsDelegate()))
  11854. {
  11855. // The only other option was to bind to a MethodRef
  11856. genericArg = mModule->ResolveGenericType(genericParam->mTypeConstraint, NULL, &methodMatcher.mBestMethodGenericArguments);
  11857. }
  11858. else
  11859. {
  11860. if (((genericParam->mGenericParamFlags & BfGenericParamFlag_Const) != 0) && (genericParam->mTypeConstraint != NULL))
  11861. {
  11862. for (int paramIdx = 0; paramIdx < (int)unspecializedMethod->mDefaultValues.size(); paramIdx++)
  11863. {
  11864. auto defaultVal = unspecializedMethod->mDefaultValues[paramIdx];
  11865. if (!defaultVal)
  11866. continue;
  11867. auto& param = unspecializedMethod->mParams[paramIdx];
  11868. if (param.mResolvedType->IsGenericParam())
  11869. {
  11870. auto genericParamType = (BfGenericParamType*)param.mResolvedType;
  11871. if ((genericParamType->mGenericParamKind == BfGenericParamKind_Method) && (genericParamType->mGenericParamIdx == checkGenericIdx))
  11872. {
  11873. BfTypedValue constExprVal;
  11874. constExprVal.mType = genericParam->mTypeConstraint;
  11875. auto constant = curTypeInst->mConstHolder->GetConstant(defaultVal.mValue);
  11876. constExprVal.mValue = mModule->ConstantToCurrent(constant, curTypeInst->mConstHolder, genericParam->mTypeConstraint);
  11877. genericArg = mModule->CreateConstExprValueType(constExprVal);
  11878. }
  11879. }
  11880. }
  11881. }
  11882. }
  11883. if (genericArg == NULL)
  11884. {
  11885. failed = true;
  11886. mModule->Fail(StrFormat("Unable to determine generic argument '%s'", methodDef->mGenericParams[checkGenericIdx]->mName.c_str()).c_str(), targetSrc);
  11887. if ((genericParam->mTypeConstraint != NULL) && (!genericParam->mTypeConstraint->IsUnspecializedType()))
  11888. genericArg = genericParam->mTypeConstraint;
  11889. else
  11890. genericArg = mModule->mContext->mBfObjectType;
  11891. }
  11892. resolvedGenericArguments.push_back(genericArg);
  11893. }
  11894. else
  11895. {
  11896. if (genericArg->IsVar())
  11897. {
  11898. BF_ASSERT(methodMatcher.mHasVarArguments);
  11899. hasVarGenerics = true;
  11900. }
  11901. if (genericArg->IsIntUnknown())
  11902. genericArg = mModule->GetPrimitiveType(BfTypeCode_IntPtr);
  11903. auto resolvedGenericArg = genericArg;
  11904. resolvedGenericArguments.push_back(resolvedGenericArg);
  11905. }
  11906. }
  11907. BfTypeInstance* foreignType = NULL;
  11908. BfGetMethodInstanceFlags flags = BfGetMethodInstanceFlag_None;
  11909. if ((mModule->mAttributeState != NULL) && (mModule->mAttributeState->mCustomAttributes != NULL) && (mModule->mAttributeState->mCustomAttributes->Contains(mModule->mCompiler->mInlineAttributeTypeDef)))
  11910. {
  11911. flags = (BfGetMethodInstanceFlags)(flags | BfGetMethodInstanceFlag_ForceInline);
  11912. }
  11913. if ((!mModule->mCurTypeInstance->IsInterface()) && (methodDef->mBody != NULL))
  11914. {
  11915. if ((methodMatcher.mBypassVirtual) && (methodMatcher.mBestMethodTypeInstance->IsInterface()))
  11916. {
  11917. // This is an explicit 'base' call to a default interface method. We pull the methodDef into our own concrete type.
  11918. foreignType = curTypeInst;
  11919. curTypeInst = mModule->mCurTypeInstance;
  11920. flags = (BfGetMethodInstanceFlags)(flags | BfGetMethodInstanceFlag_ForeignMethodDef);
  11921. }
  11922. else if ((methodDef->mIsStatic) && (curTypeInst->IsInterface()))
  11923. {
  11924. if (mModule->TypeIsSubTypeOf(mModule->mCurTypeInstance, curTypeInst))
  11925. {
  11926. // This is an explicit call to a default static interface method. We pull the methodDef into our own concrete type.
  11927. foreignType = curTypeInst;
  11928. curTypeInst = mModule->mCurTypeInstance;
  11929. flags = (BfGetMethodInstanceFlags)(flags | BfGetMethodInstanceFlag_ForeignMethodDef);
  11930. }
  11931. }
  11932. }
  11933. if (hasVarGenerics)
  11934. return BfModuleMethodInstance();
  11935. BfModuleMethodInstance methodInstance;
  11936. if (methodMatcher.mBestMethodInstance)
  11937. {
  11938. methodInstance = methodMatcher.mBestMethodInstance;
  11939. }
  11940. else
  11941. {
  11942. methodInstance = mModule->GetMethodInstance(curTypeInst, methodDef, resolvedGenericArguments, flags, foreignType);
  11943. }
  11944. if (mModule->IsSkippingExtraResolveChecks())
  11945. {
  11946. //BF_ASSERT(methodInstance.mFunc == NULL);
  11947. }
  11948. if (methodInstance.mMethodInstance == NULL)
  11949. return NULL;
  11950. if (methodDef->IsEmptyPartial())
  11951. return methodInstance;
  11952. if (methodInstance.mMethodInstance->mMethodInfoEx != NULL)
  11953. {
  11954. for (int checkGenericIdx = 0; checkGenericIdx < (int)methodInstance.mMethodInstance->mMethodInfoEx->mGenericParams.size(); checkGenericIdx++)
  11955. {
  11956. auto genericParams = methodInstance.mMethodInstance->mMethodInfoEx->mGenericParams[checkGenericIdx];
  11957. BfTypeVector* checkMethodGenericArgs = NULL;
  11958. BfType* genericArg = NULL;
  11959. if (checkGenericIdx < (int)methodMatcher.mBestMethodGenericArguments.size())
  11960. {
  11961. genericArg = methodMatcher.mBestMethodGenericArguments[checkGenericIdx];
  11962. }
  11963. else
  11964. {
  11965. checkMethodGenericArgs = &methodMatcher.mBestMethodGenericArguments;
  11966. genericArg = genericParams->mExternType;
  11967. auto owner = methodInstance.mMethodInstance->GetOwner();
  11968. BfTypeVector* typeGenericArguments = NULL;
  11969. if (owner->mGenericTypeInfo != NULL)
  11970. typeGenericArguments = &owner->mGenericTypeInfo->mTypeGenericArguments;
  11971. //genericArg = mModule->ResolveGenericType(genericArg, typeGenericArguments, checkMethodGenericArgs);
  11972. }
  11973. if (genericArg->IsVar())
  11974. continue;
  11975. BfAstNode* paramSrc;
  11976. if (checkGenericIdx >= methodMatcher.mBestMethodGenericArgumentSrcs.size())
  11977. {
  11978. paramSrc = targetSrc;
  11979. }
  11980. else
  11981. paramSrc = methodMatcher.mArguments[methodMatcher.mBestMethodGenericArgumentSrcs[checkGenericIdx]].mExpression;
  11982. // Note: don't pass methodMatcher.mBestMethodGenericArguments into here, this method is already specialized
  11983. BfError* error = NULL;
  11984. if (!mModule->CheckGenericConstraints(BfGenericParamSource(methodInstance.mMethodInstance), genericArg, paramSrc, genericParams, NULL,
  11985. failed ? NULL : &error))
  11986. {
  11987. if (methodInstance.mMethodInstance->IsSpecializedGenericMethod())
  11988. {
  11989. // We mark this as failed to make sure we don't try to process a method that doesn't even follow the constraints
  11990. methodInstance.mMethodInstance->mFailedConstraints = true;
  11991. }
  11992. if (methodInstance.mMethodInstance->mMethodDef->mMethodDeclaration != NULL)
  11993. {
  11994. if (error != NULL)
  11995. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("See method declaration"), methodInstance.mMethodInstance->mMethodDef->GetRefNode());
  11996. }
  11997. }
  11998. }
  11999. }
  12000. else
  12001. BF_ASSERT(methodMatcher.mBestMethodGenericArguments.IsEmpty());
  12002. return methodInstance;
  12003. }
  12004. void BfExprEvaluator::CheckLocalMethods(BfAstNode* targetSrc, BfTypeInstance* typeInstance, const StringImpl& methodName, BfMethodMatcher& methodMatcher, BfMethodType methodType)
  12005. {
  12006. auto _GetNodeId = [&]()
  12007. {
  12008. auto parser = targetSrc->GetSourceData()->ToParserData();
  12009. return ((int64)parser->mDataId << 32) + targetSrc->GetSrcStart();
  12010. };
  12011. BfMethodState* ctxMethodState = NULL;
  12012. BfClosureInstanceInfo* ctxClosureInstanceInfo = NULL;
  12013. if ((mModule->mCurMethodState != NULL) && (mModule->mCurMethodState->mClosureState != NULL))
  12014. {
  12015. ctxClosureInstanceInfo = mModule->mCurMethodState->mClosureState->mClosureInstanceInfo;
  12016. ctxMethodState = mModule->mCurMethodState;
  12017. }
  12018. bool atCtxMethodState = false;
  12019. auto checkMethodState = mModule->mCurMethodState;
  12020. auto rootMethodState = checkMethodState;
  12021. while (checkMethodState != NULL)
  12022. {
  12023. rootMethodState = checkMethodState;
  12024. if (checkMethodState == ctxMethodState)
  12025. atCtxMethodState = true;
  12026. if ((ctxClosureInstanceInfo != NULL) && (!ctxMethodState->mClosureState->mCapturing))
  12027. {
  12028. BfMethodDef* localMethodDef = NULL;
  12029. if (ctxClosureInstanceInfo->mLocalMethodBindings.TryGetValue(_GetNodeId(), &localMethodDef))
  12030. {
  12031. methodMatcher.CheckMethod(mModule->mCurTypeInstance, mModule->mCurTypeInstance, localMethodDef, true);
  12032. BF_ASSERT(methodMatcher.mBestMethodDef != NULL);
  12033. return;
  12034. }
  12035. }
  12036. else
  12037. {
  12038. BfLocalMethod* matchedLocalMethod = NULL;
  12039. BfLocalMethod* localMethod = NULL;
  12040. if (checkMethodState->mLocalMethodMap.TryGetValue(methodName, &localMethod))
  12041. {
  12042. auto typeInst = mModule->mCurTypeInstance;
  12043. if (checkMethodState->mMixinState != NULL)
  12044. typeInst = checkMethodState->mMixinState->mMixinMethodInstance->GetOwner();
  12045. while (localMethod != NULL)
  12046. {
  12047. auto methodDef = mModule->GetLocalMethodDef(localMethod);
  12048. if (methodDef->mMethodType == methodType)
  12049. {
  12050. methodMatcher.CheckMethod(mModule->mCurTypeInstance, typeInst, methodDef, true);
  12051. if (methodMatcher.mBestMethodDef == methodDef)
  12052. matchedLocalMethod = localMethod;
  12053. }
  12054. localMethod = localMethod->mNextWithSameName;
  12055. }
  12056. }
  12057. if (matchedLocalMethod != NULL)
  12058. {
  12059. if ((mModule->mCurMethodState != NULL) && (mModule->mCurMethodState->mClosureState != NULL) && (mModule->mCurMethodState->mClosureState->mCapturing))
  12060. {
  12061. BfModuleMethodInstance moduleMethodInstance = GetSelectedMethod(targetSrc, typeInstance, matchedLocalMethod->mMethodDef, methodMatcher);
  12062. if (moduleMethodInstance)
  12063. {
  12064. auto methodInstance = moduleMethodInstance.mMethodInstance;
  12065. if ((methodInstance->mMethodInfoEx != NULL) && (methodInstance->mMethodInfoEx->mClosureInstanceInfo->mCaptureClosureState != NULL))
  12066. {
  12067. // The called method is calling us from its mLocalMethodRefs set. Stretch our mCaptureStartAccessId back to incorporate its
  12068. // captures as well
  12069. if (methodInstance->mMethodInfoEx->mClosureInstanceInfo->mCaptureClosureState->mCaptureStartAccessId < mModule->mCurMethodState->mClosureState->mCaptureStartAccessId)
  12070. mModule->mCurMethodState->mClosureState->mCaptureStartAccessId = methodInstance->mMethodInfoEx->mClosureInstanceInfo->mCaptureClosureState->mCaptureStartAccessId;
  12071. }
  12072. else
  12073. {
  12074. if (methodInstance->mDisallowCalling) // We need to process the captures from this guy
  12075. {
  12076. if (mModule->mCurMethodState->mClosureState->mLocalMethodRefSet.Add(methodInstance))
  12077. mModule->mCurMethodState->mClosureState->mLocalMethodRefs.Add(methodInstance);
  12078. }
  12079. }
  12080. }
  12081. }
  12082. if (ctxClosureInstanceInfo != NULL)
  12083. {
  12084. BF_ASSERT(mModule->mCurMethodState->mClosureState->mCapturing);
  12085. ctxClosureInstanceInfo->mLocalMethodBindings[_GetNodeId()] = methodMatcher.mBestMethodDef;
  12086. }
  12087. break;
  12088. }
  12089. }
  12090. checkMethodState = checkMethodState->mPrevMethodState;
  12091. }
  12092. }
  12093. void BfExprEvaluator::InjectMixin(BfAstNode* targetSrc, BfTypedValue target, bool allowImplicitThis, const StringImpl& name, const BfSizedArray<BfExpression*>& arguments, BfSizedArray<ASTREF(BfTypeReference*)>* methodGenericArgs)
  12094. {
  12095. if (mModule->mCurMethodState == NULL)
  12096. return;
  12097. if (mDeferCallRef != NULL)
  12098. {
  12099. mModule->Fail("Mixins cannot be directly deferred. Consider wrapping in a block.", targetSrc);
  12100. }
  12101. BfAstNode* origTargetSrc = targetSrc;
  12102. BfScopedInvocationTarget* scopedInvocationTarget = NULL;
  12103. if (mModule->mParentNodeEntry != NULL)
  12104. {
  12105. if (auto invocationExpr = BfNodeDynCast<BfInvocationExpression>(mModule->mParentNodeEntry->mNode))
  12106. {
  12107. scopedInvocationTarget = BfNodeDynCast<BfScopedInvocationTarget>(invocationExpr->mTarget);
  12108. }
  12109. }
  12110. auto targetNameNode = targetSrc;
  12111. if (scopedInvocationTarget != NULL)
  12112. targetNameNode = scopedInvocationTarget->mTarget;
  12113. BfTypeInstance* mixinClass = NULL;
  12114. if (target.mType != NULL)
  12115. mixinClass = target.mType->ToTypeInstance();
  12116. int inLine = mModule->mCurFilePosition.mCurLine;
  12117. SizedArray<BfResolvedArg, 4> args;
  12118. SizedArray<BfExprEvaluator*, 8> argExprEvaluators;
  12119. defer
  12120. (
  12121. {
  12122. for (auto exprEvaluator : argExprEvaluators)
  12123. delete exprEvaluator;
  12124. }
  12125. );
  12126. auto _AddArg = [&](BfExpression* argExpr)
  12127. {
  12128. BfResolvedArg resolvedArg;
  12129. argExprEvaluators.push_back(new BfExprEvaluator(mModule));
  12130. BfExprEvaluator* exprEvaluator = argExprEvaluators.back();
  12131. exprEvaluator->mResolveGenericParam = false;
  12132. exprEvaluator->mBfEvalExprFlags = (BfEvalExprFlags)(exprEvaluator->mBfEvalExprFlags | BfEvalExprFlags_NoCast | BfEvalExprFlags_AllowRefExpr | BfEvalExprFlags_AllowOutExpr);
  12133. bool deferExpr = false;
  12134. if (auto variableDecl = BfNodeDynCast<BfVariableDeclaration>(argExpr))
  12135. {
  12136. deferExpr = true;
  12137. resolvedArg.mArgFlags = (BfArgFlags)(resolvedArg.mArgFlags | BfArgFlag_VariableDeclaration);
  12138. }
  12139. if (deferExpr)
  12140. {
  12141. //
  12142. }
  12143. else if (argExpr != NULL)
  12144. exprEvaluator->Evaluate(argExpr, false, false, true);
  12145. auto argValue = exprEvaluator->mResult;
  12146. mModule->FixIntUnknown(argValue);
  12147. if (argValue)
  12148. {
  12149. if (argValue.mType->IsRef())
  12150. {
  12151. exprEvaluator->FinishExpressionResult();
  12152. }
  12153. }
  12154. resolvedArg.mTypedValue = argValue;
  12155. resolvedArg.mExpression = argExpr;
  12156. args.push_back(resolvedArg);
  12157. };
  12158. for (BfExpression* argExpr : arguments)
  12159. {
  12160. _AddArg(argExpr);
  12161. }
  12162. auto autoComplete = GetAutoComplete();
  12163. if ((autoComplete != NULL) && (autoComplete->mIsCapturingMethodMatchInfo) && (autoComplete->mMethodMatchInfo->mInstanceList.size() != 0))
  12164. autoComplete->mIsCapturingMethodMatchInfo = false;
  12165. BfMethodMatcher methodMatcher(targetSrc, mModule, name, args, methodGenericArgs);
  12166. methodMatcher.mMethodType = BfMethodType_Mixin;
  12167. methodMatcher.mSkipImplicitParams = true;
  12168. auto curTypeInst = mModule->mCurTypeInstance;
  12169. if (mixinClass != NULL)
  12170. curTypeInst = mixinClass;
  12171. if (target.mType == NULL)
  12172. {
  12173. CheckLocalMethods(targetSrc, curTypeInst, name, methodMatcher, BfMethodType_Mixin);
  12174. }
  12175. if (methodMatcher.mBestMethodDef == NULL)
  12176. methodMatcher.mBestMethodDef = methodMatcher.mBackupMethodDef;
  12177. if (methodMatcher.mBestMethodDef == NULL)
  12178. {
  12179. if (mixinClass != NULL)
  12180. methodMatcher.CheckType(mixinClass, BfTypedValue(), false);
  12181. else
  12182. methodMatcher.CheckType(mModule->mCurTypeInstance, BfTypedValue(), false);
  12183. }
  12184. if ((methodMatcher.mBestMethodDef == NULL) && (target.mType == NULL) && (mModule->mContext->mCurTypeState != NULL))
  12185. {
  12186. BF_ASSERT(mModule->mCurTypeInstance == mModule->mContext->mCurTypeState->mTypeInstance);
  12187. BfGlobalLookup globalLookup;
  12188. globalLookup.mKind = BfGlobalLookup::Kind_Method;
  12189. globalLookup.mName = name;
  12190. mModule->PopulateGlobalContainersList(globalLookup);
  12191. for (auto& globalContainer : mModule->mContext->mCurTypeState->mGlobalContainers)
  12192. {
  12193. if (globalContainer.mTypeInst == NULL)
  12194. continue;
  12195. methodMatcher.CheckType(globalContainer.mTypeInst, BfTypedValue(), false);
  12196. if (methodMatcher.mBestMethodDef != NULL)
  12197. break;
  12198. }
  12199. }
  12200. if (methodMatcher.mBestMethodDef == NULL)
  12201. {
  12202. mModule->Fail("Cannot find mixin", targetSrc);
  12203. return;
  12204. }
  12205. auto resolvePassData = mModule->mCompiler->mResolvePassData;
  12206. if ((autoComplete != NULL) && (autoComplete->IsAutocompleteNode(targetNameNode)) && (autoComplete->mDefType == NULL))
  12207. {
  12208. autoComplete->mInsertStartIdx = targetNameNode->GetSrcStart();
  12209. autoComplete->mInsertEndIdx = targetNameNode->GetSrcEnd();
  12210. autoComplete->mDefType = methodMatcher.mBestMethodTypeInstance->mTypeDef;
  12211. autoComplete->mDefMethod = methodMatcher.mBestMethodDef;
  12212. autoComplete->SetDefinitionLocation(methodMatcher.mBestMethodDef->GetMethodDeclaration()->mNameNode);
  12213. }
  12214. if ((mModule->mCompiler->mResolvePassData != NULL) && (mModule->mCompiler->mResolvePassData->mGetSymbolReferenceKind == BfGetSymbolReferenceKind_Method))
  12215. {
  12216. targetNameNode->SetSrcEnd(targetNameNode->GetSrcEnd() - 1);
  12217. mModule->mCompiler->mResolvePassData->HandleMethodReference(targetNameNode, methodMatcher.mBestMethodTypeInstance->mTypeDef, methodMatcher.mBestMethodDef);
  12218. targetNameNode->SetSrcEnd(targetNameNode->GetSrcEnd() + 1);
  12219. }
  12220. auto curMethodState = mModule->mCurMethodState;
  12221. //
  12222. {
  12223. bool hasCircularRef = false;
  12224. auto checkMethodState = curMethodState;
  12225. while (checkMethodState != NULL)
  12226. {
  12227. auto curMixinState = checkMethodState->mMixinState;
  12228. while (curMixinState != NULL)
  12229. {
  12230. if (curMixinState->mSource == targetSrc)
  12231. hasCircularRef = true;
  12232. curMixinState = curMixinState->mPrevMixinState;
  12233. }
  12234. if ((checkMethodState->mClosureState != NULL) && (checkMethodState->mClosureState->mActiveDeferredLocalMethod != NULL))
  12235. {
  12236. for (auto& mixinRecord : checkMethodState->mClosureState->mActiveDeferredLocalMethod->mMixinStateRecords)
  12237. {
  12238. if (mixinRecord.mSource == targetSrc)
  12239. hasCircularRef = true;
  12240. }
  12241. }
  12242. checkMethodState = checkMethodState->mPrevMethodState;
  12243. }
  12244. if (hasCircularRef)
  12245. {
  12246. mModule->Fail("Circular reference detected between mixins", targetSrc);
  12247. return;
  12248. }
  12249. }
  12250. auto moduleMethodInstance = GetSelectedMethod(targetSrc, methodMatcher.mBestMethodTypeInstance, methodMatcher.mBestMethodDef, methodMatcher);
  12251. if (!moduleMethodInstance)
  12252. return;
  12253. auto methodInstance = moduleMethodInstance.mMethodInstance;
  12254. for (int checkGenericIdx = 0; checkGenericIdx < (int)methodMatcher.mBestMethodGenericArguments.size(); checkGenericIdx++)
  12255. {
  12256. auto& genericParams = methodInstance->mMethodInfoEx->mGenericParams;
  12257. auto genericArg = methodMatcher.mBestMethodGenericArguments[checkGenericIdx];
  12258. if (genericArg->IsVar())
  12259. continue;
  12260. BfAstNode* paramSrc;
  12261. if (methodMatcher.mBestMethodGenericArgumentSrcs.size() == 0)
  12262. paramSrc = targetSrc;
  12263. else
  12264. paramSrc = methodMatcher.mArguments[methodMatcher.mBestMethodGenericArgumentSrcs[checkGenericIdx]].mExpression;
  12265. // Note: don't pass methodMatcher.mBestMethodGenericArguments into here, this method is already specialized
  12266. BfError* error = NULL;
  12267. if (!mModule->CheckGenericConstraints(BfGenericParamSource(methodInstance), genericArg, paramSrc, genericParams[checkGenericIdx], NULL, &error))
  12268. {
  12269. if (methodInstance->mMethodDef->mMethodDeclaration != NULL)
  12270. {
  12271. if (error != NULL)
  12272. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("See method declaration"), methodInstance->mMethodDef->GetRefNode());
  12273. }
  12274. }
  12275. }
  12276. // Check circular ref based on methodInstance
  12277. {
  12278. bool hasCircularRef = false;
  12279. auto checkMethodState = curMethodState;
  12280. while (checkMethodState != NULL)
  12281. {
  12282. if (checkMethodState->mMethodInstance == methodInstance)
  12283. hasCircularRef = true;
  12284. auto curMixinState = checkMethodState->mMixinState;
  12285. while (curMixinState != NULL)
  12286. {
  12287. if (curMixinState->mMixinMethodInstance == methodInstance)
  12288. hasCircularRef = true;
  12289. curMixinState = curMixinState->mPrevMixinState;
  12290. }
  12291. checkMethodState = checkMethodState->mPrevMethodState;
  12292. }
  12293. if (hasCircularRef)
  12294. {
  12295. mModule->Fail("Circular reference detected between mixins", targetSrc);
  12296. return;
  12297. }
  12298. }
  12299. AddCallDependencies(methodInstance);
  12300. if (!methodMatcher.mBestMethodDef->mIsStatic)
  12301. {
  12302. if ((!target) && (allowImplicitThis))
  12303. target = mModule->GetThis();
  12304. if (!target)
  12305. {
  12306. BfError* error = mModule->Fail(StrFormat("An instance reference is required to invoke the non-static mixin '%s'",
  12307. mModule->MethodToString(methodInstance).c_str()), targetSrc);
  12308. if ((error != NULL) && (methodInstance->mMethodDef->GetRefNode() != NULL))
  12309. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("See method declaration"), methodInstance->mMethodDef->GetRefNode());
  12310. }
  12311. }
  12312. else
  12313. {
  12314. if (target)
  12315. {
  12316. BfError* error = mModule->Fail(StrFormat("Mixin '%s' cannot be accessed with an instance reference; qualify it with a type name instead",
  12317. mModule->MethodToString(methodInstance).c_str()), targetSrc);
  12318. if ((error != NULL) && (methodInstance->mMethodDef->GetRefNode() != NULL))
  12319. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("See method declaration"), methodInstance->mMethodDef->GetRefNode());
  12320. }
  12321. }
  12322. int methodParamCount = (int)methodInstance->GetParamCount();
  12323. // Implicit params are ignored for calling- they should be resolved at the injection site
  12324. int implicitParamCount = methodInstance->GetImplicitParamCount();
  12325. int explicitParamCount = methodParamCount - implicitParamCount;
  12326. while ((int)args.size() < explicitParamCount)
  12327. {
  12328. int argIdx = (int)args.size();
  12329. BfExpression* expr = methodInstance->GetParamInitializer(argIdx);
  12330. if (expr == NULL)
  12331. break;
  12332. _AddArg(expr);
  12333. }
  12334. if ((int)args.size() < explicitParamCount)
  12335. {
  12336. BfError* error = mModule->Fail(StrFormat("Not enough arguments specified, expected %d more.", explicitParamCount - (int)arguments.size()), targetSrc);
  12337. if ((error != NULL) && (methodInstance->mMethodDef->GetRefNode() != NULL))
  12338. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("See method declaration"), methodInstance->mMethodDef->GetRefNode());
  12339. return;
  12340. }
  12341. else if ((int)args.size() > explicitParamCount)
  12342. {
  12343. BfError* error = mModule->Fail(StrFormat("Too many arguments specified, expected %d fewer.", (int)arguments.size() - explicitParamCount), targetSrc);
  12344. if ((error != NULL) && (methodInstance->mMethodDef->GetRefNode() != NULL))
  12345. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("See method declaration"), methodInstance->mMethodDef->GetRefNode());
  12346. return;
  12347. }
  12348. int paramIdx = implicitParamCount;
  12349. auto argExprEvaluatorItr = argExprEvaluators.begin();
  12350. for (int argIdx = 0; argIdx < (int)args.size(); argIdx++)
  12351. {
  12352. auto exprEvaluator = *argExprEvaluatorItr;
  12353. //auto paramType = methodInstance->GetParamKind(paramIdx);
  12354. BfType* wantType = methodInstance->mParams[paramIdx].mResolvedType;
  12355. auto& arg = args[argIdx];
  12356. if ((arg.mArgFlags & BfArgFlag_VariableDeclaration) != 0)
  12357. {
  12358. arg.mTypedValue = ResolveArgValue(arg, wantType);
  12359. }
  12360. if (wantType->IsGenericParam())
  12361. {
  12362. //
  12363. }
  12364. else if (!wantType->IsVar())
  12365. {
  12366. if (arg.mTypedValue.mType == NULL)
  12367. {
  12368. mModule->AssertErrorState();
  12369. return;
  12370. }
  12371. if (arg.mTypedValue.mType != wantType)
  12372. {
  12373. exprEvaluator->FinishExpressionResult();
  12374. arg.mTypedValue = mModule->LoadValue(arg.mTypedValue);
  12375. arg.mTypedValue = mModule->Cast(arg.mExpression, arg.mTypedValue, wantType);
  12376. /*// Do this to generate default implicit cast error
  12377. mModule->Fail(StrFormat("Mixin argument type '%s' must match parameter type '%s'.",
  12378. mModule->TypeToString(arg.mTypedValue.mType).c_str(),
  12379. mModule->TypeToString(wantType).c_str()), arg.mExpression);
  12380. return;*/
  12381. }
  12382. }
  12383. paramIdx++;
  12384. argExprEvaluatorItr++;
  12385. }
  12386. mModule->AddDependency(methodInstance->GetOwner(), mModule->mCurTypeInstance, BfDependencyMap::DependencyFlag_InlinedCall);
  12387. auto startBlock = mModule->mBfIRBuilder->CreateBlock("mixinStart");
  12388. mModule->mBfIRBuilder->CreateBr(startBlock);
  12389. mModule->mBfIRBuilder->AddBlock(startBlock);
  12390. mModule->mBfIRBuilder->SetInsertPoint(startBlock);
  12391. //auto prevDebugLoc = mModule->mBfIRBuilder->getCurrentDebugLocation();
  12392. // This is so when we debug we can hit a steppoint on the inlined "call line"
  12393. mModule->EmitEnsureInstructionAt();
  12394. auto rootMethodState = mModule->mCurMethodState->GetRootMethodState();
  12395. BfMixinState* mixinState = rootMethodState->mMixinStates.Alloc();
  12396. mixinState->mPrevMixinState = curMethodState->mMixinState;
  12397. mixinState->mLocalsStartIdx = (int)mModule->mCurMethodState->mLocals.size();
  12398. mixinState->mMixinMethodInstance = methodInstance;
  12399. mixinState->mSource = origTargetSrc;
  12400. mixinState->mCallerScope = mModule->mCurMethodState->mCurScope;
  12401. mixinState->mTargetScope = mixinState->mCallerScope;
  12402. mixinState->mResultExpr = NULL;
  12403. mixinState->mHasDeferredUsage = false;
  12404. mixinState->mUsedInvocationScope = false;
  12405. mixinState->mTarget = target;
  12406. auto checkNode = origTargetSrc;
  12407. if (scopedInvocationTarget != NULL)
  12408. {
  12409. auto targetScope = mModule->FindScope(scopedInvocationTarget->mScopeName, curMethodState->mMixinState);
  12410. if (targetScope != NULL)
  12411. {
  12412. mixinState->mTargetScope = targetScope;
  12413. if (autoComplete != NULL)
  12414. {
  12415. if (auto identifer = BfNodeDynCast<BfIdentifierNode>(scopedInvocationTarget->mScopeName))
  12416. autoComplete->CheckLabel(identifer, NULL, targetScope);
  12417. }
  12418. }
  12419. }
  12420. mModule->mBfIRBuilder->SaveDebugLocation();
  12421. SetAndRestoreValue<BfMixinState*> prevMixinState(curMethodState->mMixinState, mixinState);
  12422. BfGetSymbolReferenceKind prevSymbolRefKind = BfGetSymbolReferenceKind_None;
  12423. if (mModule->mCompiler->mResolvePassData != NULL)
  12424. {
  12425. prevSymbolRefKind = mModule->mCompiler->mResolvePassData->mGetSymbolReferenceKind;
  12426. mModule->mCompiler->mResolvePassData->mGetSymbolReferenceKind = BfGetSymbolReferenceKind_None;
  12427. }
  12428. defer
  12429. (
  12430. {
  12431. if (mModule->mCompiler->mResolvePassData != NULL)
  12432. mModule->mCompiler->mResolvePassData->mGetSymbolReferenceKind = prevSymbolRefKind;
  12433. }
  12434. );
  12435. auto methodDef = methodInstance->mMethodDef;
  12436. auto methodDeclaration = methodDef->GetMethodDeclaration();
  12437. BfScopeData scopeData;
  12438. scopeData.mCloseNode = methodDeclaration->mBody;
  12439. if (auto block = BfNodeDynCast<BfBlock>(methodDeclaration->mBody))
  12440. {
  12441. if (block->mCloseBrace != NULL)
  12442. scopeData.mCloseNode = block->mCloseBrace;
  12443. }
  12444. curMethodState->AddScope(&scopeData);
  12445. curMethodState->mCurScope->mMixinDepth++;
  12446. // We can't flush scope state because we extend params in as arbitrary values
  12447. mModule->NewScopeState(true, false);
  12448. bool wantsDIData = (mModule->mBfIRBuilder->DbgHasInfo()) && (mModule->mHasFullDebugInfo);
  12449. DISubprogram* diFunction = NULL;
  12450. int mixinLocalVarIdx = -1;
  12451. int startLocalIdx = (int)mModule->mCurMethodState->mLocals.size();
  12452. int endLocalIdx = startLocalIdx;
  12453. if (wantsDIData)
  12454. {
  12455. BfIRMDNode diFuncType = mModule->mBfIRBuilder->DbgCreateSubroutineType(methodInstance);
  12456. //int defLine = mModule->mCurFilePosition.mCurLine;
  12457. int flags = 0;
  12458. curMethodState->mCurScope->mDIInlinedAt = mModule->mBfIRBuilder->DbgGetCurrentLocation();
  12459. // 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
  12460. // definitions, so we need to be consistent and use the actual line
  12461. mModule->UpdateSrcPos(methodDeclaration->mNameNode, BfSrcPosFlag_NoSetDebugLoc);
  12462. int defLine = mModule->mCurFilePosition.mCurLine;
  12463. auto diParentType = mModule->mBfIRBuilder->DbgGetTypeInst(methodInstance->GetOwner());
  12464. if (!mModule->mBfIRBuilder->mIgnoreWrites)
  12465. {
  12466. String methodName = methodDef->mName;
  12467. methodName += "!";
  12468. BfMangler::Mangle(methodName, mModule->mCompiler->GetMangleKind(), methodInstance);
  12469. curMethodState->mCurScope->mDIScope = mModule->mBfIRBuilder->DbgCreateFunction(diParentType, methodName, "", mModule->mCurFilePosition.mFileInstance->mDIFile,
  12470. defLine + 1, diFuncType, false, true, mModule->mCurFilePosition.mCurLine + 1, flags, false, BfIRValue());
  12471. scopeData.mAltDIFile = mModule->mCurFilePosition.mFileInstance->mDIFile;
  12472. }
  12473. }
  12474. if (methodDef->mBody != NULL)
  12475. mModule->UpdateSrcPos(methodDef->mBody);
  12476. mModule->SetIllegalSrcPos();
  12477. auto _AddLocalVariable = [&](BfLocalVariable* newLocalVar, BfExprEvaluator* exprEvaluator)
  12478. {
  12479. mModule->SetIllegalSrcPos();
  12480. bool hasConstValue = newLocalVar->mConstValue;
  12481. if (hasConstValue)
  12482. {
  12483. auto constant = mModule->mBfIRBuilder->GetConstant(newLocalVar->mConstValue);
  12484. hasConstValue = constant->mConstType < BfConstType_GlobalVar;
  12485. }
  12486. if ((exprEvaluator != NULL) && (exprEvaluator->mResultLocalVar != NULL) && (exprEvaluator->mResultLocalVarField == 0))
  12487. {
  12488. mModule->UpdateSrcPos(methodDeclaration->mNameNode);
  12489. mModule->AddLocalVariableDef(newLocalVar, hasConstValue);
  12490. auto inLocalVar = exprEvaluator->mResultLocalVar;
  12491. newLocalVar->mAssignedKind = inLocalVar->mAssignedKind;
  12492. newLocalVar->mUnassignedFieldFlags = inLocalVar->mUnassignedFieldFlags;
  12493. newLocalVar->mReadFromId = inLocalVar->mReadFromId;
  12494. newLocalVar->mIsReadOnly = inLocalVar->mIsReadOnly;
  12495. if ((newLocalVar->mAssignedKind == BfLocalVarAssignKind_None) && (mModule->mCurMethodState->mDeferredLocalAssignData != NULL))
  12496. {
  12497. for (auto deferredAssign : mModule->mCurMethodState->mDeferredLocalAssignData->mAssignedLocals)
  12498. {
  12499. if (deferredAssign.mLocalVar == inLocalVar)
  12500. newLocalVar->mAssignedKind = BfLocalVarAssignKind_Unconditional;
  12501. }
  12502. }
  12503. }
  12504. else
  12505. {
  12506. mModule->AddLocalVariableDef(newLocalVar, hasConstValue);
  12507. }
  12508. if ((wantsDIData) && (!mModule->mBfIRBuilder->mIgnoreWrites))
  12509. {
  12510. mModule->UpdateSrcPos(methodDeclaration->mNameNode);
  12511. if (hasConstValue)
  12512. {
  12513. // Already handled
  12514. }
  12515. else if (newLocalVar->mIsSplat)
  12516. {
  12517. bool found = false;
  12518. auto checkMethodState = mModule->mCurMethodState;
  12519. while ((checkMethodState != NULL) && (!found))
  12520. {
  12521. for (auto localVar : checkMethodState->mLocals)
  12522. {
  12523. if (localVar == newLocalVar)
  12524. continue;
  12525. if (!localVar->mIsSplat)
  12526. continue;
  12527. if (newLocalVar->mValue != localVar->mAddr)
  12528. continue;
  12529. String name = "$";
  12530. name += newLocalVar->mName;
  12531. name += "$alias$";
  12532. name += localVar->mName;
  12533. // auto fakeValue = mModule->mBfIRBuilder->CreateConst(BfTypeCode_Int32, 0);
  12534. // auto diType = mModule->mBfIRBuilder->DbgGetType(mModule->GetPrimitiveType(BfTypeCode_Int32));
  12535. // auto diVariable = mModule->mBfIRBuilder->DbgCreateAutoVariable(mModule->mCurMethodState->mCurScope->mDIScope,
  12536. // name, mModule->mCurFilePosition.mFileInstance->mDIFile, mModule->mCurFilePosition.mCurLine, diType);
  12537. // mModule->mBfIRBuilder->DbgInsertValueIntrinsic(fakeValue, diVariable);
  12538. auto diType = mModule->mBfIRBuilder->DbgGetType(mModule->GetPrimitiveType(BfTypeCode_NullPtr));
  12539. auto diVariable = mModule->mBfIRBuilder->DbgCreateAutoVariable(mModule->mCurMethodState->mCurScope->mDIScope,
  12540. name, mModule->mCurFilePosition.mFileInstance->mDIFile, mModule->mCurFilePosition.mCurLine, diType);
  12541. mModule->mBfIRBuilder->DbgInsertValueIntrinsic(mModule->mBfIRBuilder->CreateConstNull(), diVariable);
  12542. found = true;
  12543. break;
  12544. }
  12545. checkMethodState = checkMethodState->mPrevMethodState;
  12546. }
  12547. }
  12548. else if (mModule->IsTargetingBeefBackend())
  12549. {
  12550. mModule->UpdateSrcPos(methodDeclaration->mNameNode);
  12551. mModule->SetIllegalSrcPos();
  12552. // With the Beef backend we can assign two variables to the same value, but LLVM does not allow this
  12553. // so we have to create a ref to that variable
  12554. auto diType = mModule->mBfIRBuilder->DbgGetType(newLocalVar->mResolvedType);
  12555. auto diVariable = mModule->mBfIRBuilder->DbgCreateAutoVariable(mModule->mCurMethodState->mCurScope->mDIScope,
  12556. newLocalVar->mName, mModule->mCurFilePosition.mFileInstance->mDIFile, mModule->mCurFilePosition.mCurLine, diType);
  12557. if (newLocalVar->mIsSplat)
  12558. {
  12559. //TODO: Implement
  12560. }
  12561. else if (newLocalVar->mResolvedType->IsValuelessType())
  12562. {
  12563. // Do nothing
  12564. }
  12565. else
  12566. {
  12567. BfIRValue value = newLocalVar->mValue;
  12568. if (newLocalVar->mAddr)
  12569. value = newLocalVar->mAddr;
  12570. else if (newLocalVar->mConstValue)
  12571. value = newLocalVar->mConstValue;
  12572. auto aliasValue = mModule->mBfIRBuilder->CreateAliasValue(value);
  12573. if (mModule->WantsLifetimes())
  12574. scopeData.mDeferredLifetimeEnds.Add(aliasValue);
  12575. if (newLocalVar->mAddr)
  12576. mModule->mBfIRBuilder->DbgInsertDeclare(aliasValue, diVariable);
  12577. else
  12578. {
  12579. mModule->mBfIRBuilder->DbgInsertValueIntrinsic(aliasValue, diVariable);
  12580. //mModule->mBfIRBuilder->DbgInsertValueIntrinsic(newLocalVar->mValue, diVariable);
  12581. }
  12582. }
  12583. }
  12584. else if (newLocalVar->mAddr)
  12585. {
  12586. mModule->UpdateSrcPos(methodDeclaration->mNameNode);
  12587. mModule->SetIllegalSrcPos();
  12588. auto refType = mModule->CreateRefType(newLocalVar->mResolvedType);
  12589. auto allocaVal = mModule->CreateAlloca(refType);
  12590. mModule->mBfIRBuilder->CreateStore(newLocalVar->mAddr, allocaVal);
  12591. if (!mModule->mBfIRBuilder->mIgnoreWrites)
  12592. {
  12593. auto diType = mModule->mBfIRBuilder->DbgGetType(refType);
  12594. auto diVariable = mModule->mBfIRBuilder->DbgCreateAutoVariable(mModule->mCurMethodState->mCurScope->mDIScope,
  12595. newLocalVar->mName, mModule->mCurFilePosition.mFileInstance->mDIFile, mModule->mCurFilePosition.mCurLine, diType);
  12596. mModule->mBfIRBuilder->DbgInsertDeclare(allocaVal, diVariable);
  12597. }
  12598. }
  12599. else if (newLocalVar->mValue)
  12600. {
  12601. mModule->UpdateSrcPos(methodDeclaration->mNameNode);
  12602. mModule->SetIllegalSrcPos();
  12603. auto localVal = LoadLocal(newLocalVar);
  12604. localVal = mModule->LoadValue(localVal);
  12605. localVal = mModule->AggregateSplat(localVal);
  12606. BfType* allocType = localVal.mType;
  12607. auto allocaVal = mModule->CreateAlloca(allocType);
  12608. mModule->mBfIRBuilder->CreateStore(localVal.mValue, allocaVal);
  12609. if (!mModule->mBfIRBuilder->mIgnoreWrites)
  12610. {
  12611. if (newLocalVar->mIsSplat)
  12612. {
  12613. //TODO: Implement
  12614. }
  12615. else
  12616. {
  12617. auto diType = mModule->mBfIRBuilder->DbgGetType(allocType);
  12618. auto diVariable = mModule->mBfIRBuilder->DbgCreateAutoVariable(mModule->mCurMethodState->mCurScope->mDIScope,
  12619. newLocalVar->mName, mModule->mCurFilePosition.mFileInstance->mDIFile, mModule->mCurFilePosition.mCurLine, diType);
  12620. mModule->mBfIRBuilder->DbgInsertDeclare(allocaVal, diVariable);
  12621. }
  12622. }
  12623. }
  12624. }
  12625. newLocalVar->mParamIdx = -3;
  12626. };
  12627. argExprEvaluatorItr = argExprEvaluators.begin();
  12628. for (int argIdx = methodDef->mIsStatic ? 0 : -1; argIdx < (int)explicitParamCount; argIdx++)
  12629. {
  12630. int paramIdx = argIdx;
  12631. auto exprEvaluator = *argExprEvaluatorItr;
  12632. BfTypedValue argValue;
  12633. BfLocalVariable* localVar = new BfLocalVariable();
  12634. if (argIdx == -1)
  12635. {
  12636. argValue = target;
  12637. localVar->mName = "this";
  12638. localVar->mIsThis = true;
  12639. localVar->mAssignedKind = BfLocalVarAssignKind_Unconditional;
  12640. }
  12641. else
  12642. {
  12643. auto arg = &args[argIdx];
  12644. auto paramDef = methodDef->mParams[paramIdx];
  12645. localVar->mName = paramDef->mName;
  12646. if (!arg->mTypedValue)
  12647. {
  12648. auto wantType = methodInstance->GetParamType(paramIdx);
  12649. if (wantType->IsVar())
  12650. wantType = mModule->mContext->mBfObjectType;
  12651. arg->mTypedValue = mModule->GetDefaultTypedValue(wantType);
  12652. }
  12653. argValue = arg->mTypedValue;
  12654. }
  12655. if (!argValue)
  12656. continue;
  12657. localVar->mResolvedType = argValue.mType;
  12658. if (argValue.mType->IsRef())
  12659. {
  12660. auto refType = (BfRefType*)localVar->mResolvedType;
  12661. localVar->mAddr = mModule->LoadValue(argValue).mValue;
  12662. localVar->mResolvedType = argValue.mType->GetUnderlyingType();
  12663. localVar->mAssignedKind = (refType->mRefKind != BfRefType::RefKind_Out) ? BfLocalVarAssignKind_Unconditional : BfLocalVarAssignKind_None;
  12664. }
  12665. else if (argValue.IsAddr())
  12666. localVar->mAddr = argValue.mValue;
  12667. else
  12668. {
  12669. if (!argValue.mValue)
  12670. {
  12671. // Untyped value
  12672. }
  12673. else if (argValue.mValue.IsConst())
  12674. {
  12675. localVar->mConstValue = argValue.mValue;
  12676. }
  12677. else if (argValue.IsSplat())
  12678. {
  12679. localVar->mValue = argValue.mValue;
  12680. localVar->mIsSplat = true;
  12681. }
  12682. else
  12683. {
  12684. if (argValue.IsAddr())
  12685. localVar->mAddr = argValue.mValue;
  12686. else
  12687. localVar->mValue = argValue.mValue;
  12688. }
  12689. localVar->mIsReadOnly = argValue.IsReadOnly();
  12690. }
  12691. if (argValue.IsReadOnly())
  12692. localVar->mIsReadOnly = true;
  12693. if (argIdx == -1)
  12694. {
  12695. _AddLocalVariable(localVar, NULL);
  12696. }
  12697. else
  12698. {
  12699. _AddLocalVariable(localVar, exprEvaluator);
  12700. endLocalIdx++;
  12701. ++argExprEvaluatorItr;
  12702. }
  12703. }
  12704. if (auto blockBody = BfNodeDynCast<BfBlock>(methodDef->mBody))
  12705. mModule->VisitCodeBlock(blockBody);
  12706. if (mixinState->mResultExpr != NULL)
  12707. {
  12708. if (auto exprNode = BfNodeDynCast<BfExpression>(mixinState->mResultExpr))
  12709. {
  12710. if (!exprNode->IsA<BfBlock>())
  12711. {
  12712. // Mixin expression result
  12713. mModule->UpdateSrcPos(exprNode);
  12714. VisitChild(exprNode);
  12715. FinishExpressionResult();
  12716. ResolveGenericType();
  12717. //mResult = mModule->LoadValue(mResult);
  12718. }
  12719. }
  12720. }
  12721. GetResult();
  12722. if (!mResult)
  12723. {
  12724. // If we didn't have an expression body then just make the result "void"
  12725. mResult = BfTypedValue(BfIRValue(), mModule->GetPrimitiveType(BfTypeCode_None));
  12726. }
  12727. int localIdx = startLocalIdx;
  12728. if (mixinLocalVarIdx != -1)
  12729. {
  12730. BfLocalVariable* localVar = curMethodState->mLocals[localIdx];
  12731. if (mResultLocalVar != NULL)
  12732. {
  12733. auto inLocalVar = mResultLocalVar;
  12734. if (localVar->mAssignedKind != BfLocalVarAssignKind_None)
  12735. inLocalVar->mAssignedKind = BfLocalVarAssignKind_Unconditional;
  12736. if (localVar->mReadFromId != -1)
  12737. inLocalVar->mReadFromId = mModule->mCurMethodState->GetRootMethodState()->mCurAccessId++;
  12738. }
  12739. localIdx++;
  12740. }
  12741. argExprEvaluatorItr = argExprEvaluators.begin();
  12742. for (; localIdx < endLocalIdx; localIdx++)
  12743. {
  12744. auto exprEvaluator = *argExprEvaluatorItr;
  12745. BfLocalVariable* localVar = curMethodState->mLocals[localIdx];
  12746. //TODO: Merge unassigned flags together
  12747. if ((exprEvaluator != NULL) && (exprEvaluator->mResultLocalVar != NULL))
  12748. {
  12749. auto inLocalVar = exprEvaluator->mResultLocalVar;
  12750. if (localVar->mAssignedKind != BfLocalVarAssignKind_None)
  12751. inLocalVar->mAssignedKind = BfLocalVarAssignKind_Unconditional;
  12752. if (localVar->mReadFromId != -1)
  12753. inLocalVar->mReadFromId = mModule->mCurMethodState->GetRootMethodState()->mCurAccessId++;
  12754. }
  12755. ++argExprEvaluatorItr;
  12756. }
  12757. if (auto blockBody = BfNodeDynCast<BfBlock>(methodDef->mBody))
  12758. if (blockBody->mCloseBrace != NULL)
  12759. mModule->UpdateSrcPos(blockBody->mCloseBrace);
  12760. mModule->RestoreScopeState();
  12761. prevMixinState.Restore();
  12762. if (mixinState->mHasDeferredUsage)
  12763. {
  12764. // if (target)
  12765. // {
  12766. // if (target.mType->IsValuelessType())
  12767. // mixinState->mTarget = target;
  12768. // else
  12769. // {
  12770. // target = mModule->LoadValue(target);
  12771. // auto savedTarget = BfTypedValue(mModule->CreateAlloca(target.mType, false), target.mType, true);
  12772. // mModule->mBfIRBuilder->CreateStore(target.mValue, savedTarget.mValue);
  12773. // mixinState->mTarget = savedTarget;
  12774. // }
  12775. // }
  12776. mixinState->mTarget = BfTypedValue();
  12777. }
  12778. else
  12779. {
  12780. BF_ASSERT(rootMethodState->mMixinStates.back() == mixinState);
  12781. rootMethodState->mMixinStates.pop_back();
  12782. delete mixinState;
  12783. }
  12784. if ((scopedInvocationTarget != NULL) && (scopedInvocationTarget->mScopeName != NULL) && (!mixinState->mUsedInvocationScope))
  12785. {
  12786. mModule->Warn(0, "Scope specifier was not referenced in mixin", scopedInvocationTarget->mScopeName);
  12787. }
  12788. mModule->mBfIRBuilder->RestoreDebugLocation();
  12789. mModule->mBfIRBuilder->DupDebugLocation();
  12790. }
  12791. void BfExprEvaluator::SetMethodElementType(BfAstNode* target)
  12792. {
  12793. if (auto delegateBindExpr = BfNodeDynCast<BfDelegateBindExpression>(target))
  12794. {
  12795. SetMethodElementType(delegateBindExpr->mTarget);
  12796. return;
  12797. }
  12798. if (auto lambdaBindExpr = BfNodeDynCast<BfLambdaBindExpression>(target))
  12799. {
  12800. return;
  12801. }
  12802. if (auto attributedIdentifierNode = BfNodeDynCast<BfAttributedIdentifierNode>(target))
  12803. {
  12804. if (attributedIdentifierNode->mIdentifier != NULL)
  12805. mModule->SetElementType(attributedIdentifierNode->mIdentifier, BfSourceElementType_Method);
  12806. }
  12807. else if (auto memberReferenceExpr = BfNodeDynCast<BfMemberReferenceExpression>(target))
  12808. {
  12809. if (memberReferenceExpr->mMemberName != NULL)
  12810. SetMethodElementType(memberReferenceExpr->mMemberName);
  12811. }
  12812. else if (auto qualifiedNameNode = BfNodeDynCast<BfQualifiedNameNode>(target))
  12813. SetMethodElementType(qualifiedNameNode->mRight);
  12814. else
  12815. mModule->SetElementType(target, BfSourceElementType_Method);
  12816. }
  12817. void BfExprEvaluator::DoInvocation(BfAstNode* target, BfMethodBoundExpression* methodBoundExpr, const BfSizedArray<BfExpression*>& args, BfSizedArray<ASTREF(BfTypeReference*)>* methodGenericArguments, BfTypedValue* outCascadeValue)
  12818. {
  12819. // Just a check
  12820. mModule->mBfIRBuilder->GetInsertBlock();
  12821. bool wasCapturingMethodInfo = false;
  12822. auto autoComplete = GetAutoComplete();
  12823. if ((autoComplete != NULL) && (methodGenericArguments != NULL))
  12824. {
  12825. for (BfTypeReference* methodGenericArg : *methodGenericArguments)
  12826. autoComplete->CheckTypeRef(methodGenericArg, false, true);
  12827. }
  12828. if ((autoComplete != NULL) && (autoComplete->mIsCapturingMethodMatchInfo))
  12829. {
  12830. // We don't want to capture a call within the target node
  12831. wasCapturingMethodInfo = true;
  12832. autoComplete->mIsCapturingMethodMatchInfo = false;
  12833. }
  12834. bool allowImplicitThis = false;
  12835. BfAstNode* methodNodeSrc = target;
  12836. BfAttributeState attributeState;
  12837. attributeState.mTarget = (BfAttributeTargets)(BfAttributeTargets_Invocation | BfAttributeTargets_MemberAccess);
  12838. if (auto scopedTarget = BfNodeDynCast<BfScopedInvocationTarget>(target))
  12839. {
  12840. target = scopedTarget->mTarget;
  12841. if (autoComplete != NULL)
  12842. {
  12843. if (auto identifier = BfNodeDynCast<BfIdentifierNode>(scopedTarget->mScopeName))
  12844. autoComplete->CheckLabel(identifier, scopedTarget->mColonToken, NULL);
  12845. }
  12846. //mModule->FindScope(scopedTarget->mScopeName);
  12847. }
  12848. bool isCascade = false;
  12849. BfAstNode* cascadeOperatorToken = NULL;
  12850. bool bypassVirtual = false;
  12851. bool gaveUnqualifiedDotError = false;
  12852. String targetFunctionName;
  12853. BfTypedValue thisValue;
  12854. //TODO: This may just be a fully qualified static method name, so let's check that also
  12855. if (auto memberRefExpression = BfNodeDynCast<BfMemberReferenceExpression>(target))
  12856. {
  12857. if (autoComplete != NULL)
  12858. {
  12859. if (memberRefExpression->mTarget != NULL)
  12860. autoComplete->CheckMemberReference(memberRefExpression->mTarget, memberRefExpression->mDotToken, memberRefExpression->mMemberName, false, mExpectingType);
  12861. else if (mExpectingType != NULL)
  12862. {
  12863. String filter;
  12864. if ((autoComplete != NULL) && (autoComplete->InitAutocomplete(memberRefExpression->mDotToken, memberRefExpression->mMemberName, filter)))
  12865. {
  12866. auto typeInst = mExpectingType->ToTypeInstance();
  12867. if (typeInst != NULL)
  12868. {
  12869. String filter;
  12870. if ((memberRefExpression->mMemberName != NULL) && (autoComplete->IsAutocompleteNode(memberRefExpression->mMemberName)))
  12871. filter = autoComplete->GetFilter(memberRefExpression->mMemberName);
  12872. bool allowPrivate = typeInst == mModule->mCurTypeInstance;
  12873. autoComplete->AddEnumTypeMembers(typeInst, filter, false, allowPrivate);
  12874. autoComplete->AddSelfResultTypeMembers(typeInst, typeInst, filter, allowPrivate);
  12875. }
  12876. }
  12877. }
  12878. }
  12879. if ((memberRefExpression->mTarget == NULL) && (memberRefExpression->mMemberName == NULL))
  12880. {
  12881. auto expectingType = mExpectingType;
  12882. if ((expectingType != NULL) && (expectingType->IsNullable()))
  12883. {
  12884. auto underlyingType = expectingType->GetUnderlyingType();
  12885. expectingType = underlyingType;
  12886. }
  12887. if (expectingType != NULL)
  12888. {
  12889. if (expectingType->IsSizedArray())
  12890. {
  12891. if (mModule->mParentNodeEntry != NULL)
  12892. {
  12893. if (auto invocationExpr = BfNodeDynCast<BfInvocationExpression>(mModule->mParentNodeEntry->mNode))
  12894. {
  12895. InitializedSizedArray((BfSizedArrayType*)expectingType, invocationExpr->mOpenParen, invocationExpr->mArguments, invocationExpr->mCommas, invocationExpr->mCloseParen);
  12896. return;
  12897. }
  12898. }
  12899. }
  12900. else if (expectingType->IsStruct())
  12901. {
  12902. if ((wasCapturingMethodInfo) && (autoComplete->mMethodMatchInfo != NULL))
  12903. {
  12904. autoComplete->mIsCapturingMethodMatchInfo = true;
  12905. BF_ASSERT(autoComplete->mMethodMatchInfo != NULL);
  12906. }
  12907. if (mModule->mParentNodeEntry != NULL)
  12908. {
  12909. if (auto invocationExpr = BfNodeDynCast<BfInvocationExpression>(mModule->mParentNodeEntry->mNode))
  12910. {
  12911. BfResolvedArgs argValues(invocationExpr->mOpenParen, &invocationExpr->mArguments, &invocationExpr->mCommas, invocationExpr->mCloseParen);
  12912. BfResolveArgFlags resolveArgsFlags = BfResolveArgFlag_DeferParamEval;
  12913. ResolveArgValues(argValues, resolveArgsFlags);
  12914. if ((mReceivingValue != NULL) && (mReceivingValue->mType == expectingType) && (mReceivingValue->IsAddr()))
  12915. {
  12916. mResult = *mReceivingValue;
  12917. mReceivingValue = NULL;
  12918. }
  12919. else
  12920. mResult = BfTypedValue(mModule->CreateAlloca(expectingType), expectingType, BfTypedValueKind_TempAddr);
  12921. MatchConstructor(target, methodBoundExpr, mResult, expectingType->ToTypeInstance(), argValues, false, false);
  12922. mModule->ValidateAllocation(expectingType, invocationExpr->mTarget);
  12923. return;
  12924. }
  12925. }
  12926. }
  12927. else if (expectingType->IsGenericParam())
  12928. {
  12929. if (mModule->mParentNodeEntry != NULL)
  12930. {
  12931. if (auto invocationExpr = BfNodeDynCast<BfInvocationExpression>(mModule->mParentNodeEntry->mNode))
  12932. {
  12933. BfResolvedArgs argValues(invocationExpr->mOpenParen, &invocationExpr->mArguments, &invocationExpr->mCommas, invocationExpr->mCloseParen);
  12934. BfResolveArgFlags resolveArgsFlags = BfResolveArgFlag_None;
  12935. ResolveArgValues(argValues, resolveArgsFlags);
  12936. CheckGenericCtor((BfGenericParamType*)expectingType, argValues, invocationExpr->mTarget);
  12937. mResult = mModule->GetDefaultTypedValue(expectingType);
  12938. return;
  12939. }
  12940. }
  12941. }
  12942. else
  12943. {
  12944. gaveUnqualifiedDotError = true;
  12945. mModule->Fail(StrFormat("Cannot use inferred constructor on type '%s'", mModule->TypeToString(expectingType).c_str()), memberRefExpression->mDotToken);
  12946. }
  12947. }
  12948. }
  12949. if (memberRefExpression->IsA<BfBaseExpression>())
  12950. bypassVirtual = true;
  12951. if (memberRefExpression->mMemberName != NULL)
  12952. methodNodeSrc = memberRefExpression->mMemberName;
  12953. if (auto attrIdentifier = BfNodeDynCast<BfAttributedIdentifierNode>(memberRefExpression->mMemberName))
  12954. {
  12955. if (attrIdentifier->mIdentifier != NULL)
  12956. methodNodeSrc = attrIdentifier->mIdentifier;
  12957. attributeState.mSrc = attrIdentifier->mAttributes;
  12958. attributeState.mCustomAttributes = mModule->GetCustomAttributes(attrIdentifier->mAttributes, attributeState.mTarget);
  12959. if (attrIdentifier->mIdentifier != NULL)
  12960. targetFunctionName = attrIdentifier->mIdentifier->ToString();
  12961. }
  12962. else if (memberRefExpression->mMemberName != NULL)
  12963. targetFunctionName = memberRefExpression->mMemberName->ToString();
  12964. if (memberRefExpression->mTarget == NULL)
  12965. {
  12966. if (mExpectingType)
  12967. mResult = BfTypedValue(mExpectingType);
  12968. else if (!gaveUnqualifiedDotError)
  12969. mModule->Fail("Unqualified dot syntax can only be used when the result type can be inferred", memberRefExpression->mDotToken);
  12970. }
  12971. else if (auto typeRef = BfNodeDynCast<BfTypeReference>(memberRefExpression->mTarget))
  12972. {
  12973. // Static method
  12974. mResult = BfTypedValue(ResolveTypeRef(typeRef));
  12975. }
  12976. if (auto leftIdentifier = BfNodeDynCast<BfIdentifierNode>(memberRefExpression->mTarget))
  12977. {
  12978. bool hadError = false;
  12979. thisValue = LookupIdentifier(leftIdentifier, true, &hadError);
  12980. CheckResultForReading(thisValue);
  12981. if (mPropDef != NULL)
  12982. thisValue = GetResult(true);
  12983. if (hadError)
  12984. {
  12985. mModule->AssertErrorState();
  12986. thisValue = mModule->GetDefaultTypedValue(mModule->mContext->mBfObjectType);
  12987. }
  12988. if ((!thisValue) && (mPropDef == NULL))
  12989. {
  12990. // Identifier not found. Static method? Just check speculatively don't throw error
  12991. BfType* type;
  12992. {
  12993. SetAndRestoreValue<bool> prevIgnoreErrors(mModule->mIgnoreErrors, true);
  12994. type = mModule->ResolveTypeRef(leftIdentifier, NULL, BfPopulateType_DataAndMethods, BfResolveTypeRefFlag_NoResolveGenericParam);
  12995. }
  12996. if (type != NULL)
  12997. thisValue = BfTypedValue(type);
  12998. else if (auto qualifiedLeft = BfNodeDynCast<BfQualifiedNameNode>(leftIdentifier))
  12999. {
  13000. LookupQualifiedStaticField(qualifiedLeft, true);
  13001. thisValue = mResult;
  13002. mResult = BfTypedValue();
  13003. }
  13004. }
  13005. if (mPropDef != NULL)
  13006. thisValue = GetResult(true);
  13007. if (!thisValue.mType)
  13008. {
  13009. mModule->Fail("Identifier not found", leftIdentifier);
  13010. mModule->CheckTypeRefFixit(leftIdentifier);
  13011. thisValue = mModule->GetDefaultTypedValue(mModule->mContext->mBfObjectType);
  13012. }
  13013. if (mResult)
  13014. CheckResultForReading(mResult);
  13015. mResult = thisValue;
  13016. }
  13017. else if (auto expr = BfNodeDynCast<BfExpression>(memberRefExpression->mTarget))
  13018. {
  13019. BfType* expectingTargetType = NULL;
  13020. if (memberRefExpression->mDotToken->mToken == BfToken_DotDot)
  13021. expectingTargetType = mExpectingType;
  13022. bool handled = false;
  13023. if (auto subMemberRefExpr = BfNodeDynCast<BfMemberReferenceExpression>(expr))
  13024. {
  13025. String findName;
  13026. if (subMemberRefExpr->mMemberName != NULL)
  13027. findName = subMemberRefExpr->mMemberName->ToString();
  13028. if (findName == "base") // Generic IFace<T>.base
  13029. {
  13030. thisValue = mModule->GetThis();
  13031. if (thisValue)
  13032. {
  13033. VisitChild(subMemberRefExpr->mTarget);
  13034. if (mResult.HasType())
  13035. {
  13036. if (mResult.mValue)
  13037. {
  13038. mModule->Fail("Type name expected", subMemberRefExpr->mTarget);
  13039. }
  13040. else
  13041. {
  13042. auto type = mResult.mType;
  13043. if (type != NULL)
  13044. {
  13045. if ((thisValue.mType == type) || (!mModule->TypeIsSubTypeOf(thisValue.mType->ToTypeInstance(), type->ToTypeInstance())))
  13046. {
  13047. mModule->Fail(StrFormat("Type '%s' is not a base type of '%s'",
  13048. mModule->TypeToString(type).c_str(),
  13049. mModule->TypeToString(thisValue.mType).c_str()), subMemberRefExpr->mTarget);
  13050. }
  13051. else
  13052. {
  13053. if (type->IsInterface())
  13054. {
  13055. thisValue.mType = type;
  13056. }
  13057. else
  13058. {
  13059. auto castedThis = mModule->Cast(subMemberRefExpr->mMemberName, thisValue, type, BfCastFlags_Explicit);
  13060. if (castedThis)
  13061. thisValue = castedThis;
  13062. //mModule->Fail("Explicit base types can only be used for specifying default interface members", qualifiedLeft->mLeft);
  13063. }
  13064. }
  13065. handled = true;
  13066. }
  13067. bypassVirtual = true;
  13068. }
  13069. }
  13070. }
  13071. }
  13072. }
  13073. if (!handled)
  13074. {
  13075. SetAndRestoreValue<BfAttributeState*> prevAttributeState(mModule->mAttributeState, &attributeState);
  13076. auto flags = (BfEvalExprFlags)(BfEvalExprFlags_PropogateNullConditional | BfEvalExprFlags_NoCast);
  13077. if (mFunctionBindResult != NULL)
  13078. {
  13079. if (auto paranExpr = BfNodeDynCast<BfParenthesizedExpression>(expr))
  13080. {
  13081. // Allow 'ref' on binding, to indicate we want to capture 'this' by reference
  13082. flags = (BfEvalExprFlags)(flags | BfEvalExprFlags_AllowRefExpr);
  13083. expr = paranExpr->mExpression;
  13084. }
  13085. }
  13086. if (expr != NULL)
  13087. mResult = mModule->CreateValueFromExpression(expr, expectingTargetType, flags);
  13088. }
  13089. }
  13090. isCascade = (memberRefExpression->mDotToken != NULL) && (memberRefExpression->mDotToken->GetToken() == BfToken_DotDot);
  13091. if (isCascade)
  13092. cascadeOperatorToken = memberRefExpression->mDotToken;
  13093. bool isNullCondLookup = (memberRefExpression->mDotToken != NULL) && (memberRefExpression->mDotToken->GetToken() == BfToken_QuestionDot);
  13094. if (isNullCondLookup)
  13095. mResult = SetupNullConditional(mResult, memberRefExpression->mDotToken);
  13096. if ((mResult.mType == NULL) && (memberRefExpression->mTarget != NULL))
  13097. {
  13098. mModule->AssertErrorState();
  13099. mResult = mModule->GetDefaultTypedValue(mModule->mContext->mBfObjectType);
  13100. }
  13101. thisValue = mResult;
  13102. mResult = BfTypedValue();
  13103. }
  13104. else if (auto qualifiedName = BfNodeDynCast<BfQualifiedNameNode>(target))
  13105. {
  13106. if (GetAutoComplete() != NULL)
  13107. GetAutoComplete()->CheckMemberReference(qualifiedName->mLeft, qualifiedName->mDot, qualifiedName->mRight);
  13108. if (qualifiedName->mLeft->GetSrcLength() == 4)
  13109. {
  13110. if (CheckIsBase(qualifiedName->mLeft))
  13111. bypassVirtual = true;
  13112. }
  13113. if (qualifiedName->mRight != NULL)
  13114. methodNodeSrc = qualifiedName->mRight;
  13115. if (auto attrIdentifier = BfNodeDynCast<BfAttributedIdentifierNode>(qualifiedName->mRight))
  13116. {
  13117. if (attrIdentifier->mIdentifier != NULL)
  13118. methodNodeSrc = attrIdentifier->mIdentifier;
  13119. attributeState.mSrc = attrIdentifier->mAttributes;
  13120. attributeState.mCustomAttributes = mModule->GetCustomAttributes(attrIdentifier->mAttributes, attributeState.mTarget);
  13121. targetFunctionName = attrIdentifier->mIdentifier->ToString();
  13122. }
  13123. else
  13124. targetFunctionName = qualifiedName->mRight->ToString();
  13125. bool hadError = false;
  13126. thisValue = LookupIdentifier(qualifiedName->mLeft, true, &hadError);
  13127. CheckResultForReading(thisValue);
  13128. if (mPropDef != NULL)
  13129. thisValue = GetResult(true);
  13130. if (hadError)
  13131. {
  13132. mModule->AssertErrorState();
  13133. thisValue = mModule->GetDefaultTypedValue(mModule->mContext->mBfObjectType);
  13134. }
  13135. if ((!thisValue) && (mPropDef == NULL))
  13136. {
  13137. // Identifier not found. Static method? Just check speculatively don't throw error
  13138. BfType* type;
  13139. {
  13140. //SetAndRestoreValue<bool> prevIgnoreErrors(mModule->mIgnoreErrors, true);
  13141. type = mModule->ResolveTypeRef(qualifiedName->mLeft, NULL, BfPopulateType_DataAndMethods, (BfResolveTypeRefFlags)(BfResolveTypeRefFlag_NoResolveGenericParam | BfResolveTypeRefFlag_IgnoreLookupError));
  13142. }
  13143. if (type == NULL)
  13144. {
  13145. //SetAndRestoreValue<bool> prevIgnoreErrors(mModule->mIgnoreErrors, true);
  13146. type = mModule->ResolveTypeRef(qualifiedName, methodGenericArguments, BfPopulateType_DataAndMethods, (BfResolveTypeRefFlags)(BfResolveTypeRefFlag_NoResolveGenericParam | BfResolveTypeRefFlag_IgnoreLookupError));
  13147. if (type != NULL)
  13148. {
  13149. // This is a CTOR call, treat it as such
  13150. targetFunctionName.clear();
  13151. }
  13152. }
  13153. if (type != NULL)
  13154. thisValue = BfTypedValue(type);
  13155. else if (auto qualifiedLeft = BfNodeDynCast<BfQualifiedNameNode>(qualifiedName->mLeft))
  13156. {
  13157. String findName = qualifiedLeft->mRight->ToString();
  13158. bool handled = false;
  13159. if (findName == "base")
  13160. {
  13161. auto type = mModule->ResolveTypeRef(qualifiedLeft->mLeft, NULL, BfPopulateType_Data, BfResolveTypeRefFlag_AllowRef);
  13162. mModule->CheckTypeRefFixit(qualifiedLeft->mLeft);
  13163. thisValue = mModule->GetThis();
  13164. if (type != NULL)
  13165. {
  13166. if ((thisValue.mType == type) || (!mModule->TypeIsSubTypeOf(thisValue.mType->ToTypeInstance(), type->ToTypeInstance())))
  13167. {
  13168. mModule->Fail(StrFormat("Type '%s' is not a base type of '%s'",
  13169. mModule->TypeToString(type).c_str(),
  13170. mModule->TypeToString(thisValue.mType).c_str()), qualifiedLeft->mLeft);
  13171. }
  13172. else
  13173. {
  13174. if (type->IsInterface())
  13175. {
  13176. thisValue.mType = type;
  13177. }
  13178. else
  13179. {
  13180. auto castedThis = mModule->Cast(qualifiedLeft->mRight, thisValue, type, BfCastFlags_Explicit);
  13181. if (castedThis)
  13182. thisValue = castedThis;
  13183. //mModule->Fail("Explicit base types can only be used for specifying default interface members", qualifiedLeft->mLeft);
  13184. }
  13185. }
  13186. handled = true;
  13187. }
  13188. bypassVirtual = true;
  13189. }
  13190. if (!handled)
  13191. {
  13192. LookupQualifiedStaticField(qualifiedLeft, true);
  13193. thisValue = mResult;
  13194. mResult = BfTypedValue();
  13195. }
  13196. }
  13197. }
  13198. if (mPropDef != NULL)
  13199. thisValue = GetResult(true);
  13200. if (!thisValue.mType)
  13201. {
  13202. mModule->Fail("Identifier not found", qualifiedName->mLeft);
  13203. mModule->CheckTypeRefFixit(qualifiedName->mLeft);
  13204. mModule->CheckIdentifierFixit(qualifiedName->mLeft);
  13205. thisValue = mModule->GetDefaultTypedValue(mModule->GetPrimitiveType(BfTypeCode_Var));
  13206. }
  13207. if (mResult)
  13208. CheckResultForReading(mResult);
  13209. mResult = BfTypedValue();
  13210. }
  13211. else if (auto identiferExpr = BfNodeDynCast<BfIdentifierNode>(target))
  13212. {
  13213. if (auto attrIdentifier = BfNodeDynCast<BfAttributedIdentifierNode>(target))
  13214. {
  13215. if (attrIdentifier->mIdentifier != NULL)
  13216. methodNodeSrc = attrIdentifier->mIdentifier;
  13217. attributeState.mSrc = attrIdentifier->mAttributes;
  13218. attributeState.mCustomAttributes = mModule->GetCustomAttributes(attrIdentifier->mAttributes, attributeState.mTarget);
  13219. }
  13220. allowImplicitThis = true;
  13221. if (autoComplete != NULL)
  13222. autoComplete->CheckIdentifier(identiferExpr);
  13223. targetFunctionName = target->ToString();
  13224. if (targetFunctionName == "PrintF") // Just directly call that one
  13225. {
  13226. BfType* charType = mModule->GetPrimitiveType(BfTypeCode_Char8);
  13227. BfType* charPtrType = mModule->CreatePointerType(charType);
  13228. auto func = mModule->GetBuiltInFunc(BfBuiltInFuncType_PrintF);
  13229. SizedArray<BfIRValue, 4> irArgs;
  13230. for (BfExpression* arg : args)
  13231. {
  13232. BfTypedValue value;
  13233. if (arg != NULL)
  13234. value = mModule->CreateValueFromExpression(arg);
  13235. if (!value)
  13236. return;
  13237. auto typeInst = value.mType->ToTypeInstance();
  13238. if ((typeInst != NULL) && (typeInst->mTypeDef == mModule->mCompiler->mStringTypeDef))
  13239. value = mModule->Cast(arg, value, charPtrType);
  13240. if ((value.mType->IsFloat()) && (value.mType->mSize != 8)) // Always cast float to double
  13241. value = mModule->Cast(arg, value, mModule->GetPrimitiveType(BfTypeCode_Double));
  13242. irArgs.push_back(value.mValue);
  13243. }
  13244. if ((targetFunctionName != "PrintF") || (irArgs.size() > 0))
  13245. {
  13246. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateCall(func, irArgs/*, targetFunctionName*/),
  13247. mModule->ResolveTypeDef(mModule->mSystem->mTypeInt32));
  13248. }
  13249. return;
  13250. }
  13251. }
  13252. else if (auto expr = BfNodeDynCast<BfExpression>(target))
  13253. {
  13254. auto innerInvocationResult = mModule->CreateValueFromExpression(expr);
  13255. if (!innerInvocationResult)
  13256. {
  13257. mModule->AssertErrorState();
  13258. innerInvocationResult = mModule->GetDefaultTypedValue(mModule->mContext->mBfObjectType);
  13259. }
  13260. if (innerInvocationResult.mType->IsVar())
  13261. {
  13262. mResult = innerInvocationResult;
  13263. return;
  13264. }
  13265. targetFunctionName = "Invoke";
  13266. if (innerInvocationResult.mType->IsTypeInstance())
  13267. {
  13268. auto invocationTypeInst = innerInvocationResult.mType->ToTypeInstance();
  13269. if (invocationTypeInst->mTypeDef->mIsDelegate)
  13270. {
  13271. thisValue = innerInvocationResult;
  13272. }
  13273. }
  13274. if (!thisValue)
  13275. {
  13276. mModule->Fail(StrFormat("Cannot perform invocation on type '%s'", mModule->TypeToString(innerInvocationResult.mType).c_str()), expr);
  13277. thisValue = mModule->GetDefaultTypedValue(mModule->mContext->mBfObjectType);
  13278. }
  13279. }
  13280. else
  13281. {
  13282. mModule->Fail("Invalid invocation target", target);
  13283. thisValue = mModule->GetDefaultTypedValue(mModule->mContext->mBfObjectType);
  13284. }
  13285. if ((wasCapturingMethodInfo) && (autoComplete->mMethodMatchInfo != NULL))
  13286. {
  13287. autoComplete->mIsCapturingMethodMatchInfo = true;
  13288. BF_ASSERT(autoComplete->mMethodMatchInfo != NULL);
  13289. }
  13290. SetAndRestoreValue<BfAttributeState*> prevAttributeState;
  13291. if (attributeState.mCustomAttributes != NULL)
  13292. prevAttributeState.Init(mModule->mAttributeState, &attributeState);
  13293. if ((targetFunctionName != "") && (targetFunctionName[targetFunctionName.length() - 1] == '!'))
  13294. {
  13295. targetFunctionName = targetFunctionName.Substring(0, targetFunctionName.length() - 1);
  13296. InjectMixin(methodNodeSrc, thisValue, allowImplicitThis, targetFunctionName, args, methodGenericArguments);
  13297. return;
  13298. }
  13299. //TODO: We removed this... Messed up with PrimStruct 'this' non-mut errors
  13300. // 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
  13301. /*if (thisValue)
  13302. {
  13303. if ((!thisValue.mType->IsGenericParam()) && (!thisValue.IsSplat()) && (!thisValue.mType->IsVar()))
  13304. thisValue = MakeCallableTarget(target, thisValue);
  13305. }*/
  13306. int methodCount = 0;
  13307. bool mayBeSkipCall = false;
  13308. if (thisValue.mType != NULL)
  13309. {
  13310. if (thisValue.mType->IsAllocType())
  13311. thisValue.mType = thisValue.mType->GetUnderlyingType();
  13312. auto checkTypeInst = thisValue.mType->ToTypeInstance();
  13313. while (checkTypeInst != NULL)
  13314. {
  13315. checkTypeInst->mTypeDef->PopulateMemberSets();
  13316. BfMemberSetEntry* memberSetEntry;
  13317. if (checkTypeInst->mTypeDef->mMethodSet.TryGetWith(targetFunctionName, &memberSetEntry))
  13318. {
  13319. BfMethodDef* methodDef = (BfMethodDef*)memberSetEntry->mMemberDef;
  13320. while (methodDef != NULL)
  13321. {
  13322. if (methodDef->mIsSkipCall)
  13323. mayBeSkipCall = true;
  13324. methodDef = methodDef->mNextWithSameName;
  13325. }
  13326. }
  13327. checkTypeInst = checkTypeInst->mBaseType;
  13328. }
  13329. }
  13330. SizedArray<BfExpression*, 8> copiedArgs;
  13331. for (BfExpression* arg : args)
  13332. copiedArgs.push_back(arg);
  13333. BfSizedArray<BfExpression*> sizedCopiedArgs(copiedArgs);
  13334. BfResolvedArgs argValues(&sizedCopiedArgs);
  13335. if (mModule->mParentNodeEntry != NULL)
  13336. {
  13337. if (auto invocationExpr = BfNodeDynCast<BfInvocationExpression>(mModule->mParentNodeEntry->mNode))
  13338. {
  13339. argValues.mOpenToken = invocationExpr->mOpenParen;
  13340. argValues.mCommas = &invocationExpr->mCommas;
  13341. argValues.mCloseToken = invocationExpr->mCloseParen;
  13342. }
  13343. }
  13344. BfResolveArgFlags resolveArgsFlags = (BfResolveArgFlags)(BfResolveArgFlag_DeferFixits | BfResolveArgFlag_AllowUnresolvedTypes);
  13345. resolveArgsFlags = (BfResolveArgFlags)(resolveArgsFlags | BfResolveArgFlag_DeferParamEval);
  13346. if (mayBeSkipCall)
  13347. resolveArgsFlags = (BfResolveArgFlags)(resolveArgsFlags | BfResolveArgFlag_DeferParamValues);
  13348. static int sCallIdx = 0;
  13349. sCallIdx++;
  13350. int callIdx = sCallIdx;
  13351. if (callIdx == 1557)
  13352. {
  13353. NOP;
  13354. }
  13355. BfCheckedKind checkedKind = BfCheckedKind_NotSet;
  13356. if ((mModule->mAttributeState != NULL) && (mModule->mAttributeState->mCustomAttributes != NULL))
  13357. {
  13358. if (mModule->mAttributeState->mCustomAttributes->Contains(mModule->mCompiler->mCheckedAttributeTypeDef))
  13359. {
  13360. checkedKind = BfCheckedKind_Checked;
  13361. mModule->mAttributeState->mUsed = true;
  13362. }
  13363. if (mModule->mAttributeState->mCustomAttributes->Contains(mModule->mCompiler->mUncheckedAttributeTypeDef))
  13364. {
  13365. checkedKind = BfCheckedKind_Unchecked;
  13366. mModule->mAttributeState->mUsed = true;
  13367. }
  13368. }
  13369. SetAndRestoreValue<bool> prevUsedAsStatement(mUsedAsStatement, mUsedAsStatement || isCascade);
  13370. ResolveArgValues(argValues, resolveArgsFlags);
  13371. mResult = MatchMethod(methodNodeSrc, methodBoundExpr, thisValue, allowImplicitThis, bypassVirtual, targetFunctionName, argValues, methodGenericArguments, checkedKind);
  13372. argValues.HandleFixits(mModule);
  13373. if (mModule->mAttributeState == &attributeState)
  13374. mModule->FinishAttributeState(&attributeState);
  13375. if (isCascade)
  13376. {
  13377. if ((outCascadeValue != NULL) && (thisValue.mValue))
  13378. {
  13379. *outCascadeValue = thisValue;
  13380. }
  13381. else
  13382. {
  13383. mModule->Fail("Invalid use of cascade operator", cascadeOperatorToken);
  13384. }
  13385. }
  13386. }
  13387. void BfExprEvaluator::Visit(BfInvocationExpression* invocationExpr)
  13388. {
  13389. BfAutoParentNodeEntry autoParentNodeEntry(mModule, invocationExpr);
  13390. // We need to check for sized array constructor like "uint8[2](1, 2)"
  13391. if (BfNodeDynCastExact<BfIndexerExpression>(invocationExpr->mTarget) != NULL)
  13392. {
  13393. auto checkTarget = invocationExpr->mTarget;
  13394. while (auto indexerExpr = BfNodeDynCastExact<BfIndexerExpression>(checkTarget))
  13395. {
  13396. checkTarget = indexerExpr->mTarget;
  13397. }
  13398. SetAndRestoreValue<bool> prevIgnoreError(mModule->mIgnoreErrors, true);
  13399. auto resolvedType = mModule->ResolveTypeRef(checkTarget, NULL, BfPopulateType_Identity);
  13400. prevIgnoreError.Restore();
  13401. if (resolvedType != NULL)
  13402. {
  13403. BfType* curType = resolvedType;
  13404. auto checkTarget = invocationExpr->mTarget;
  13405. while (auto indexerExpr = BfNodeDynCastExact<BfIndexerExpression>(checkTarget))
  13406. {
  13407. checkTarget = indexerExpr->mTarget;
  13408. if (indexerExpr->mCommas.size() != 0)
  13409. 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]);
  13410. int arrSize = 0;
  13411. BfTypeState typeState;
  13412. typeState.mArrayInitializerSize = (int)invocationExpr->mArguments.size();
  13413. SetAndRestoreValue<BfTypeState*> prevTypeState(mModule->mContext->mCurTypeState, &typeState);
  13414. if (indexerExpr->mArguments.size() != 0)
  13415. {
  13416. BfConstResolver constResolver(mModule);
  13417. auto arg = indexerExpr->mArguments[0];
  13418. constResolver.mExpectingType = mModule->GetPrimitiveType(BfTypeCode_IntPtr);
  13419. if (arg != NULL)
  13420. constResolver.Resolve(arg, NULL, BfConstResolveFlag_ArrayInitSize);
  13421. if (constResolver.mResult.mValue.IsConst())
  13422. {
  13423. auto constant = mModule->mBfIRBuilder->GetConstant(constResolver.mResult.mValue);
  13424. if ((mModule->mBfIRBuilder->IsInt(constant->mTypeCode)) && (constant->mInt64 >= 0))
  13425. {
  13426. arrSize = constant->mInt32;
  13427. }
  13428. else
  13429. mModule->Fail("Non-negative integer expected", indexerExpr->mArguments[0]);
  13430. }
  13431. }
  13432. else
  13433. arrSize = invocationExpr->mArguments.size();
  13434. curType = mModule->CreateSizedArrayType(curType, arrSize);
  13435. }
  13436. InitializedSizedArray((BfSizedArrayType*)curType, invocationExpr->mOpenParen, invocationExpr->mArguments, invocationExpr->mCommas, invocationExpr->mCloseParen, NULL);
  13437. return;
  13438. }
  13439. }
  13440. auto autoComplete = GetAutoComplete();
  13441. auto wasCapturingMethodInfo = (autoComplete != NULL) && (autoComplete->mIsCapturingMethodMatchInfo);
  13442. if (autoComplete != NULL)
  13443. autoComplete->CheckInvocation(invocationExpr, invocationExpr->mOpenParen, invocationExpr->mCloseParen, invocationExpr->mCommas);
  13444. mModule->UpdateExprSrcPos(invocationExpr);
  13445. BfSizedArray<ASTREF(BfTypeReference*)>* methodGenericArguments = NULL;
  13446. if (invocationExpr->mGenericArgs != NULL)
  13447. methodGenericArguments = &invocationExpr->mGenericArgs->mGenericArgs;
  13448. SizedArray<BfExpression*, 8> copiedArgs;
  13449. for (BfExpression* arg : invocationExpr->mArguments)
  13450. copiedArgs.push_back(arg);
  13451. BfTypedValue cascadeValue;
  13452. DoInvocation(invocationExpr->mTarget, invocationExpr, copiedArgs, methodGenericArguments, &cascadeValue);
  13453. if (autoComplete != NULL)
  13454. {
  13455. if ((wasCapturingMethodInfo) && (!autoComplete->mIsCapturingMethodMatchInfo))
  13456. {
  13457. if (autoComplete->mMethodMatchInfo != NULL)
  13458. autoComplete->mIsCapturingMethodMatchInfo = true;
  13459. else
  13460. autoComplete->mIsCapturingMethodMatchInfo = false;
  13461. //BF_ASSERT(autoComplete->mMethodMatchInfo != NULL);
  13462. }
  13463. else
  13464. autoComplete->mIsCapturingMethodMatchInfo = false;
  13465. }
  13466. /// Previous check for discard
  13467. if (cascadeValue)
  13468. mResult = cascadeValue;
  13469. }
  13470. BfMethodDef* BfExprEvaluator::GetPropertyMethodDef(BfPropertyDef* propDef, BfMethodType methodType, BfCheckedKind checkedKind, BfTypedValue propTarget)
  13471. {
  13472. bool allowMut = true;
  13473. if ((propTarget) && (propTarget.mType->IsValueType()))
  13474. {
  13475. if (propTarget.IsReadOnly())
  13476. {
  13477. allowMut = false;
  13478. }
  13479. else if (!propTarget.IsAddr())
  13480. {
  13481. mModule->PopulateType(propTarget.mType);
  13482. if (!propTarget.IsValuelessType())
  13483. allowMut = false;
  13484. }
  13485. }
  13486. int bestPri = -1000;
  13487. BfMethodDef* matchedMethod = NULL;
  13488. for (auto methodDef : propDef->mMethods)
  13489. {
  13490. if (methodDef->mMethodType != methodType)
  13491. continue;
  13492. int curPri = 0;
  13493. if (methodDef->mCheckedKind == checkedKind)
  13494. {
  13495. curPri = 5;
  13496. }
  13497. else if ((checkedKind == BfCheckedKind_NotSet) && (methodDef->mCheckedKind == mModule->GetDefaultCheckedKind()))
  13498. curPri = 3;
  13499. else
  13500. curPri = 1;
  13501. if (methodDef->mIsMutating)
  13502. {
  13503. if (allowMut)
  13504. curPri++;
  13505. else
  13506. curPri -= 10;
  13507. }
  13508. if (curPri > bestPri)
  13509. {
  13510. bestPri = curPri;
  13511. matchedMethod = methodDef;
  13512. }
  13513. }
  13514. return matchedMethod;
  13515. /*BfMethodDef* matchedMethod = NULL;
  13516. BfMethodDef* backupMethod = NULL;
  13517. for (auto methodDef : propDef->mMethods)
  13518. {
  13519. if (methodDef->mMethodType != methodType)
  13520. continue;
  13521. if (methodDef->mCheckedKind == checkedKind)
  13522. {
  13523. matchedMethod = methodDef;
  13524. break;
  13525. }
  13526. if ((checkedKind == BfCheckedKind_NotSet) && (methodDef->mCheckedKind == mModule->GetDefaultCheckedKind()))
  13527. matchedMethod = methodDef;
  13528. else
  13529. backupMethod = methodDef;
  13530. }
  13531. if (matchedMethod == NULL)
  13532. matchedMethod = backupMethod;
  13533. return matchedMethod;*/
  13534. }
  13535. BfModuleMethodInstance BfExprEvaluator::GetPropertyMethodInstance(BfMethodDef* methodDef)
  13536. {
  13537. if (mPropDefBypassVirtual)
  13538. {
  13539. if (mPropTarget.mType->IsInterface())
  13540. {
  13541. auto curTypeInst = mPropTarget.mType->ToTypeInstance();
  13542. if (mModule->TypeIsSubTypeOf(mModule->mCurTypeInstance, curTypeInst))
  13543. {
  13544. if (methodDef->mBody != NULL)
  13545. {
  13546. // This is an explicit call to a default static interface method. We pull the methodDef into our own concrete type.
  13547. mPropTarget = mModule->GetThis();
  13548. return mModule->GetMethodInstance(mModule->mCurTypeInstance, methodDef, BfTypeVector(), BfGetMethodInstanceFlag_ForeignMethodDef, curTypeInst);
  13549. }
  13550. }
  13551. else
  13552. {
  13553. mModule->Fail("Property is not implemented by this type", mPropSrc);
  13554. return BfModuleMethodInstance();
  13555. }
  13556. }
  13557. else
  13558. {
  13559. auto propTypeInst = mPropTarget.mType->ToTypeInstance();
  13560. mModule->PopulateType(propTypeInst, BfPopulateType_DataAndMethods);
  13561. auto rawMethodInstance = mModule->GetRawMethodInstance(propTypeInst, methodDef);
  13562. if (rawMethodInstance->mVirtualTableIdx == -1)
  13563. {
  13564. if (!mModule->mCompiler->mIsResolveOnly)
  13565. {
  13566. // ResolveOnly does not force methods to slot
  13567. BF_ASSERT(rawMethodInstance->mVirtualTableIdx != -1);
  13568. mModule->Fail(StrFormat("Failed to devirtualize %s", mModule->MethodToString(rawMethodInstance).c_str()));
  13569. }
  13570. }
  13571. else
  13572. {
  13573. auto useTypeInst = mOrigPropTarget.mType->ToTypeInstance();
  13574. auto virtualMethod = (BfMethodInstance*)useTypeInst->mVirtualMethodTable[rawMethodInstance->mVirtualTableIdx].mImplementingMethod;
  13575. return mModule->ReferenceExternalMethodInstance(virtualMethod);
  13576. }
  13577. }
  13578. }
  13579. if ((mOrigPropTarget) && (mOrigPropTarget.mType != mPropTarget.mType) &&
  13580. ((!mOrigPropTarget.mType->IsGenericParam()) && (mPropTarget.mType->IsInterface())))
  13581. {
  13582. auto checkType = mOrigPropTarget.mType;
  13583. if (checkType->IsPointer())
  13584. checkType = ((BfPointerType*)checkType)->mElementType;
  13585. if (checkType->IsWrappableType())
  13586. checkType = mModule->GetWrappedStructType(checkType);
  13587. if ((checkType != NULL) && (checkType->IsTypeInstance()))
  13588. {
  13589. auto activeTypeDef = mModule->GetActiveTypeDef();
  13590. BfTypeInterfaceEntry* bestIFaceEntry = NULL;
  13591. bool checkedUnderlying = false;
  13592. auto checkTypeInst = checkType->ToTypeInstance();
  13593. while (checkTypeInst != NULL)
  13594. {
  13595. mModule->PopulateType(checkTypeInst, BfPopulateType_DataAndMethods);
  13596. for (auto& iface : checkTypeInst->mInterfaces)
  13597. {
  13598. if (!mModule->IsInSpecializedSection())
  13599. {
  13600. if (!checkTypeInst->IsTypeMemberAccessible(iface.mDeclaringType, activeTypeDef))
  13601. continue;
  13602. }
  13603. if (iface.mInterfaceType == mPropTarget.mType)
  13604. {
  13605. if (bestIFaceEntry == NULL)
  13606. {
  13607. bestIFaceEntry = &iface;
  13608. continue;
  13609. }
  13610. bool isBetter;
  13611. bool isWorse;
  13612. mModule->CompareDeclTypes(iface.mDeclaringType, bestIFaceEntry->mDeclaringType, isBetter, isWorse);
  13613. if (isBetter == isWorse)
  13614. {
  13615. // Failed
  13616. }
  13617. else
  13618. {
  13619. if (isBetter)
  13620. bestIFaceEntry = &iface;
  13621. }
  13622. }
  13623. }
  13624. if (bestIFaceEntry != NULL)
  13625. break;
  13626. checkTypeInst = checkTypeInst->mBaseType;
  13627. if (checkTypeInst == NULL)
  13628. {
  13629. if (!checkedUnderlying)
  13630. {
  13631. checkedUnderlying = true;
  13632. if (checkType->HasWrappedRepresentation())
  13633. {
  13634. auto underlyingType = checkType->GetUnderlyingType();
  13635. if (underlyingType != NULL)
  13636. checkTypeInst = mModule->GetWrappedStructType(underlyingType);
  13637. }
  13638. }
  13639. }
  13640. }
  13641. if (bestIFaceEntry != NULL)
  13642. {
  13643. auto ifaceMethodEntry = checkTypeInst->mInterfaceMethodTable[bestIFaceEntry->mStartInterfaceTableIdx + methodDef->mIdx];
  13644. BfMethodInstance* bestMethodInstance = ifaceMethodEntry.mMethodRef;
  13645. if (bestMethodInstance != NULL)
  13646. {
  13647. mPropTarget = mOrigPropTarget;
  13648. mPropTarget.mType = checkTypeInst;
  13649. return mModule->GetMethodInstanceAtIdx(ifaceMethodEntry.mMethodRef.mTypeInstance, ifaceMethodEntry.mMethodRef.mMethodNum);
  13650. }
  13651. }
  13652. }
  13653. mModule->AssertErrorState();
  13654. return BfModuleMethodInstance();
  13655. }
  13656. auto propTypeInst = mPropTarget.mType->ToTypeInstance();
  13657. if (propTypeInst == NULL)
  13658. {
  13659. propTypeInst = mModule->GetWrappedStructType(mPropTarget.mType);
  13660. }
  13661. if (propTypeInst == NULL)
  13662. {
  13663. mModule->Fail("INTERNAL ERROR: Invalid property target", mPropSrc);
  13664. return BfModuleMethodInstance();
  13665. }
  13666. return mModule->GetMethodInstance(propTypeInst, methodDef, BfTypeVector(), mPropGetMethodFlags);
  13667. }
  13668. void BfExprEvaluator::CheckPropFail(BfMethodDef* propMethodDef, BfMethodInstance* methodInstance, bool checkProt)
  13669. {
  13670. auto propTypeInst = mPropTarget.mType->ToTypeInstance();
  13671. // If mExplicitInterface is null then we are implicitly calling through an interface
  13672. if ((checkProt) && (propTypeInst != NULL) && (methodInstance->GetExplicitInterface() == NULL) &&
  13673. (!mModule->CheckAccessMemberProtection(propMethodDef->mProtection, propTypeInst)))
  13674. mModule->Fail(StrFormat("'%s' is inaccessible due to its protection level", mModule->MethodToString(methodInstance).c_str()), mPropSrc);
  13675. else if (mPropCheckedKind != methodInstance->mMethodDef->mCheckedKind)
  13676. {
  13677. bool passes = true;
  13678. if (mPropCheckedKind != BfCheckedKind_NotSet)
  13679. {
  13680. passes = false;
  13681. }
  13682. else
  13683. {
  13684. auto defaultCheckedKind = mModule->GetDefaultCheckedKind();
  13685. if (defaultCheckedKind != methodInstance->mMethodDef->mCheckedKind)
  13686. passes = false;
  13687. }
  13688. if (!passes)
  13689. {
  13690. 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);
  13691. if (error != NULL)
  13692. {
  13693. if ((error != NULL) && (methodInstance->mMethodDef->mMethodDeclaration != NULL))
  13694. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("See method declaration"), methodInstance->mMethodDef->GetRefNode());
  13695. }
  13696. }
  13697. }
  13698. }
  13699. bool BfExprEvaluator::HasResult()
  13700. {
  13701. return (mResult) || (mPropDef != NULL);
  13702. }
  13703. BfTypedValue BfExprEvaluator::GetResult(bool clearResult, bool resolveGenericType)
  13704. {
  13705. if ((!mResult) && (mPropDef != NULL))
  13706. {
  13707. bool handled = false;
  13708. if (mPropTarget.mType->IsGenericTypeInstance())
  13709. {
  13710. auto genericTypeInst = (BfTypeInstance*)mPropTarget.mType;
  13711. if (genericTypeInst->mTypeDef == mModule->mCompiler->mSizedArrayTypeDef)
  13712. {
  13713. if (mPropDef->mName == "Count")
  13714. {
  13715. auto sizedType = genericTypeInst->mGenericTypeInfo->mTypeGenericArguments[1];
  13716. if (sizedType->IsConstExprValue())
  13717. {
  13718. auto constExprType = (BfConstExprValueType*)sizedType;
  13719. mResult = BfTypedValue(mModule->GetConstValue(constExprType->mValue.mInt64), mModule->GetPrimitiveType(BfTypeCode_IntPtr));
  13720. handled = true;
  13721. }
  13722. else
  13723. {
  13724. BF_ASSERT(mModule->mCurMethodInstance->mIsUnspecialized);
  13725. mResult = BfTypedValue(mModule->mBfIRBuilder->GetUndefConstValue(BfTypeCode_IntPtr), mModule->GetPrimitiveType(BfTypeCode_IntPtr));
  13726. handled = true;
  13727. }
  13728. }
  13729. }
  13730. }
  13731. if (!handled)
  13732. {
  13733. SetAndRestoreValue<BfFunctionBindResult*> prevFunctionBindResult(mFunctionBindResult, NULL);
  13734. SetAndRestoreValue<BfAstNode*> prevDeferCallRef(mDeferCallRef, NULL);
  13735. BfMethodDef* matchedMethod = GetPropertyMethodDef(mPropDef, BfMethodType_PropertyGetter, mPropCheckedKind, mPropTarget);
  13736. if (matchedMethod == NULL)
  13737. {
  13738. mModule->Fail("Property has no getter", mPropSrc);
  13739. return mResult;
  13740. }
  13741. auto methodInstance = GetPropertyMethodInstance(matchedMethod);
  13742. if (methodInstance.mMethodInstance == NULL)
  13743. return mResult;
  13744. BF_ASSERT(methodInstance.mMethodInstance->mMethodDef->mName == matchedMethod->mName);
  13745. if (!mModule->mBfIRBuilder->mIgnoreWrites)
  13746. {
  13747. BF_ASSERT(!methodInstance.mFunc.IsFake());
  13748. }
  13749. if (mPropSrc != NULL)
  13750. mModule->UpdateExprSrcPos(mPropSrc);
  13751. auto autoComplete = GetAutoComplete();
  13752. if ((autoComplete != NULL) && (autoComplete->IsAutocompleteNode(mPropSrc)) && (autoComplete->mResolveType == BfResolveType_GetResultString))
  13753. {
  13754. autoComplete->mResultString = ":";
  13755. autoComplete->mResultString += mModule->TypeToString(methodInstance.mMethodInstance->mReturnType);
  13756. autoComplete->mResultString += " ";
  13757. autoComplete->mResultString += mModule->TypeToString(methodInstance.mMethodInstance->GetOwner());
  13758. autoComplete->mResultString += ".";
  13759. autoComplete->mResultString += mPropDef->mName;
  13760. }
  13761. CheckPropFail(matchedMethod, methodInstance.mMethodInstance, (mPropGetMethodFlags & BfGetMethodInstanceFlag_Friend) == 0);
  13762. PerformCallChecks(methodInstance.mMethodInstance, mPropSrc);
  13763. if (methodInstance.mMethodInstance->IsSkipCall())
  13764. {
  13765. mResult = mModule->GetDefaultTypedValue(methodInstance.mMethodInstance->mReturnType);
  13766. }
  13767. else
  13768. {
  13769. SizedArray<BfIRValue, 4> args;
  13770. if (!matchedMethod->mIsStatic)
  13771. {
  13772. auto owner = methodInstance.mMethodInstance->GetOwner();
  13773. if ((mPropTarget.mValue.IsFake()) && (!mOrigPropTarget.mValue.IsFake()))
  13774. {
  13775. mPropTarget = mModule->Cast(mPropSrc, mOrigPropTarget, owner);
  13776. }
  13777. if ((mPropGetMethodFlags & BfGetMethodInstanceFlag_DisableObjectAccessChecks) == 0)
  13778. mModule->EmitObjectAccessCheck(mPropTarget);
  13779. PushThis(mPropSrc, mPropTarget, methodInstance.mMethodInstance, args);
  13780. }
  13781. bool failed = false;
  13782. for (int paramIdx = 0; paramIdx < (int)mIndexerValues.size(); paramIdx++)
  13783. {
  13784. auto refNode = mIndexerValues[paramIdx].mExpression;
  13785. auto wantType = methodInstance.mMethodInstance->GetParamType(paramIdx);
  13786. auto argValue = ResolveArgValue(mIndexerValues[paramIdx], wantType);
  13787. if (refNode == NULL)
  13788. refNode = mPropSrc;
  13789. BfTypedValue val;
  13790. if (argValue)
  13791. val = mModule->Cast(refNode, argValue, wantType);
  13792. if (!val)
  13793. failed = true;
  13794. else
  13795. PushArg(val, args);
  13796. }
  13797. if (mPropDefBypassVirtual)
  13798. {
  13799. auto methodDef = methodInstance.mMethodInstance->mMethodDef;
  13800. if ((methodDef->mIsAbstract) && (mPropDefBypassVirtual))
  13801. {
  13802. mModule->Fail(StrFormat("Abstract base property method '%s' cannot be invoked", mModule->MethodToString(methodInstance.mMethodInstance).c_str()), mPropSrc);
  13803. }
  13804. }
  13805. if (failed)
  13806. {
  13807. auto returnType = methodInstance.mMethodInstance->mReturnType;
  13808. auto methodDef = methodInstance.mMethodInstance->mMethodDef;
  13809. if (returnType->IsRef())
  13810. {
  13811. auto result = mModule->GetDefaultTypedValue(returnType->GetUnderlyingType(), true, BfDefaultValueKind_Addr);
  13812. if (methodDef->mIsReadOnly)
  13813. result.mKind = BfTypedValueKind_ReadOnlyAddr;
  13814. return result;
  13815. }
  13816. else
  13817. {
  13818. auto val = mModule->GetDefaultTypedValue(returnType, true, (methodInstance.mMethodInstance->GetStructRetIdx() != -1) ? BfDefaultValueKind_Addr : BfDefaultValueKind_Value);
  13819. if (val.mKind == BfTypedValueKind_Addr)
  13820. val.mKind = BfTypedValueKind_TempAddr;
  13821. return val;
  13822. }
  13823. }
  13824. else
  13825. mResult = CreateCall(mPropSrc, methodInstance.mMethodInstance, methodInstance.mFunc, mPropDefBypassVirtual, args);
  13826. if (mResult.mType != NULL)
  13827. {
  13828. if ((mResult.mType->IsVar()) && (mModule->mCompiler->mIsResolveOnly))
  13829. mModule->Fail("Property type reference failed to resolve", mPropSrc);
  13830. BF_ASSERT(!mResult.mType->IsRef());
  13831. }
  13832. }
  13833. }
  13834. mPropDef = NULL;
  13835. mPropDefBypassVirtual = false;
  13836. mIndexerValues.clear();
  13837. mResultLocalVar = NULL;
  13838. mResultFieldInstance = NULL;
  13839. }
  13840. if (resolveGenericType)
  13841. ResolveGenericType();
  13842. BfTypedValue result = mResult;
  13843. if (clearResult)
  13844. mResult = BfTypedValue();
  13845. return result;
  13846. }
  13847. void BfExprEvaluator::CheckResultForReading(BfTypedValue& typedValue)
  13848. {
  13849. if (mModule->mCurMethodState == NULL)
  13850. return;
  13851. if ((mModule->mCurMethodState->mTempKind != BfMethodState::TempKind_None) || (mModule->mCurMethodState->mAllowUinitReads))
  13852. return;
  13853. if ((mModule->mCurTypeInstance->mResolvingVarField) || (mModule->mCurTypeInstance->mResolvingConstField))
  13854. return;
  13855. if ((typedValue) && (typedValue.IsAddr()))
  13856. {
  13857. if ((mResultLocalVar != NULL) && (mResultLocalVarRefNode != NULL))
  13858. {
  13859. SetAndRestoreValue<bool> prevIgnoreError(mModule->mIgnoreErrors);
  13860. if ((mModule->mCurMethodState->mClosureState != NULL) && (mModule->mCurMethodState->mClosureState->mCapturing))
  13861. {
  13862. // These errors can only be detected during capture time, so we don't ignore them on this pass
  13863. mModule->mIgnoreErrors = false;
  13864. }
  13865. int fieldIdx = mResultLocalVarField - 1;
  13866. auto localVar = mResultLocalVar;
  13867. if (localVar->mCompositeCount > 0)
  13868. {
  13869. mModule->Fail(StrFormat("Cannot read from composite '%s', it can only be used in an argument list", localVar->mName.c_str()), mResultLocalVarRefNode);
  13870. typedValue = BfTypedValue();
  13871. return;
  13872. }
  13873. if (localVar->mAssignedKind == BfLocalVarAssignKind_None)
  13874. {
  13875. mModule->TryLocalVariableInit(localVar);
  13876. }
  13877. if (localVar->mAssignedKind == BfLocalVarAssignKind_None)
  13878. {
  13879. auto methodStateForLocal = mModule->mCurMethodState->GetMethodStateForLocal(localVar);
  13880. bool isAssigned = false;
  13881. int64 undefinedFieldFlags = localVar->mUnassignedFieldFlags;
  13882. auto deferredLocalAssignData = methodStateForLocal->mDeferredLocalAssignData;
  13883. while ((deferredLocalAssignData != NULL) && (deferredLocalAssignData->mIsChained))
  13884. deferredLocalAssignData = deferredLocalAssignData->mChainedAssignData;
  13885. if (deferredLocalAssignData != NULL)
  13886. {
  13887. for (auto& assignedVar : deferredLocalAssignData->mAssignedLocals)
  13888. {
  13889. auto assignedLocal = assignedVar.mLocalVar;
  13890. if (assignedLocal == localVar)
  13891. {
  13892. int assignedFieldIdx = assignedVar.mLocalVarField;
  13893. if (assignedFieldIdx >= 0)
  13894. undefinedFieldFlags &= ~((int64)1 << assignedFieldIdx);
  13895. else
  13896. undefinedFieldFlags = 0;
  13897. }
  13898. }
  13899. }
  13900. if (fieldIdx == -1)
  13901. {
  13902. if (undefinedFieldFlags == 0)
  13903. isAssigned = true;
  13904. }
  13905. else
  13906. {
  13907. isAssigned = true;
  13908. for (int i = 0; i < mResultLocalVarFieldCount; i++)
  13909. if ((undefinedFieldFlags & (1LL << (fieldIdx + i))) != 0)
  13910. isAssigned = false;
  13911. }
  13912. if (!isAssigned)
  13913. {
  13914. if ((localVar->mIsThis) && (fieldIdx != -1))
  13915. {
  13916. // When we have initializers for fields, they won't all be processed in the autocomplte case
  13917. if (!mModule->mCompiler->IsAutocomplete())
  13918. {
  13919. auto bfError = mModule->Fail(StrFormat("Use of possibly unassigned field '%s'", mResultLocalVarRefNode->ToString().c_str()), mResultLocalVarRefNode, true);
  13920. }
  13921. }
  13922. else
  13923. {
  13924. mModule->Fail(StrFormat("Use of unassigned local variable '%s'", localVar->mName.c_str()), mResultLocalVarRefNode);
  13925. }
  13926. }
  13927. }
  13928. localVar->mReadFromId = mModule->mCurMethodState->GetRootMethodState()->mCurAccessId++;
  13929. }
  13930. }
  13931. }
  13932. void BfExprEvaluator::FinishExpressionResult()
  13933. {
  13934. CheckResultForReading(mResult);
  13935. mResultLocalVar = NULL;
  13936. mResultFieldInstance = NULL;
  13937. }
  13938. bool BfExprEvaluator::CheckAllowValue(const BfTypedValue& typedValue, BfAstNode* refNode)
  13939. {
  13940. return true;
  13941. }
  13942. void BfExprEvaluator::MarkResultUsed()
  13943. {
  13944. if (mResultLocalVar != NULL)
  13945. {
  13946. mResultLocalVar->mReadFromId = mModule->mCurMethodState->GetRootMethodState()->mCurAccessId++;
  13947. }
  13948. }
  13949. void BfExprEvaluator::MarkResultAssigned()
  13950. {
  13951. if (mResultLocalVar != NULL)
  13952. {
  13953. //int localIdx = mResultLocalVarIdx;
  13954. //if (localIdx == 0x7FFF)
  13955. //return;
  13956. auto localVar = mResultLocalVar;
  13957. int fieldIdx = mResultLocalVarField - 1;
  13958. int count = mResultLocalVarFieldCount;
  13959. if (fieldIdx == -1)
  13960. count = 1;
  13961. for (int i = 0; i < count; i++)
  13962. mModule->mCurMethodState->GetMethodStateForLocal(localVar)->LocalDefined(localVar, fieldIdx + i);
  13963. //if (localIdx != 0x7FFF)
  13964. {
  13965. if (localVar->mCompositeCount > 0)
  13966. {
  13967. mModule->Fail(StrFormat("Cannot write to composite '%s', it can only be used in an argument list", localVar->mName.c_str()), mResultLocalVarRefNode);
  13968. }
  13969. }
  13970. }
  13971. }
  13972. void BfExprEvaluator::MakeResultAsValue()
  13973. {
  13974. // Expressions like parens will turn a variable reference into a simple value
  13975. mResultLocalVar = NULL;
  13976. mResultFieldInstance = NULL;
  13977. }
  13978. bool BfExprEvaluator::CheckIsBase(BfAstNode* checkNode)
  13979. {
  13980. if (checkNode == NULL)
  13981. return false;
  13982. if (!checkNode->Equals("base"))
  13983. return false;
  13984. auto autoComplete = GetAutoComplete();
  13985. if ((autoComplete != NULL) && (autoComplete->IsAutocompleteNode(checkNode)))
  13986. {
  13987. if ((mModule->mCurTypeInstance != NULL) && (mModule->mCurTypeInstance->mBaseType != NULL))
  13988. autoComplete->SetDefinitionLocation(mModule->mCurTypeInstance->mBaseType->mTypeDef->GetRefNode());
  13989. }
  13990. return true;
  13991. }
  13992. bool BfExprEvaluator::CheckModifyResult(BfTypedValue typedVal, BfAstNode* refNode, const char* modifyType, bool onlyNeedsMut, bool emitWarning)
  13993. {
  13994. BfLocalVariable* localVar = NULL;
  13995. bool isCapturedLocal = false;
  13996. if (mResultLocalVar != NULL)
  13997. {
  13998. localVar = mResultLocalVar;
  13999. localVar->mWrittenToId = mModule->mCurMethodState->GetRootMethodState()->mCurAccessId++;
  14000. }
  14001. else if (typedVal.IsThis())
  14002. {
  14003. localVar = mModule->GetThisVariable();
  14004. }
  14005. else if (typedVal.IsSplat())
  14006. {
  14007. for (auto checkLocal : mModule->mCurMethodState->mLocals)
  14008. {
  14009. if (checkLocal->mAddr == typedVal.mValue)
  14010. {
  14011. localVar = checkLocal;
  14012. break;
  14013. }
  14014. }
  14015. }
  14016. else if (typedVal.mValue.IsArg())
  14017. {
  14018. auto methodState = mModule->mCurMethodState->GetNonCaptureState();
  14019. localVar = methodState->mLocals[typedVal.mValue.mId];
  14020. }
  14021. if ((typedVal.mKind == BfTypedValueKind_MutableValue) && (onlyNeedsMut))
  14022. {
  14023. return true;
  14024. }
  14025. bool canModify = typedVal.CanModify();
  14026. auto _Fail = [&](const StringImpl& error, BfAstNode* refNode)
  14027. {
  14028. if (emitWarning)
  14029. return mModule->Warn(BfWarning_BF4204_AddressOfReadOnly, error, refNode);
  14030. else
  14031. return mModule->Fail(error, refNode);
  14032. };
  14033. if (localVar != NULL)
  14034. {
  14035. if (!canModify)
  14036. {
  14037. BfError* error = NULL;
  14038. if (localVar->mIsThis)
  14039. {
  14040. bool isClosure = false;
  14041. BfTypeInstance* checkTypeInst = localVar->mResolvedType->ToTypeInstance();
  14042. int fieldIdx = mResultLocalVarField - 1;
  14043. if ((!isCapturedLocal) && (mModule->mCurMethodState != NULL) && (mModule->mCurMethodState->mClosureState != NULL) && (mModule->mCurMethodState->mClosureState->mClosureType != NULL))
  14044. {
  14045. isClosure = true;
  14046. auto closureThis = mModule->mCurMethodState->mClosureState->mClosureType;
  14047. closureThis = checkTypeInst->mFieldInstances[0].mResolvedType->ToTypeInstance();
  14048. if (fieldIdx >= -1)
  14049. {
  14050. checkTypeInst = closureThis;
  14051. }
  14052. else
  14053. {
  14054. fieldIdx = -fieldIdx - 2;
  14055. isCapturedLocal = true;
  14056. }
  14057. }
  14058. if (fieldIdx < 0)
  14059. {
  14060. if (isClosure)
  14061. {
  14062. if (!mModule->mCurMethodState->mClosureState->mDeclaringMethodIsMutating)
  14063. error = _Fail(StrFormat("Cannot %s 'this' within struct lambda. Consider adding 'mut' specifier to this method.", modifyType), refNode);
  14064. else
  14065. error = _Fail(StrFormat("Cannot %s 'this' within struct lambda. Consider adding by-reference capture specifier [&] to lambda.", modifyType), refNode);
  14066. }
  14067. else if (localVar->mResolvedType->IsValueType())
  14068. {
  14069. error = _Fail(StrFormat("Cannot %s 'this' within struct method '%s'. Consider adding 'mut' specifier to this method.", modifyType,
  14070. mModule->MethodToString(mModule->mCurMethodInstance).c_str()), refNode);
  14071. }
  14072. else
  14073. {
  14074. error = _Fail(StrFormat("Cannot %s 'this' because '%s' is a reference type.", modifyType,
  14075. mModule->TypeToString(localVar->mResolvedType).c_str()), refNode);
  14076. }
  14077. return false;
  14078. }
  14079. else if (mResultFieldInstance != NULL)
  14080. {
  14081. if (isCapturedLocal)
  14082. {
  14083. 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,
  14084. mResultFieldInstance->GetFieldDef()->mName.c_str()), refNode);
  14085. }
  14086. else if (isClosure)
  14087. {
  14088. if (!mModule->mCurMethodState->mClosureState->mDeclaringMethodIsMutating)
  14089. error = _Fail(StrFormat("Cannot %s field '%s.%s' within struct lambda. Consider adding 'mut' specifier to this method.", modifyType,
  14090. mModule->TypeToString(mResultFieldInstance->mOwner).c_str(), mResultFieldInstance->GetFieldDef()->mName.c_str()), refNode);
  14091. else
  14092. error = _Fail(StrFormat("Cannot %s field '%s.%s' within struct lambda. Consider adding by-reference capture specifier [&] to lambda.", modifyType,
  14093. mModule->TypeToString(mResultFieldInstance->mOwner).c_str(), mResultFieldInstance->GetFieldDef()->mName.c_str()), refNode);
  14094. }
  14095. else if (mResultFieldInstance->GetFieldDef()->mIsReadOnly)
  14096. {
  14097. error = _Fail(StrFormat("Cannot %s readonly field '%s.%s' within method '%s'", modifyType,
  14098. mModule->TypeToString(mResultFieldInstance->mOwner).c_str(), mResultFieldInstance->GetFieldDef()->mName.c_str(),
  14099. mModule->MethodToString(mModule->mCurMethodInstance).c_str()), refNode);
  14100. }
  14101. else if (auto propertyDeclaration = BfNodeDynCast<BfPropertyDeclaration>(mResultFieldInstance->GetFieldDef()->mFieldDeclaration))
  14102. {
  14103. String propNam;
  14104. if (propertyDeclaration->mNameNode != NULL)
  14105. propertyDeclaration->mNameNode->ToString(propNam);
  14106. error = _Fail(StrFormat("Cannot %s auto-implemented property '%s.%s' without set accessor", modifyType,
  14107. mModule->TypeToString(mResultFieldInstance->mOwner).c_str(), propNam.c_str()), refNode);
  14108. }
  14109. else
  14110. {
  14111. error = _Fail(StrFormat("Cannot %s field '%s.%s' within struct method '%s'. Consider adding 'mut' specifier to this method.", modifyType,
  14112. mModule->TypeToString(mResultFieldInstance->mOwner).c_str(), mResultFieldInstance->GetFieldDef()->mName.c_str(),
  14113. mModule->MethodToString(mModule->mCurMethodInstance).c_str()), refNode);
  14114. }
  14115. return false;
  14116. }
  14117. }
  14118. else if (localVar->IsParam())
  14119. {
  14120. if (!mModule->mCurMethodInstance->IsMixin())
  14121. {
  14122. if (mModule->mCurMethodState->mMixinState != NULL)
  14123. error = _Fail(StrFormat("Cannot %s mixin parameter '%s'", modifyType,
  14124. localVar->mName.c_str(), mModule->MethodToString(mModule->mCurMethodInstance).c_str()), refNode);
  14125. else if ((localVar->mResolvedType->IsGenericParam()) && (onlyNeedsMut))
  14126. error = _Fail(StrFormat("Cannot %s parameter '%s'. Consider adding 'mut' or 'ref' specifier to parameter or copying to a local variable.", modifyType,
  14127. localVar->mName.c_str(), mModule->MethodToString(mModule->mCurMethodInstance).c_str()), refNode);
  14128. else
  14129. error = _Fail(StrFormat("Cannot %s parameter '%s'. Consider adding 'ref' specifier to parameter or copying to a local variable.", modifyType,
  14130. localVar->mName.c_str(), mModule->MethodToString(mModule->mCurMethodInstance).c_str()), refNode);
  14131. return false;
  14132. }
  14133. }
  14134. else
  14135. {
  14136. if ((mResultLocalVarField != 0) && (!localVar->mIsReadOnly))
  14137. {
  14138. auto typeInst = localVar->mResolvedType->ToTypeInstance();
  14139. int dataIdx = mResultLocalVarField - 1;
  14140. if (typeInst != NULL)
  14141. {
  14142. for (auto& field : typeInst->mFieldInstances)
  14143. {
  14144. if (field.mDataIdx == dataIdx)
  14145. {
  14146. error = _Fail(StrFormat("Cannot %s readonly field '%s.%s'.", modifyType,
  14147. mModule->TypeToString(typeInst).c_str(),
  14148. field.GetFieldDef()->mName.c_str()), refNode);
  14149. break;
  14150. }
  14151. }
  14152. }
  14153. }
  14154. if (error == NULL)
  14155. {
  14156. error = _Fail(StrFormat("Cannot %s read-only local variable '%s'.", modifyType,
  14157. localVar->mName.c_str()), refNode);
  14158. }
  14159. return false;
  14160. }
  14161. }
  14162. else
  14163. {
  14164. // When we are capturing, we need to note that we require capturing by reference here
  14165. localVar->mWrittenToId = mModule->mCurMethodState->GetRootMethodState()->mCurAccessId++;
  14166. }
  14167. }
  14168. if ((mResultFieldInstance != NULL) && (mResultFieldInstance->GetFieldDef()->mIsReadOnly) && (!canModify))
  14169. {
  14170. auto error = _Fail(StrFormat("Cannot %s static readonly field '%s.%s' within method '%s'", modifyType,
  14171. mModule->TypeToString(mResultFieldInstance->mOwner).c_str(), mResultFieldInstance->GetFieldDef()->mName.c_str(),
  14172. mModule->MethodToString(mModule->mCurMethodInstance).c_str()), refNode);
  14173. return false;
  14174. }
  14175. return mModule->CheckModifyValue(typedVal, refNode, modifyType);
  14176. }
  14177. void BfExprEvaluator::Visit(BfConditionalExpression* condExpr)
  14178. {
  14179. static int sCallCount = 0;
  14180. sCallCount++;
  14181. auto condResult = mModule->CreateValueFromExpression(condExpr->mConditionExpression, mModule->GetPrimitiveType(BfTypeCode_Boolean));
  14182. if (!condResult)
  14183. return;
  14184. if (condExpr->mTrueExpression == NULL)
  14185. {
  14186. mModule->AssertErrorState();
  14187. return;
  14188. }
  14189. if (condExpr->mFalseExpression == NULL)
  14190. {
  14191. mModule->CreateValueFromExpression(condExpr->mTrueExpression, mExpectingType, BfEvalExprFlags_NoCast);
  14192. mModule->AssertErrorState();
  14193. return;
  14194. }
  14195. bool isConstBranch = false;
  14196. bool constResult = false;
  14197. bool constResultUndef = false;
  14198. if (condResult.mValue.IsConst())
  14199. {
  14200. auto constValue = mModule->mBfIRBuilder->GetConstant(condResult.mValue);
  14201. if (constValue->mTypeCode == BfTypeCode_Boolean)
  14202. {
  14203. isConstBranch = true;
  14204. constResult = constValue->mBool;
  14205. }
  14206. else if (constValue->mConstType == BfConstType_Undef)
  14207. {
  14208. isConstBranch = true;
  14209. constResultUndef = true;
  14210. }
  14211. }
  14212. if (isConstBranch)
  14213. {
  14214. BfExpression* actualExpr = (constResult) ? condExpr->mTrueExpression : condExpr->mFalseExpression;
  14215. BfExpression* ignoredExpr = (constResult) ? condExpr->mFalseExpression : condExpr->mTrueExpression;
  14216. BfTypedValue actualValue = mModule->CreateValueFromExpression(actualExpr, mExpectingType, BfEvalExprFlags_NoCast);
  14217. BfTypedValue ignoredValue;
  14218. //
  14219. {
  14220. auto curBlock = mModule->mBfIRBuilder->GetInsertBlock();
  14221. SetAndRestoreValue<bool> ignoreWrites(mModule->mBfIRBuilder->mIgnoreWrites, true);
  14222. ignoredValue = mModule->CreateValueFromExpression(ignoredExpr, mExpectingType, BfEvalExprFlags_NoCast);
  14223. mModule->mBfIRBuilder->SetInsertPoint(curBlock);
  14224. }
  14225. if (!actualValue)
  14226. return;
  14227. if ((ignoredValue) && (ignoredValue.mType != actualValue.mType))
  14228. {
  14229. // Cast to more specific 'ignored' type if applicable
  14230. if (mModule->CanCast(actualValue, ignoredValue.mType))
  14231. {
  14232. actualValue = mModule->Cast(actualExpr, actualValue, ignoredValue.mType);
  14233. }
  14234. else if (!mModule->CanCast(ignoredValue, actualValue.mType))
  14235. {
  14236. mModule->Fail(StrFormat("Type of conditional expression cannot be determined because there is no implicit conversion between '%s' and '%s'",
  14237. mModule->TypeToString(actualValue.mType).c_str(), mModule->TypeToString(ignoredValue.mType).c_str()), condExpr);
  14238. }
  14239. }
  14240. mResult = actualValue;
  14241. if (constResultUndef)
  14242. mResult = mModule->GetDefaultTypedValue(mResult.mType, false, BfDefaultValueKind_Undef);
  14243. return;
  14244. }
  14245. auto trueBB = mModule->mBfIRBuilder->CreateBlock("cond.then");
  14246. auto falseBB = mModule->mBfIRBuilder->CreateBlock("cond.else");
  14247. auto endBB = mModule->mBfIRBuilder->CreateBlock("cond.end");
  14248. auto contBB = mModule->mBfIRBuilder->CreateBlock("cond.cont");
  14249. mModule->mBfIRBuilder->CreateCondBr(condResult.mValue, trueBB, falseBB);
  14250. SetAndRestoreValue<bool> prevInCondBlock(mModule->mCurMethodState->mCurScope->mInnerIsConditional, true);
  14251. mModule->AddBasicBlock(trueBB);
  14252. auto trueValue = mModule->CreateValueFromExpression(condExpr->mTrueExpression, mExpectingType, (BfEvalExprFlags)(BfEvalExprFlags_NoCast | BfEvalExprFlags_CreateConditionalScope));
  14253. if ((mExpectingType != NULL) && (trueValue) && (trueValue.mType != mExpectingType))
  14254. {
  14255. // In some cases like typed primitives - we CAN individually cast each value which it's a constant still, but not after the merging
  14256. // IE: Color c = isOver ? 0xFF000000 : 0xFFFFFFFF;
  14257. // Otherwise the resulting value would just be 'int' which cannot implicitly convert to Color, but each of those ints can be
  14258. // a uint32 if converted separately
  14259. auto checkTrueValue = mModule->Cast(condExpr->mTrueExpression, trueValue, mExpectingType, BfCastFlags_SilentFail);
  14260. if (checkTrueValue)
  14261. trueValue = checkTrueValue;
  14262. mModule->FixIntUnknown(trueValue);
  14263. }
  14264. auto trueBlockPos = mModule->mBfIRBuilder->GetInsertBlock();
  14265. mModule->AddBasicBlock(falseBB);
  14266. auto falseValue = mModule->CreateValueFromExpression(condExpr->mFalseExpression, mExpectingType, (BfEvalExprFlags)(BfEvalExprFlags_NoCast | BfEvalExprFlags_CreateConditionalScope));
  14267. auto falseBlockPos = mModule->mBfIRBuilder->GetInsertBlock();
  14268. if ((mExpectingType != NULL) && (falseValue) && (falseValue.mType != mExpectingType))
  14269. {
  14270. auto checkFalseValue = mModule->Cast(condExpr->mFalseExpression, falseValue, mExpectingType, BfCastFlags_SilentFail);
  14271. if (checkFalseValue)
  14272. falseValue = checkFalseValue;
  14273. mModule->FixIntUnknown(falseValue);
  14274. }
  14275. prevInCondBlock.Restore();
  14276. bool isValid = trueValue && falseValue;
  14277. if (isValid)
  14278. {
  14279. BfTypedValue falseToTrue;
  14280. {
  14281. SetAndRestoreValue<bool> prevIgnoreError(mModule->mIgnoreErrors, true);
  14282. mModule->mBfIRBuilder->SetInsertPoint(falseBlockPos);
  14283. falseToTrue = mModule->Cast(condExpr->mFalseExpression, falseValue, trueValue.mType);
  14284. }
  14285. if (falseToTrue)
  14286. {
  14287. falseValue = falseToTrue;
  14288. }
  14289. else
  14290. {
  14291. BfTypedValue trueToFalse;
  14292. {
  14293. SetAndRestoreValue<bool> prevIgnoreError(mModule->mIgnoreErrors, true);
  14294. mModule->mBfIRBuilder->SetInsertPoint(trueBlockPos);
  14295. trueToFalse = mModule->Cast(condExpr->mTrueExpression, trueValue, falseValue.mType);
  14296. }
  14297. if (!trueToFalse)
  14298. {
  14299. mModule->Fail(StrFormat("Type of conditional expression cannot be determined because there is no implicit conversion between '%s' and '%s'",
  14300. mModule->TypeToString(trueValue.mType).c_str(), mModule->TypeToString(falseValue.mType).c_str()), condExpr);
  14301. //return;
  14302. isValid = false;
  14303. }
  14304. else
  14305. trueValue = trueToFalse;
  14306. }
  14307. }
  14308. mModule->mBfIRBuilder->SetInsertPoint(trueBlockPos);
  14309. if (isValid)
  14310. trueValue = mModule->LoadValue(trueValue);
  14311. mModule->mBfIRBuilder->CreateBr(endBB);
  14312. mModule->mBfIRBuilder->SetInsertPoint(falseBlockPos);
  14313. if (isValid)
  14314. falseValue = mModule->LoadValue(falseValue);
  14315. mModule->mBfIRBuilder->CreateBr(endBB);
  14316. mModule->AddBasicBlock(endBB, false);
  14317. if (!isValid)
  14318. return;
  14319. mModule->mBfIRBuilder->SetInsertPoint(endBB);
  14320. BfIRValue phi;
  14321. if (!trueValue.mType->IsValuelessType())
  14322. {
  14323. if (trueValue.mType->IsVar())
  14324. {
  14325. phi = mModule->mBfIRBuilder->GetFakeVal();
  14326. }
  14327. else
  14328. {
  14329. phi = mModule->mBfIRBuilder->CreatePhi(mModule->mBfIRBuilder->MapType(trueValue.mType), 2);
  14330. mModule->mBfIRBuilder->AddPhiIncoming(phi, trueValue.mValue, trueBlockPos);
  14331. mModule->mBfIRBuilder->AddPhiIncoming(phi, falseValue.mValue, falseBlockPos);
  14332. }
  14333. }
  14334. mModule->mBfIRBuilder->CreateBr(contBB);
  14335. mModule->AddBasicBlock(contBB);
  14336. mResult = BfTypedValue(phi, trueValue.mType);
  14337. }
  14338. void BfExprEvaluator::PopulateDeferrredTupleAssignData(BfTupleExpression* tupleExpr, DeferredTupleAssignData& deferredTupleAssignData)
  14339. {
  14340. BfTypeVector fieldTypes;
  14341. Array<String> fieldNames;
  14342. // We need to evaluate each LHS tuple component in a separate BfExprEvaluator because each one
  14343. // could be a property and the 'mPropDef' target info is tied to a single evaluator
  14344. for (int valueIdx = 0; valueIdx < (int)tupleExpr->mValues.size(); valueIdx++)
  14345. {
  14346. DeferredTupleAssignData::Entry entry;
  14347. entry.mExprEvaluator = NULL;
  14348. entry.mInnerTuple = NULL;
  14349. BfExpression* valueExpr = tupleExpr->mValues[valueIdx];
  14350. entry.mExpr = valueExpr;
  14351. BfType* fieldType = NULL;
  14352. BfType* resultType = NULL;
  14353. if (auto innerTupleExpr = BfNodeDynCast<BfTupleExpression>(valueExpr))
  14354. {
  14355. entry.mInnerTuple = new DeferredTupleAssignData();
  14356. PopulateDeferrredTupleAssignData(innerTupleExpr, *entry.mInnerTuple);
  14357. resultType = entry.mInnerTuple->mTupleType;
  14358. }
  14359. else
  14360. {
  14361. BfExprEvaluator* exprEvaluator = new BfExprEvaluator(mModule);
  14362. entry.mExprEvaluator = exprEvaluator;
  14363. if (valueExpr->IsA<BfUninitializedExpression>())
  14364. {
  14365. resultType = mModule->GetPrimitiveType(BfTypeCode_None);
  14366. }
  14367. if (auto varDecl = BfNodeDynCast<BfVariableDeclaration>(valueExpr))
  14368. {
  14369. if ((varDecl->mTypeRef->IsA<BfLetTypeReference>()) || (varDecl->mTypeRef->IsA<BfVarTypeReference>()))
  14370. {
  14371. resultType = mModule->GetPrimitiveType(BfTypeCode_Var);
  14372. }
  14373. else
  14374. {
  14375. resultType = ResolveTypeRef(varDecl->mTypeRef);
  14376. if (resultType == NULL)
  14377. resultType = mModule->GetPrimitiveType(BfTypeCode_Var);
  14378. }
  14379. }
  14380. if (resultType == NULL)
  14381. {
  14382. exprEvaluator->VisitChild(valueExpr);
  14383. if ((!exprEvaluator->mResult) && (exprEvaluator->mPropDef == NULL))
  14384. exprEvaluator->mResult = mModule->GetDefaultTypedValue(mModule->GetPrimitiveType(BfTypeCode_None));
  14385. resultType = exprEvaluator->mResult.mType;
  14386. }
  14387. if ((resultType == NULL) && (exprEvaluator->mPropDef != NULL) && (exprEvaluator->mPropTarget.mType != NULL))
  14388. {
  14389. auto propTypeInst = exprEvaluator->mPropTarget.mType->ToTypeInstance();
  14390. if ((propTypeInst == NULL) && (exprEvaluator->mPropTarget.mType->IsPointer()))
  14391. {
  14392. BfPointerType* pointerType = (BfPointerType*)exprEvaluator->mPropTarget.mType;
  14393. propTypeInst = pointerType->mElementType->ToTypeInstance();
  14394. }
  14395. auto setMethod = GetPropertyMethodDef(exprEvaluator->mPropDef, BfMethodType_PropertySetter, mPropCheckedKind, mPropTarget);
  14396. if (setMethod != NULL)
  14397. {
  14398. auto methodInstance = mModule->GetMethodInstance(propTypeInst, setMethod, BfTypeVector());
  14399. resultType = methodInstance.mMethodInstance->GetParamType(0);
  14400. }
  14401. else
  14402. {
  14403. auto getMethod = GetPropertyMethodDef(exprEvaluator->mPropDef, BfMethodType_PropertyGetter, mPropCheckedKind, mPropTarget);
  14404. if (getMethod != NULL)
  14405. {
  14406. auto methodInstance = mModule->GetMethodInstance(propTypeInst, getMethod, BfTypeVector());
  14407. auto retType = methodInstance.mMethodInstance->mReturnType;
  14408. if (retType->IsRef())
  14409. resultType = retType->GetUnderlyingType();
  14410. }
  14411. }
  14412. }
  14413. }
  14414. if (resultType == NULL)
  14415. resultType = mModule->GetPrimitiveType(BfTypeCode_None);
  14416. deferredTupleAssignData.mChildren.push_back(entry);
  14417. fieldTypes.push_back(resultType);
  14418. }
  14419. for (BfTupleNameNode* requestedName : tupleExpr->mNames)
  14420. {
  14421. if (requestedName == NULL)
  14422. fieldNames.push_back("");
  14423. else
  14424. fieldNames.push_back(requestedName->mNameNode->ToString());
  14425. }
  14426. BfTypeInstance* tupleType = mModule->CreateTupleType(fieldTypes, fieldNames, true);
  14427. deferredTupleAssignData.mTupleType = tupleType;
  14428. }
  14429. void BfExprEvaluator::AssignDeferrredTupleAssignData(BfAssignmentExpression* assignExpr, DeferredTupleAssignData& deferredTupleAssignData, BfTypedValue rightValue)
  14430. {
  14431. BF_ASSERT(rightValue.mType->IsTuple());
  14432. auto tupleType = (BfTypeInstance*)rightValue.mType;
  14433. for (int valueIdx = 0; valueIdx < (int)deferredTupleAssignData.mChildren.size(); valueIdx++)
  14434. {
  14435. auto& child = deferredTupleAssignData.mChildren[valueIdx];
  14436. BfFieldInstance* fieldInstance = &tupleType->mFieldInstances[valueIdx];
  14437. BfTypedValue elementValue;
  14438. if (fieldInstance->mDataIdx >= 0)
  14439. {
  14440. auto extractedValue = mModule->mBfIRBuilder->CreateExtractValue(rightValue.mValue, fieldInstance->mDataIdx);
  14441. elementValue = BfTypedValue(extractedValue, fieldInstance->GetResolvedType());
  14442. if (child.mInnerTuple != NULL)
  14443. {
  14444. AssignDeferrredTupleAssignData(assignExpr, *child.mInnerTuple, elementValue);
  14445. delete child.mInnerTuple;
  14446. child.mInnerTuple = NULL;
  14447. }
  14448. else
  14449. {
  14450. if (child.mExprEvaluator->HasResult())
  14451. {
  14452. child.mExprEvaluator->mBfEvalExprFlags = (BfEvalExprFlags)(child.mExprEvaluator->mBfEvalExprFlags | BfEvalExprFlags_NoAutoComplete);
  14453. child.mExprEvaluator->PerformAssignment(assignExpr, true, elementValue);
  14454. }
  14455. }
  14456. }
  14457. if (auto varDecl = BfNodeDynCast<BfVariableDeclaration>(child.mExpr))
  14458. {
  14459. if (!elementValue)
  14460. elementValue = mModule->GetDefaultTypedValue(fieldInstance->GetResolvedType());
  14461. mModule->HandleVariableDeclaration(varDecl, elementValue);
  14462. }
  14463. }
  14464. }
  14465. void BfExprEvaluator::DoTupleAssignment(BfAssignmentExpression* assignExpr)
  14466. {
  14467. auto tupleExpr = BfNodeDynCast<BfTupleExpression>(assignExpr->mLeft);
  14468. DeferredTupleAssignData deferredTupleAssignData;
  14469. PopulateDeferrredTupleAssignData(tupleExpr, deferredTupleAssignData);
  14470. BfTypeInstance* tupleType = deferredTupleAssignData.mTupleType;
  14471. BfTypedValue rightValue;
  14472. if (assignExpr->mRight != NULL)
  14473. {
  14474. rightValue = mModule->CreateValueFromExpression(assignExpr->mRight, tupleType);
  14475. }
  14476. if (!rightValue)
  14477. {
  14478. tupleType = mModule->SantizeTupleType(tupleType);
  14479. rightValue = mModule->GetDefaultTypedValue(tupleType);
  14480. }
  14481. rightValue = mModule->LoadValue(rightValue);
  14482. AssignDeferrredTupleAssignData(assignExpr, deferredTupleAssignData, rightValue);
  14483. mResult = rightValue;
  14484. }
  14485. void BfExprEvaluator::PerformAssignment(BfAssignmentExpression* assignExpr, bool evaluatedLeft, BfTypedValue rightValue, BfTypedValue* outCascadeValue)
  14486. {
  14487. auto binaryOp = BfAssignOpToBinaryOp(assignExpr->mOp);
  14488. BfExpression* targetNode = assignExpr->mLeft;
  14489. if ((BfNodeIsA<BfMixinExpression>(targetNode)) && (!mModule->mCurMethodInstance->mIsUnspecialized))
  14490. {
  14491. // If we have a "mixin = <X>" but there's no mixin target then ignore the assignment
  14492. int mixinVar = GetMixinVariable();
  14493. if (mixinVar == -1)
  14494. {
  14495. mResult = mModule->GetDefaultTypedValue(mModule->GetPrimitiveType(BfTypeCode_None));
  14496. return;
  14497. }
  14498. }
  14499. BfAutoComplete* autoComplete = GetAutoComplete();
  14500. bool deferredFixits = false;
  14501. if ((autoComplete != NULL) && (autoComplete->mResolveType == BfResolveType_GetFixits))
  14502. {
  14503. SetAndRestoreValue<bool> ignoreFixits(autoComplete->mIgnoreFixits, true);
  14504. VisitChild(targetNode);
  14505. deferredFixits = true;
  14506. }
  14507. else if (!evaluatedLeft)
  14508. {
  14509. if (auto memberReferenceExpr = BfNodeDynCast<BfMemberReferenceExpression>(targetNode))
  14510. {
  14511. DoMemberReference(memberReferenceExpr, outCascadeValue);
  14512. }
  14513. else
  14514. VisitChild(targetNode);
  14515. }
  14516. if ((!mResult) && (mPropDef == NULL))
  14517. {
  14518. if (assignExpr->mRight != NULL)
  14519. {
  14520. auto result = mModule->CreateValueFromExpression(assignExpr->mRight);
  14521. if (deferredFixits)
  14522. {
  14523. SetAndRestoreValue<bool> ignoreErrors(mModule->mIgnoreErrors, true);
  14524. mExpectingType = result.mType;
  14525. VisitChild(targetNode);
  14526. mResult = BfTypedValue();
  14527. }
  14528. }
  14529. return;
  14530. }
  14531. ResolveGenericType();
  14532. auto ptr = mResult;
  14533. mResult = BfTypedValue();
  14534. if (mPropDef == NULL)
  14535. {
  14536. if (!CheckModifyResult(ptr, assignExpr->mOpToken, "assign to"))
  14537. {
  14538. if (assignExpr->mRight != NULL)
  14539. mModule->CreateValueFromExpression(assignExpr->mRight, ptr.mType, BfEvalExprFlags_NoCast);
  14540. return;
  14541. }
  14542. }
  14543. if (mPropDef != NULL)
  14544. {
  14545. bool hasLeftVal = false;
  14546. auto propDef = mPropDef;
  14547. auto propTarget = mPropTarget;
  14548. auto setMethod = GetPropertyMethodDef(mPropDef, BfMethodType_PropertySetter, mPropCheckedKind, mPropTarget);
  14549. if (setMethod == NULL)
  14550. {
  14551. // Allow for a ref return on the getter to be used if a setter is not available
  14552. GetResult();
  14553. if ((mResult) && (mResult.mKind == BfTypedValueKind_Addr))
  14554. {
  14555. ptr = mResult;
  14556. mResult = BfTypedValue();
  14557. hasLeftVal = true;
  14558. }
  14559. else
  14560. {
  14561. mModule->Fail("Property has no setter", mPropSrc);
  14562. if (assignExpr->mRight != NULL)
  14563. mModule->CreateValueFromExpression(assignExpr->mRight, ptr.mType, BfEvalExprFlags_NoCast);
  14564. return;
  14565. }
  14566. }
  14567. if (!hasLeftVal)
  14568. {
  14569. auto methodInstance = GetPropertyMethodInstance(setMethod);
  14570. if (methodInstance.mMethodInstance == NULL)
  14571. return;
  14572. //BF_ASSERT(methodInstance.mMethodInstance->mMethodDef == setMethod);
  14573. CheckPropFail(setMethod, methodInstance.mMethodInstance, (mPropGetMethodFlags & BfGetMethodInstanceFlag_Friend) == 0);
  14574. auto autoComplete = GetAutoComplete();
  14575. if ((autoComplete != NULL) && (autoComplete->IsAutocompleteNode(mPropSrc)) && (autoComplete->mResolveType == BfResolveType_GetResultString))
  14576. {
  14577. autoComplete->mResultString = ":";
  14578. autoComplete->mResultString += mModule->TypeToString(methodInstance.mMethodInstance->GetParamType(0));
  14579. autoComplete->mResultString += " ";
  14580. autoComplete->mResultString += mModule->TypeToString(methodInstance.mMethodInstance->GetOwner());
  14581. autoComplete->mResultString += ".";
  14582. autoComplete->mResultString += mPropDef->mName;
  14583. }
  14584. BfTypedValue convVal;
  14585. if (binaryOp != BfBinaryOp_None)
  14586. {
  14587. PerformBinaryOperation(assignExpr->mLeft, assignExpr->mRight, binaryOp, assignExpr->mOpToken, BfBinOpFlag_ForceLeftType);
  14588. if (!mResult)
  14589. return;
  14590. convVal = mResult;
  14591. mResult = BfTypedValue();
  14592. if (!convVal)
  14593. return;
  14594. }
  14595. else
  14596. {
  14597. auto wantType = methodInstance.mMethodInstance->GetParamType(methodInstance.mMethodInstance->GetParamCount() - 1);
  14598. if (rightValue)
  14599. {
  14600. convVal = mModule->Cast(assignExpr->mRight, rightValue, wantType);
  14601. }
  14602. else
  14603. {
  14604. if (assignExpr->mRight == NULL)
  14605. {
  14606. mModule->AssertErrorState();
  14607. return;
  14608. }
  14609. convVal = mModule->CreateValueFromExpression(assignExpr->mRight, wantType, (BfEvalExprFlags)(BfEvalExprFlags_AllowSplat | BfEvalExprFlags_PendingPropSet));
  14610. }
  14611. if (!convVal)
  14612. {
  14613. mPropDef = NULL;
  14614. return;
  14615. }
  14616. }
  14617. if (mPropSrc != NULL)
  14618. mModule->UpdateExprSrcPos(mPropSrc);
  14619. SizedArray<BfIRValue, 4> args;
  14620. if (!setMethod->mIsStatic)
  14621. {
  14622. auto owner = methodInstance.mMethodInstance->GetOwner();
  14623. if (mPropTarget.mType != owner)
  14624. {
  14625. if (mPropDefBypassVirtual)
  14626. mPropTarget = mModule->Cast(mPropSrc, mOrigPropTarget, owner);
  14627. }
  14628. mModule->EmitObjectAccessCheck(mPropTarget);
  14629. PushThis(mPropSrc, mPropTarget, methodInstance.mMethodInstance, args);
  14630. }
  14631. for (int paramIdx = 0; paramIdx < (int)mIndexerValues.size(); paramIdx++)
  14632. {
  14633. auto refNode = mIndexerValues[paramIdx].mExpression;
  14634. auto wantType = methodInstance.mMethodInstance->GetParamType(paramIdx);
  14635. auto argValue = ResolveArgValue(mIndexerValues[paramIdx], wantType);
  14636. if (refNode == NULL)
  14637. refNode = mPropSrc;
  14638. auto val = mModule->Cast(refNode, argValue, wantType);
  14639. if (!val)
  14640. {
  14641. mPropDef = NULL;
  14642. return;
  14643. }
  14644. PushArg(val, args);
  14645. }
  14646. PushArg(convVal, args);
  14647. if (methodInstance)
  14648. CreateCall(assignExpr, methodInstance.mMethodInstance, methodInstance.mFunc, mPropDefBypassVirtual, args);
  14649. mPropDef = NULL;
  14650. mResult = convVal;
  14651. return;
  14652. }
  14653. }
  14654. auto toType = ptr.mType;
  14655. if (toType->IsRef())
  14656. {
  14657. auto refType = (BfRefType*)toType;
  14658. toType = refType->mElementType;
  14659. }
  14660. if ((autoComplete != NULL) && (assignExpr->mOpToken != NULL) && (toType != NULL))
  14661. autoComplete->CheckEmptyStart(assignExpr->mOpToken, toType);
  14662. BfExpression* rightExpr = assignExpr->mRight;
  14663. if (rightExpr == NULL)
  14664. {
  14665. mModule->AssertErrorState();
  14666. return;
  14667. }
  14668. bool alreadyWritten = false;
  14669. BfTypedValue convVal;
  14670. if (binaryOp != BfBinaryOp_None)
  14671. {
  14672. CheckResultForReading(ptr);
  14673. BfTypedValue leftValue = ptr;
  14674. auto expectedType = ptr.mType;
  14675. if ((binaryOp == BfBinaryOp_LeftShift) || (binaryOp == BfBinaryOp_RightShift))
  14676. expectedType = mModule->GetPrimitiveType(BfTypeCode_IntPtr);
  14677. if ((!rightValue) && (assignExpr->mRight != NULL))
  14678. {
  14679. rightValue = mModule->CreateValueFromExpression(assignExpr->mRight, expectedType, (BfEvalExprFlags)(BfEvalExprFlags_AllowSplat | BfEvalExprFlags_NoCast));
  14680. }
  14681. bool handled = false;
  14682. if (rightValue)
  14683. {
  14684. auto checkTypeInst = leftValue.mType->ToTypeInstance();
  14685. while (checkTypeInst != NULL)
  14686. {
  14687. for (auto operatorDef : checkTypeInst->mTypeDef->mOperators)
  14688. {
  14689. if (operatorDef->mOperatorDeclaration->mAssignOp != assignExpr->mOp)
  14690. continue;
  14691. auto methodInst = mModule->GetRawMethodInstanceAtIdx(checkTypeInst, operatorDef->mIdx);
  14692. if (methodInst->GetParamCount() != 1)
  14693. continue;
  14694. auto paramType = methodInst->GetParamType(0);
  14695. if (!mModule->CanCast(rightValue, paramType))
  14696. continue;
  14697. mModule->SetElementType(assignExpr->mOpToken, BfSourceElementType_Method);
  14698. if ((autoComplete != NULL) && (autoComplete->IsAutocompleteNode(assignExpr->mOpToken)))
  14699. {
  14700. if (operatorDef->mOperatorDeclaration != NULL)
  14701. autoComplete->SetDefinitionLocation(operatorDef->mOperatorDeclaration->mOpTypeToken);
  14702. }
  14703. auto moduleMethodInstance = mModule->GetMethodInstance(checkTypeInst, operatorDef, BfTypeVector());
  14704. BfExprEvaluator exprEvaluator(mModule);
  14705. SizedArray<BfIRValue, 1> args;
  14706. exprEvaluator.PushThis(assignExpr->mLeft, leftValue, moduleMethodInstance.mMethodInstance, args);
  14707. exprEvaluator.PushArg(rightValue, args);
  14708. exprEvaluator.CreateCall(assignExpr, moduleMethodInstance.mMethodInstance, moduleMethodInstance.mFunc, false, args);
  14709. convVal = leftValue;
  14710. handled = true;
  14711. break;
  14712. }
  14713. if (handled)
  14714. break;
  14715. checkTypeInst = mModule->GetBaseType(checkTypeInst);
  14716. }
  14717. if (!handled)
  14718. {
  14719. leftValue = mModule->LoadValue(leftValue);
  14720. PerformBinaryOperation(assignExpr->mLeft, assignExpr->mRight, binaryOp, assignExpr->mOpToken, BfBinOpFlag_ForceLeftType, leftValue, rightValue);
  14721. }
  14722. }
  14723. if (!handled)
  14724. {
  14725. convVal = mResult;
  14726. mResult = BfTypedValue();
  14727. }
  14728. if (!convVal)
  14729. return;
  14730. }
  14731. else
  14732. {
  14733. convVal = rightValue;
  14734. if (!convVal)
  14735. {
  14736. if (auto uninitExpr = BfNodeDynCast<BfUninitializedExpression>(rightExpr))
  14737. {
  14738. if (mResultLocalVar != NULL)
  14739. {
  14740. MarkResultAssigned();
  14741. return;
  14742. }
  14743. }
  14744. // In the cases like "structVal = GetVal()", the allowDirectStructRetWrite optimization allows us to pass the
  14745. // address of structVal into the sret. We only allow that if structVal is a local, because if it's globally
  14746. // visible then we could see the results of a partially-modified structVal
  14747. //bool allowDirectStructRetWrite = mResultLocalVarIdx != -1;
  14748. // ALTHOUGH- we can only allow this optimization if we can be sure the local value is not aliased- we could
  14749. // have the backend ensure that this local value never gets its address taken.
  14750. bool allowDirectStructWrite = false;
  14751. BfExprEvaluator exprEvaluator(mModule);
  14752. exprEvaluator.mExpectingType = toType;
  14753. if (allowDirectStructWrite)
  14754. exprEvaluator.mReceivingValue = &ptr;
  14755. exprEvaluator.Evaluate(rightExpr, false, false, true);
  14756. exprEvaluator.CheckResultForReading(exprEvaluator.mResult);
  14757. convVal = exprEvaluator.GetResult();
  14758. mModule->FixIntUnknown(convVal);
  14759. alreadyWritten = (allowDirectStructWrite) && (exprEvaluator.mReceivingValue == NULL);
  14760. if (!convVal)
  14761. convVal = mModule->GetDefaultTypedValue(toType);
  14762. // Did we use mReceivingValue as a mixin result?
  14763. if ((convVal.mValue) && (convVal.mValue == ptr.mValue))
  14764. {
  14765. mResult = convVal;
  14766. return;
  14767. }
  14768. }
  14769. }
  14770. BF_ASSERT(convVal);
  14771. if ((convVal) && (convVal.mType->IsNull()) && (ptr.mType->IsNullable()))
  14772. {
  14773. // Allow this to pass through so we can catch it in the memset later in this function
  14774. }
  14775. else
  14776. {
  14777. if (!convVal.mType->IsComposite())
  14778. convVal = mModule->LoadValue(convVal);
  14779. convVal = mModule->Cast(rightExpr, convVal, toType);
  14780. if (!convVal)
  14781. return;
  14782. convVal = mModule->LoadValue(convVal);
  14783. }
  14784. if (ptr.mType->IsVar())
  14785. {
  14786. mResult = ptr;
  14787. return;
  14788. }
  14789. if (convVal.mValue)
  14790. {
  14791. if ((ptr.mType->IsStruct()) && (!ptr.mType->IsValuelessType()) && (convVal.mValue.IsConst()))
  14792. {
  14793. auto constant = mModule->mBfIRBuilder->GetConstant(convVal.mValue);
  14794. if ((constant->mTypeCode == BfTypeCode_NullPtr) || (constant->mConstType == BfConstType_AggZero))
  14795. {
  14796. auto type = ptr.mType;
  14797. mModule->mBfIRBuilder->CreateMemSet(ptr.mValue, mModule->GetConstValue(0, mModule->GetPrimitiveType(BfTypeCode_Int8)),
  14798. mModule->GetConstValue(type->mSize), type->mAlign);
  14799. mResult = ptr;
  14800. MarkResultAssigned();
  14801. return;
  14802. }
  14803. }
  14804. // if (ptr.mType->IsMethodRef())
  14805. // {
  14806. // auto methodRefType = (BfMethodRefType*)ptr.mType;
  14807. // auto methodInstance = methodRefType->mMethodInstance;
  14808. // int implicitParamCount = methodInstance->GetImplicitParamCount();
  14809. // for (int implicitParamIdx = methodInstance->HasThis() ? - 1 : 0; implicitParamIdx < implicitParamCount; implicitParamIdx++)
  14810. // {
  14811. // bool failed = false;
  14812. // auto destPtr = DoImplicitArgCapture(assignExpr, methodRefType->mMethodInstance, implicitParamIdx, failed, BfImplicitParamKind_GenericTypeMember_Addr);
  14813. // auto srcVal = DoImplicitArgCapture(assignExpr, methodRefType->mMethodInstance, implicitParamIdx, failed, BfImplicitParamKind_GenericMethodMember);
  14814. // if ((destPtr) && (srcVal))
  14815. // {
  14816. // srcVal = mModule->AggregateSplat(srcVal);
  14817. // mModule->mBfIRBuilder->CreateStore(srcVal.mValue, destPtr.mValue);
  14818. // }
  14819. // }
  14820. // }
  14821. // else
  14822. {
  14823. mModule->mBfIRBuilder->PopulateType(ptr.mType);
  14824. if (convVal.IsSplat())
  14825. {
  14826. //convVal = mModule->AggregateSplat(convVal);
  14827. mModule->AggregateSplatIntoAddr(convVal, ptr.mValue);
  14828. }
  14829. else
  14830. {
  14831. if (ptr.mType->IsValuelessType())
  14832. {
  14833. mModule->EmitEnsureInstructionAt();
  14834. }
  14835. else if (!alreadyWritten)
  14836. {
  14837. //ptr = mModule->LoadValue(ptr);
  14838. BF_ASSERT(ptr.IsAddr());
  14839. convVal = mModule->LoadValue(convVal);
  14840. auto storeInst = mModule->mBfIRBuilder->CreateAlignedStore(convVal.mValue, ptr.mValue, ptr.mType->mAlign, mIsVolatileReference);
  14841. }
  14842. }
  14843. }
  14844. }
  14845. else
  14846. {
  14847. BF_ASSERT(convVal.mType->IsValuelessType());
  14848. }
  14849. mResult = convVal;
  14850. MarkResultAssigned();
  14851. }
  14852. void BfExprEvaluator::Visit(BfAssignmentExpression* assignExpr)
  14853. {
  14854. if (assignExpr->mLeft->IsA<BfTupleExpression>())
  14855. {
  14856. DoTupleAssignment(assignExpr);
  14857. return;
  14858. }
  14859. BfAutoParentNodeEntry autoParentNodeEntry(mModule, assignExpr);
  14860. BfTypedValue cascadeValue;
  14861. PerformAssignment(assignExpr, false, BfTypedValue(), &cascadeValue);
  14862. if (cascadeValue)
  14863. mResult = cascadeValue;
  14864. }
  14865. void BfExprEvaluator::Visit(BfParenthesizedExpression* parenExpr)
  14866. {
  14867. VisitChild(parenExpr->mExpression);
  14868. MakeResultAsValue();
  14869. }
  14870. void BfExprEvaluator::InitializedSizedArray(BfSizedArrayType* arrayType, BfTokenNode* openToken, const BfSizedArray<BfExpression*>& valueExprs, const BfSizedArray<BfTokenNode*>& commas, BfTokenNode* closeToken, BfTypedValue* receivingValue)
  14871. {
  14872. struct InitValue
  14873. {
  14874. BfTypedValue mValue;
  14875. bool mIsUninitialized;
  14876. bool mIsDefaultInitializer;
  14877. bool mIsDeferred;
  14878. InitValue()
  14879. {
  14880. mIsUninitialized = false;
  14881. mIsDefaultInitializer = false;
  14882. mIsDeferred = false;
  14883. }
  14884. };
  14885. SizedArray<InitValue, 8> values;
  14886. {
  14887. //bool hasFailed = false;
  14888. HashSet<int> failedAt;
  14889. bool isAllConst = true;
  14890. //bool endUninitialzied = false;
  14891. int depth = 0;
  14892. std::function<void(BfSizedArrayType*, BfTokenNode* openToken, const BfSizedArray<BfExpression*>&, const BfSizedArray<BfTokenNode*>&, BfTokenNode*, bool)>
  14893. _GetValues = [&](BfSizedArrayType* checkArrayType, BfTokenNode* openToken, const BfSizedArray<BfExpression*>& valueExprs, const BfSizedArray<BfTokenNode*>& commas, BfTokenNode* closeToken, bool ignore)
  14894. {
  14895. int64 initCountDiff = (int)valueExprs.size() - checkArrayType->mElementCount;
  14896. if ((initCountDiff != 0) && (!valueExprs.IsEmpty()) && (!failedAt.Contains(depth)))
  14897. {
  14898. if (checkArrayType->mElementCount == -1)
  14899. {
  14900. mModule->Fail("Initializers not supported for unknown-sized arrays", valueExprs[0]);
  14901. failedAt.Add(depth);
  14902. }
  14903. else if (initCountDiff > 0)
  14904. {
  14905. mModule->Fail(StrFormat("Too many initializers, expected %d fewer", initCountDiff), valueExprs[BF_MAX((int)checkArrayType->mElementCount, 0)]);
  14906. failedAt.Add(depth);
  14907. }
  14908. else
  14909. {
  14910. // If it ends with ", ?) or ",)" then allow unsized
  14911. if (((valueExprs.size() == 0) || (BfNodeDynCast<BfUninitializedExpression>(valueExprs.back()) == NULL)) &&
  14912. ((commas.size() < valueExprs.size()) || (valueExprs.size() == 0)))
  14913. {
  14914. BfAstNode* refNode = closeToken;
  14915. if ((refNode == NULL) && (mModule->mParentNodeEntry != NULL))
  14916. refNode = mModule->mParentNodeEntry->mNode;
  14917. BF_ASSERT(refNode != NULL);
  14918. mModule->Fail(StrFormat("Too few initializer, expected %d more", -initCountDiff), refNode);
  14919. failedAt.Add(depth);
  14920. }
  14921. }
  14922. }
  14923. for (int idx = 0; idx < BF_MAX(checkArrayType->mElementCount, valueExprs.size()); idx++)
  14924. {
  14925. BfTypedValue elementValue;
  14926. bool deferredValue = false;
  14927. BfExpression* expr = NULL;
  14928. if (idx < (int)valueExprs.size())
  14929. {
  14930. expr = valueExprs[idx];
  14931. if (expr == NULL)
  14932. {
  14933. if (idx == 0)
  14934. mModule->FailAfter("Expression expected", openToken);
  14935. else
  14936. mModule->FailAfter("Expression expected", commas[idx - 1]);
  14937. }
  14938. if ((BfNodeDynCastExact<BfUninitializedExpression>(expr) != NULL) && (idx == (int)commas.size()))
  14939. {
  14940. isAllConst = false;
  14941. break;
  14942. }
  14943. if (checkArrayType->mElementType->IsSizedArray())
  14944. {
  14945. if (auto arrayInitExpr = BfNodeDynCast<BfTupleExpression>(expr))
  14946. {
  14947. depth++;
  14948. _GetValues((BfSizedArrayType*)checkArrayType->mElementType, arrayInitExpr->mOpenParen, arrayInitExpr->mValues, arrayInitExpr->mCommas, arrayInitExpr->mCloseParen, ignore);
  14949. depth--;
  14950. continue;
  14951. }
  14952. else if (auto arrayInitExpr = BfNodeDynCast<BfCollectionInitializerExpression>(expr))
  14953. {
  14954. depth++;
  14955. _GetValues((BfSizedArrayType*)checkArrayType->mElementType, arrayInitExpr->mOpenBrace, arrayInitExpr->mValues, arrayInitExpr->mCommas, arrayInitExpr->mCloseBrace, ignore);
  14956. depth--;
  14957. continue;
  14958. }
  14959. else if (auto parenExpr = BfNodeDynCast<BfParenthesizedExpression>(expr))
  14960. {
  14961. depth++;
  14962. SizedArray<BfExpression*, 1> values;
  14963. values.Add(parenExpr->mExpression);
  14964. SizedArray<BfTokenNode*, 1> commas;
  14965. _GetValues((BfSizedArrayType*)checkArrayType->mElementType, parenExpr->mOpenParen, values, commas, parenExpr->mCloseParen, ignore);
  14966. depth--;
  14967. continue;
  14968. }
  14969. }
  14970. if (expr != NULL)
  14971. {
  14972. bool tryDefer = false;
  14973. if ((checkArrayType->IsComposite()) &&
  14974. ((expr->IsA<BfInvocationExpression>()) || (expr->IsExact<BfTupleExpression>())))
  14975. {
  14976. // We evaluate with a new scope because this expression may create variables that we don't want to be visible to other
  14977. // non-deferred evaluations (since the value may actually be a FakeVal)
  14978. SetAndRestoreValue<bool> prevIgnoreWrites(mModule->mBfIRBuilder->mIgnoreWrites, true);
  14979. elementValue = mModule->CreateValueFromExpression(expr, checkArrayType->mElementType, BfEvalExprFlags_CreateConditionalScope);
  14980. deferredValue = !prevIgnoreWrites.mPrevVal && elementValue.mValue.IsFake();
  14981. }
  14982. else
  14983. {
  14984. elementValue = mModule->CreateValueFromExpression(expr, checkArrayType->mElementType);
  14985. }
  14986. if (!elementValue)
  14987. elementValue = mModule->GetDefaultTypedValue(checkArrayType->mElementType);
  14988. if ((!elementValue) || (!CheckAllowValue(elementValue, expr)))
  14989. elementValue = mModule->GetDefaultTypedValue(checkArrayType->mElementType);
  14990. // For now, we can't properly create const-valued non-size-aligned composites
  14991. if (checkArrayType->mElementType->NeedsExplicitAlignment())
  14992. isAllConst = false;
  14993. if (!elementValue.mValue.IsConst())
  14994. isAllConst = false;
  14995. if (elementValue.IsAddr())
  14996. isAllConst = false;
  14997. InitValue initValue;
  14998. initValue.mValue = elementValue;
  14999. initValue.mIsDeferred = deferredValue;
  15000. values.push_back(initValue);
  15001. }
  15002. }
  15003. }
  15004. };
  15005. int valueIdx = 0;
  15006. std::function<void(BfTypedValue, BfTokenNode* openToken, const BfSizedArray<BfExpression*>&, const BfSizedArray<BfTokenNode*>&, BfTokenNode*)>
  15007. _CreateMemArray = [&](BfTypedValue arrayValue, BfTokenNode* openToken, const BfSizedArray<BfExpression*>& valueExprs, const BfSizedArray<BfTokenNode*>& commas, BfTokenNode* closeToken)
  15008. {
  15009. BF_ASSERT(arrayValue.mType->IsSizedArray());
  15010. auto checkArrayType = (BfSizedArrayType*)arrayValue.mType;
  15011. int valIdx = 0;
  15012. bool hasUninit = false;
  15013. for (int idx = 0; idx < checkArrayType->mElementCount; idx++)
  15014. {
  15015. BfExpression* expr = NULL;
  15016. BfTypedValue elementValue;
  15017. if (idx >= (int)valueExprs.size())
  15018. break;
  15019. expr = valueExprs[idx];
  15020. if ((BfNodeDynCastExact<BfUninitializedExpression>(expr) != NULL) && (idx == (int)commas.size()))
  15021. {
  15022. hasUninit = true;
  15023. break;
  15024. }
  15025. BfIRValue elemPtrValue = mModule->CreateIndexedValue(checkArrayType->mElementType, arrayValue.mValue, valIdx, true);
  15026. valIdx++;
  15027. if (checkArrayType->mElementType->IsSizedArray())
  15028. {
  15029. if (auto arrayInitExpr = BfNodeDynCast<BfTupleExpression>(expr))
  15030. {
  15031. _CreateMemArray(BfTypedValue(elemPtrValue, checkArrayType->mElementType, true), arrayInitExpr->mOpenParen, arrayInitExpr->mValues, arrayInitExpr->mCommas, arrayInitExpr->mCloseParen);
  15032. continue;
  15033. }
  15034. else if (auto arrayInitExpr = BfNodeDynCast<BfCollectionInitializerExpression>(expr))
  15035. {
  15036. _CreateMemArray(BfTypedValue(elemPtrValue, checkArrayType->mElementType, true), arrayInitExpr->mOpenBrace, arrayInitExpr->mValues, arrayInitExpr->mCommas, arrayInitExpr->mCloseBrace);
  15037. continue;
  15038. }
  15039. else if (auto parenExpr = BfNodeDynCast<BfParenthesizedExpression>(expr))
  15040. {
  15041. depth++;
  15042. SizedArray<BfExpression*, 1> values;
  15043. values.Add(parenExpr->mExpression);
  15044. SizedArray<BfTokenNode*, 1> commas;
  15045. _CreateMemArray(BfTypedValue(elemPtrValue, checkArrayType->mElementType, true), parenExpr->mOpenParen, values, commas, parenExpr->mCloseParen);
  15046. depth--;
  15047. continue;
  15048. }
  15049. }
  15050. if (expr != NULL)
  15051. {
  15052. InitValue initValue = values[valueIdx++];
  15053. elementValue = initValue.mValue;
  15054. if (initValue.mIsDeferred)
  15055. {
  15056. BfTypedValue elemePtrTypedVal = BfTypedValue(elemPtrValue, checkArrayType->mElementType, BfTypedValueKind_Addr);
  15057. BfExprEvaluator exprEvaluator(mModule);
  15058. exprEvaluator.mExpectingType = checkArrayType->mElementType;
  15059. exprEvaluator.mReceivingValue = &elemePtrTypedVal;
  15060. exprEvaluator.Evaluate(expr);
  15061. exprEvaluator.GetResult();
  15062. if (exprEvaluator.mReceivingValue == NULL)
  15063. {
  15064. // We wrote directly to the array in-place, we're done with this element
  15065. continue;
  15066. }
  15067. elementValue = exprEvaluator.mResult;
  15068. elementValue = mModule->Cast(expr, elementValue, checkArrayType->mElementType);
  15069. if (!elementValue)
  15070. {
  15071. mModule->AssertErrorState();
  15072. continue;
  15073. }
  15074. }
  15075. elementValue = mModule->LoadValue(elementValue);
  15076. mModule->mBfIRBuilder->CreateAlignedStore(elementValue.mValue, elemPtrValue, checkArrayType->mElementType->mAlign);
  15077. }
  15078. }
  15079. int fillCount = (int)(checkArrayType->mElementCount - valIdx);
  15080. if (fillCount > 0)
  15081. {
  15082. BfIRValue elemPtrValue = mModule->CreateIndexedValue(checkArrayType->mElementType, arrayValue.mValue, valIdx, true);
  15083. if (hasUninit)
  15084. {
  15085. if (!mModule->IsOptimized())
  15086. {
  15087. int setSize = std::min(checkArrayType->mElementType->mSize, 128); // Keep it to a reasonable number of bytes to trash
  15088. mModule->mBfIRBuilder->CreateMemSet(elemPtrValue, mModule->mBfIRBuilder->CreateConst(BfTypeCode_Int8, 0xCC),
  15089. mModule->GetConstValue(setSize), checkArrayType->mElementType->mAlign);
  15090. }
  15091. }
  15092. else
  15093. {
  15094. int setSize = (int)((checkArrayType->mElementType->GetStride() * (fillCount - 1)) + checkArrayType->mElementType->mSize);
  15095. if (setSize >= 0)
  15096. {
  15097. mModule->mBfIRBuilder->CreateMemSet(elemPtrValue, mModule->mBfIRBuilder->CreateConst(BfTypeCode_Int8, 0),
  15098. mModule->GetConstValue(setSize), checkArrayType->mElementType->mAlign);
  15099. }
  15100. }
  15101. }
  15102. };
  15103. std::function<BfIRValue(BfTypedValue, BfTokenNode*, const BfSizedArray<BfExpression*>&, const BfSizedArray<BfTokenNode*>&, BfTokenNode*)>
  15104. _CreateConstArray = [&](BfTypedValue arrayValue, BfTokenNode* openToken, const BfSizedArray<BfExpression*>& valueExprs, const BfSizedArray<BfTokenNode*>& commas, BfTokenNode* closeToken)
  15105. {
  15106. SizedArray<BfIRValue, 8> members;
  15107. BF_ASSERT(arrayValue.mType->IsSizedArray());
  15108. auto checkArrayType = (BfSizedArrayType*)arrayValue.mType;
  15109. int valIdx = 0;
  15110. for (int idx = 0; idx < checkArrayType->mElementCount; idx++)
  15111. {
  15112. BfTypedValue elementValue;
  15113. if (idx >= (int)valueExprs.size())
  15114. break;
  15115. auto expr = valueExprs[idx];
  15116. if (expr == NULL)
  15117. continue;
  15118. valIdx++;
  15119. if (checkArrayType->mElementType->IsSizedArray())
  15120. {
  15121. if (auto arrayInitExpr = BfNodeDynCast<BfTupleExpression>(expr))
  15122. {
  15123. members.push_back(_CreateConstArray(checkArrayType->mElementType, arrayInitExpr->mOpenParen, arrayInitExpr->mValues, arrayInitExpr->mCommas, arrayInitExpr->mCloseParen));
  15124. continue;
  15125. }
  15126. else if (auto arrayInitExpr = BfNodeDynCast<BfCollectionInitializerExpression>(expr))
  15127. {
  15128. members.push_back(_CreateConstArray(checkArrayType->mElementType, arrayInitExpr->mOpenBrace, arrayInitExpr->mValues, arrayInitExpr->mCommas, arrayInitExpr->mCloseBrace));
  15129. continue;
  15130. }
  15131. else if (auto parenExpr = BfNodeDynCast<BfParenthesizedExpression>(expr))
  15132. {
  15133. depth++;
  15134. SizedArray<BfExpression*, 1> values;
  15135. values.Add(parenExpr->mExpression);
  15136. SizedArray<BfTokenNode*, 1> commas;
  15137. members.push_back(_CreateConstArray(checkArrayType->mElementType, parenExpr->mOpenParen, values, commas, parenExpr->mCloseParen));
  15138. depth--;
  15139. continue;
  15140. }
  15141. }
  15142. InitValue initValue = values[valueIdx++];
  15143. BF_ASSERT(!initValue.mIsUninitialized);
  15144. elementValue = initValue.mValue;
  15145. members.push_back(elementValue.mValue);
  15146. }
  15147. int fillCount = (int)(checkArrayType->mElementCount - valIdx);
  15148. if (fillCount > 0)
  15149. {
  15150. // We just need to insert one default value, it will be duplicated as needed into the backend
  15151. auto defaultVal = mModule->GetDefaultTypedValue(checkArrayType->GetUnderlyingType());
  15152. BF_ASSERT(defaultVal.mValue.IsConst());
  15153. members.push_back(defaultVal.mValue);
  15154. }
  15155. if (checkArrayType->mElementType->IsStruct())
  15156. {
  15157. // This fixed cases where we have non-size-aligned initializers. Assume zero-initialized
  15158. return mModule->mBfIRBuilder->CreateConstStructZero(mModule->mBfIRBuilder->MapType(checkArrayType));
  15159. }
  15160. else
  15161. return mModule->mBfIRBuilder->CreateConstArray(mModule->mBfIRBuilder->MapType(checkArrayType), members);
  15162. };
  15163. _GetValues(arrayType, openToken, valueExprs, commas, closeToken, false);
  15164. if (!failedAt.IsEmpty())
  15165. {
  15166. mResult = mModule->GetDefaultTypedValue(arrayType, false, BfDefaultValueKind_Addr);
  15167. return;
  15168. }
  15169. if (receivingValue != NULL)
  15170. {
  15171. BF_ASSERT(receivingValue->mType == arrayType);
  15172. BF_ASSERT(receivingValue->IsAddr());
  15173. mResult = *receivingValue;
  15174. _CreateMemArray(mResult, openToken, valueExprs, commas, closeToken);
  15175. }
  15176. else if (isAllConst)
  15177. {
  15178. mResult = BfTypedValue(_CreateConstArray(arrayType, openToken, valueExprs, commas, closeToken), arrayType, BfTypedValueKind_Value);
  15179. }
  15180. else
  15181. {
  15182. if ((mReceivingValue != NULL) && (mReceivingValue->mType == arrayType) && (mReceivingValue->IsAddr()))
  15183. {
  15184. mResult = *mReceivingValue;
  15185. mReceivingValue = NULL;
  15186. }
  15187. else
  15188. {
  15189. auto arrayValue = mModule->CreateAlloca(arrayType);
  15190. mResult = BfTypedValue(arrayValue, arrayType, BfTypedValueKind_TempAddr);
  15191. }
  15192. if (!arrayType->IsValuelessType())
  15193. _CreateMemArray(mResult, openToken, valueExprs, commas, closeToken);
  15194. }
  15195. }
  15196. }
  15197. void BfExprEvaluator::Visit(BfTupleExpression* tupleExpr)
  15198. {
  15199. BfTypeInstance* tupleType = NULL;
  15200. bool hadFullMatch = false;
  15201. if ((mExpectingType != NULL) && (mExpectingType->IsTuple()))
  15202. {
  15203. tupleType = (BfTypeInstance*)mExpectingType;
  15204. hadFullMatch = tupleType->mFieldInstances.size() == tupleExpr->mValues.size();
  15205. }
  15206. struct InitValue
  15207. {
  15208. BfTypedValue mValue;
  15209. bool mIsUninitialized;
  15210. bool mIsDefaultInitializer;
  15211. bool mIsDeferred;
  15212. InitValue()
  15213. {
  15214. mIsUninitialized = false;
  15215. mIsDefaultInitializer = false;
  15216. mIsDeferred = false;
  15217. }
  15218. };
  15219. SizedArray<BfTypedValue, 2> typedValues;
  15220. if ((tupleExpr->mCommas.size() != 0) && (tupleExpr->mCommas.size() >= tupleExpr->mValues.size()))
  15221. {
  15222. // We would normally give this error during syntax parsing, but a TupleExpression can be an array initializer
  15223. mModule->FailAfter("Expression expected", tupleExpr->mCommas.back());
  15224. }
  15225. for (int valueIdx = 0; valueIdx < (int)tupleExpr->mValues.size(); valueIdx++)
  15226. {
  15227. BfExpression* valueExpr = tupleExpr->mValues[valueIdx];
  15228. BfType* fieldType = NULL;
  15229. BfFieldInstance* fieldInstance = NULL;
  15230. if (tupleType != NULL)
  15231. {
  15232. if (valueIdx < (int)tupleType->mFieldInstances.size())
  15233. {
  15234. fieldInstance = (BfFieldInstance*)&tupleType->mFieldInstances[valueIdx];
  15235. fieldType = fieldInstance->GetResolvedType();
  15236. if (fieldType->IsVoid())
  15237. {
  15238. typedValues.push_back(BfTypedValue());
  15239. continue;
  15240. }
  15241. if (fieldType->IsVar())
  15242. {
  15243. hadFullMatch = false;
  15244. fieldType = NULL;
  15245. }
  15246. }
  15247. }
  15248. bool tryDefer = false;
  15249. if (((fieldType == NULL) || (fieldType->IsComposite())) &&
  15250. ((valueExpr->IsA<BfInvocationExpression>()) || (valueExpr->IsExact<BfTupleExpression>())))
  15251. {
  15252. tryDefer = true;
  15253. }
  15254. SetAndRestoreValue<bool> prevIgnoreWrites(mModule->mBfIRBuilder->mIgnoreWrites, mModule->mBfIRBuilder->mIgnoreWrites || tryDefer);
  15255. BfTypedValue value = mModule->CreateValueFromExpression(valueExpr, fieldType);
  15256. if (!value)
  15257. {
  15258. if (fieldType != NULL)
  15259. value = mModule->GetDefaultTypedValue(fieldType);
  15260. else
  15261. value = mModule->GetDefaultTypedValue(mModule->mContext->mBfObjectType);
  15262. }
  15263. if ((fieldInstance != NULL) && (!fieldInstance->GetFieldDef()->IsUnnamedTupleField()) && (valueIdx < (int)tupleExpr->mNames.size()))
  15264. {
  15265. auto checkName = tupleExpr->mNames[valueIdx];
  15266. if (checkName != NULL)
  15267. {
  15268. if (checkName->ToString() != fieldInstance->GetFieldDef()->mName)
  15269. hadFullMatch = false;
  15270. }
  15271. }
  15272. value = mModule->LoadValue(value);
  15273. typedValues.push_back(value);
  15274. }
  15275. if (!hadFullMatch)
  15276. {
  15277. BfTypeVector fieldTypes;
  15278. Array<String> fieldNames;
  15279. HashSet<String> fieldNameSet;
  15280. for (auto typedVal : typedValues)
  15281. {
  15282. auto type = typedVal.mType;
  15283. if (type != NULL)
  15284. fieldTypes.push_back(type);
  15285. else
  15286. fieldTypes.push_back(mModule->mContext->mBfObjectType);
  15287. }
  15288. for (BfTupleNameNode* requestedName : tupleExpr->mNames)
  15289. {
  15290. if (requestedName == NULL)
  15291. fieldNames.push_back("");
  15292. else
  15293. {
  15294. auto fieldName = requestedName->mNameNode->ToString();
  15295. if (!fieldNameSet.TryAdd(fieldName, NULL))
  15296. {
  15297. mModule->Fail(StrFormat("A field named '%s' has already been declared", fieldName.c_str()), requestedName->mNameNode);
  15298. }
  15299. fieldNames.push_back(fieldName);
  15300. }
  15301. }
  15302. tupleType = mModule->CreateTupleType(fieldTypes, fieldNames);
  15303. }
  15304. mModule->mBfIRBuilder->PopulateType(tupleType);
  15305. BfIRValue curTupleValue;
  15306. if ((mReceivingValue != NULL) && (mReceivingValue->mType == tupleType) && (mReceivingValue->IsAddr()))
  15307. {
  15308. mResult = *mReceivingValue;
  15309. mReceivingValue = NULL;
  15310. curTupleValue = mResult.mValue;
  15311. }
  15312. else
  15313. {
  15314. curTupleValue = mModule->CreateAlloca(tupleType);
  15315. mResultIsTempComposite = true;
  15316. mResult = BfTypedValue(curTupleValue, tupleType, BfTypedValueKind_TempAddr);
  15317. }
  15318. for (int valueIdx = 0; valueIdx < (int)typedValues.size(); valueIdx++)
  15319. {
  15320. BfFieldInstance* fieldInstance = &tupleType->mFieldInstances[valueIdx];
  15321. if (fieldInstance->mResolvedType->IsValuelessType())
  15322. continue;
  15323. auto typedVal = typedValues[valueIdx];
  15324. if (!typedVal)
  15325. {
  15326. mModule->AssertErrorState();
  15327. continue;
  15328. }
  15329. if (fieldInstance->mDataIdx >= 0)
  15330. {
  15331. auto memberVal = mModule->mBfIRBuilder->CreateInBoundsGEP(curTupleValue, 0, fieldInstance->mDataIdx);
  15332. if ((!mModule->mBfIRBuilder->mIgnoreWrites) && (typedVal.mValue.IsFake()))
  15333. {
  15334. // Value was deferred. Allow us to try to init in place
  15335. BfExpression* valueExpr = tupleExpr->mValues[valueIdx];
  15336. BfTypedValue memberPtrTypedVal = BfTypedValue(memberVal, fieldInstance->mResolvedType, BfTypedValueKind_Addr);
  15337. BfExprEvaluator exprEvaluator(mModule);
  15338. exprEvaluator.mExpectingType = fieldInstance->mResolvedType;
  15339. exprEvaluator.mReceivingValue = &memberPtrTypedVal;
  15340. exprEvaluator.Evaluate(valueExpr);
  15341. exprEvaluator.GetResult();
  15342. if (exprEvaluator.mReceivingValue == NULL)
  15343. {
  15344. // We wrote directly to the array in-place, we're done with this element
  15345. continue;
  15346. }
  15347. typedVal = exprEvaluator.mResult;
  15348. typedVal = mModule->Cast(valueExpr, typedVal, fieldInstance->mResolvedType);
  15349. if (!typedVal)
  15350. {
  15351. mModule->AssertErrorState();
  15352. continue;
  15353. }
  15354. typedVal = mModule->LoadValue(typedVal);
  15355. }
  15356. if (typedVal.mType->IsVar())
  15357. {
  15358. // Do nothing
  15359. }
  15360. else if (typedVal.IsSplat())
  15361. mModule->AggregateSplatIntoAddr(typedVal, memberVal);
  15362. else
  15363. mModule->mBfIRBuilder->CreateStore(typedVal.mValue, memberVal);
  15364. }
  15365. }
  15366. }
  15367. BfTypedValue BfExprEvaluator::SetupNullConditional(BfTypedValue thisValue, BfTokenNode* dotToken)
  15368. {
  15369. bool isStaticLookup = (!thisValue) ||
  15370. ((!thisValue.mType->IsValuelessType()) && (!thisValue.mValue));
  15371. if (isStaticLookup)
  15372. {
  15373. mModule->Fail("Null conditional reference not valid for static field references", dotToken);
  15374. return thisValue;
  15375. }
  15376. auto opResult = PerformUnaryOperation_TryOperator(thisValue, NULL, BfUnaryOp_NullConditional, dotToken, BfUnaryOpFlag_None);
  15377. if (opResult)
  15378. thisValue = opResult;
  15379. //TODO: But make null conditional work for Nullable types
  15380. if (thisValue.mType->IsNullable())
  15381. {
  15382. // Success
  15383. }
  15384. else if ((thisValue.mType->IsPointer()) || (thisValue.mType->IsObjectOrInterface()))
  15385. {
  15386. // Also good
  15387. }
  15388. else
  15389. {
  15390. mModule->Warn(0, StrFormat("Null conditional reference is unnecessary since value type '%s' can never be null", mModule->TypeToString(thisValue.mType).c_str()), dotToken);
  15391. return thisValue;
  15392. }
  15393. thisValue = mModule->LoadValue(thisValue);
  15394. BfPendingNullConditional* pendingNullCond = mModule->mCurMethodState->mPendingNullConditional;
  15395. if (pendingNullCond == NULL)
  15396. {
  15397. pendingNullCond = new BfPendingNullConditional();
  15398. mModule->mCurMethodState->mPendingNullConditional = pendingNullCond;
  15399. }
  15400. if (!pendingNullCond->mPrevBB)
  15401. pendingNullCond->mPrevBB = mModule->mBfIRBuilder->GetInsertBlock();
  15402. if (!pendingNullCond->mDoneBB)
  15403. pendingNullCond->mDoneBB = mModule->mBfIRBuilder->CreateBlock("nullCond.done");
  15404. // We will in the br to checkBB later
  15405. if (!pendingNullCond->mCheckBB)
  15406. {
  15407. pendingNullCond->mCheckBB = mModule->mBfIRBuilder->CreateBlock("nullCond.check");
  15408. mModule->AddBasicBlock(pendingNullCond->mCheckBB);
  15409. }
  15410. BfIRValue isNotNull;
  15411. if (thisValue.mType->IsNullable())
  15412. {
  15413. BfTypeInstance* nullableType = (BfTypeInstance*)thisValue.mType->ToTypeInstance();
  15414. auto elementType = nullableType->GetUnderlyingType();
  15415. if (elementType->IsValuelessType())
  15416. {
  15417. thisValue = mModule->MakeAddressable(thisValue);
  15418. BfIRValue hasValuePtr = mModule->mBfIRBuilder->CreateInBoundsGEP(thisValue.mValue, 0, 1); // mHasValue
  15419. isNotNull = mModule->mBfIRBuilder->CreateLoad(hasValuePtr);
  15420. thisValue = BfTypedValue(mModule->mBfIRBuilder->GetFakeVal(), elementType, true);
  15421. }
  15422. else
  15423. {
  15424. thisValue = mModule->MakeAddressable(thisValue);
  15425. BfIRValue hasValuePtr = mModule->mBfIRBuilder->CreateInBoundsGEP(thisValue.mValue, 0, 2); // mHasValue
  15426. isNotNull = mModule->mBfIRBuilder->CreateLoad(hasValuePtr);
  15427. BfIRValue valuePtr = mModule->mBfIRBuilder->CreateInBoundsGEP(thisValue.mValue, 0, 1); // mValue
  15428. thisValue = BfTypedValue(valuePtr, elementType, true);
  15429. }
  15430. }
  15431. else
  15432. isNotNull = mModule->mBfIRBuilder->CreateIsNotNull(thisValue.mValue);
  15433. BfIRBlock notNullBB = mModule->mBfIRBuilder->CreateBlock("nullCond.notNull");
  15434. pendingNullCond->mNotNullBBs.Add(notNullBB);
  15435. mModule->mBfIRBuilder->CreateCondBr(isNotNull, notNullBB, pendingNullCond->mDoneBB);
  15436. mModule->AddBasicBlock(notNullBB);
  15437. return thisValue;
  15438. }
  15439. void BfExprEvaluator::CheckDotToken(BfTokenNode* tokenNode)
  15440. {
  15441. if ((tokenNode != NULL) && (tokenNode->mToken == BfToken_DotDot))
  15442. mModule->Fail("Unexpected cascade operation. Chaining can only be used for method invocations", tokenNode);
  15443. }
  15444. void BfExprEvaluator::DoMemberReference(BfMemberReferenceExpression* memberRefExpr, BfTypedValue* outCascadeValue)
  15445. {
  15446. CheckDotToken(memberRefExpr->mDotToken);
  15447. BfAttributeState attributeState;
  15448. attributeState.mTarget = (BfAttributeTargets)(BfAttributeTargets_MemberAccess);
  15449. String findName;
  15450. BfAstNode* nameRefNode = memberRefExpr->mMemberName;
  15451. if (auto attrIdentifierExpr = BfNodeDynCast<BfAttributedIdentifierNode>(memberRefExpr->mMemberName))
  15452. {
  15453. nameRefNode = attrIdentifierExpr->mIdentifier;
  15454. // Don't validate
  15455. attributeState.mCustomAttributes = mModule->GetCustomAttributes(attrIdentifierExpr->mAttributes, BfAttributeTargets_SkipValidate);
  15456. if (nameRefNode != NULL)
  15457. findName = attrIdentifierExpr->mIdentifier->ToString();
  15458. }
  15459. else if (memberRefExpr->mMemberName != NULL)
  15460. findName = memberRefExpr->mMemberName->ToString();
  15461. defer
  15462. (
  15463. if (attributeState.mCustomAttributes != NULL)
  15464. {
  15465. if (mPropDef != NULL)
  15466. attributeState.mTarget = (BfAttributeTargets)(attributeState.mTarget | BfAttributeTargets_Invocation);
  15467. mModule->ValidateCustomAttributes(attributeState.mCustomAttributes, attributeState.mTarget);
  15468. }
  15469. );
  15470. SetAndRestoreValue<BfAttributeState*> prevAttributeState(mModule->mAttributeState, &attributeState);
  15471. BfTypeInstance* expectingTypeInst = NULL;
  15472. if (mExpectingType != NULL)
  15473. {
  15474. expectingTypeInst = mExpectingType->ToTypeInstance();
  15475. if (mExpectingType->IsPointer())
  15476. expectingTypeInst = mExpectingType->GetUnderlyingType()->ToTypeInstance();
  15477. else if (mExpectingType->IsNullable())
  15478. expectingTypeInst = mExpectingType->GetUnderlyingType()->ToTypeInstance();
  15479. else if (mExpectingType->IsConstExprValue())
  15480. expectingTypeInst = mExpectingType->GetUnderlyingType()->ToTypeInstance();
  15481. else if (mExpectingType->IsGenericParam())
  15482. {
  15483. auto genericParam = mModule->GetGenericParamInstance((BfGenericParamType*)mExpectingType);
  15484. if (genericParam->mTypeConstraint != NULL)
  15485. expectingTypeInst = genericParam->mTypeConstraint->ToTypeInstance();
  15486. }
  15487. }
  15488. BfAutoComplete* autoComplete = GetAutoComplete();
  15489. if (autoComplete != NULL)
  15490. {
  15491. SetAndRestoreValue<bool> prevFriendSet(autoComplete->mHasFriendSet, (attributeState.mCustomAttributes != NULL) && (attributeState.mCustomAttributes->Contains(mModule->mCompiler->mFriendAttributeTypeDef)));
  15492. if (memberRefExpr->mTarget == NULL)
  15493. {
  15494. String filter;
  15495. if ((mExpectingType != NULL) &&
  15496. (autoComplete->InitAutocomplete(memberRefExpr->mDotToken, memberRefExpr->mMemberName, filter)))
  15497. {
  15498. if (expectingTypeInst != NULL)
  15499. {
  15500. bool allowPrivate = expectingTypeInst == mModule->mCurTypeInstance;
  15501. if (expectingTypeInst->IsEnum())
  15502. autoComplete->AddEnumTypeMembers(expectingTypeInst, filter, false, allowPrivate);
  15503. autoComplete->AddSelfResultTypeMembers(expectingTypeInst, expectingTypeInst, filter, allowPrivate);
  15504. }
  15505. }
  15506. }
  15507. else
  15508. {
  15509. autoComplete->CheckMemberReference(memberRefExpr->mTarget, memberRefExpr->mDotToken, memberRefExpr->mMemberName, false, mExpectingType);
  15510. if (auto objCreateExpr = BfNodeDynCast<BfObjectCreateExpression>(memberRefExpr->mTarget))
  15511. {
  15512. // This handles a weird case where we have "obj a = new\nWhatever().Thing = 123;".
  15513. // That gets parsed as "Whatever()" being the type we want to create, and then referencing
  15514. // the "Thing" member of that new object.
  15515. //if (objCreateExpr->mArraySizeSpecifier == NULL)
  15516. CheckObjectCreateTypeRef(mExpectingType, objCreateExpr->mNewNode);
  15517. }
  15518. }
  15519. }
  15520. if (memberRefExpr->mTarget == NULL)
  15521. {
  15522. if (mExpectingType == NULL)
  15523. {
  15524. mModule->Fail("Unqualified dot syntax can only be used when the result type can be inferred", nameRefNode);
  15525. return;
  15526. }
  15527. if (expectingTypeInst == NULL)
  15528. {
  15529. mModule->Fail(StrFormat("Unqualified dot syntax cannot be used with type '%s'", mModule->TypeToString(mExpectingType).c_str()), nameRefNode);
  15530. return;
  15531. }
  15532. if (mExpectingType->IsVar())
  15533. {
  15534. mResult = mModule->GetDefaultTypedValue(mExpectingType);
  15535. return;
  15536. }
  15537. BfTypedValue expectingVal(expectingTypeInst);
  15538. mResult = LookupField(memberRefExpr->mMemberName, expectingVal, findName);
  15539. if ((mResult) || (mPropDef != NULL))
  15540. return;
  15541. }
  15542. bool isNullCondLookup = (memberRefExpr->mDotToken != NULL) && (memberRefExpr->mDotToken->GetToken() == BfToken_QuestionDot);
  15543. bool isCascade = ((memberRefExpr->mDotToken != NULL) && (memberRefExpr->mDotToken->GetToken() == BfToken_DotDot));
  15544. BfIdentifierNode* nameLeft = BfNodeDynCast<BfIdentifierNode>(memberRefExpr->mTarget);
  15545. BfIdentifierNode* nameRight = BfIdentifierCast(memberRefExpr->mMemberName);
  15546. if ((nameLeft != NULL) && (nameRight != NULL) && (!isNullCondLookup) && (!isCascade))
  15547. {
  15548. bool hadError = false;
  15549. LookupQualifiedName(memberRefExpr, nameLeft, nameRight, true, &hadError);
  15550. if ((mResult) || (mPropDef != NULL))
  15551. return;
  15552. if (hadError)
  15553. return;
  15554. LookupQualifiedStaticField(memberRefExpr, nameLeft, nameRight, false);
  15555. return;
  15556. }
  15557. BfTypedValue thisValue;
  15558. if (auto exprTarget = BfNodeDynCast<BfExpression>(memberRefExpr->mTarget))
  15559. {
  15560. if (auto typeOfExpr = BfNodeDynCast<BfTypeOfExpression>(memberRefExpr->mTarget))
  15561. {
  15562. if (auto nameIdentifer = BfNodeDynCast<BfIdentifierNode>(memberRefExpr->mMemberName))
  15563. {
  15564. if (LookupTypeProp(typeOfExpr, nameIdentifer))
  15565. return;
  15566. }
  15567. }
  15568. //Hm, not using VisitChild broke our ability to write to a field for a not-initialized local struct
  15569. VisitChild(memberRefExpr->mTarget);
  15570. GetResult();
  15571. thisValue = mResult;
  15572. if (!thisValue)
  15573. {
  15574. if (auto targetIdentifier = BfNodeDynCast<BfIdentifierNode>(exprTarget))
  15575. {
  15576. thisValue = BfTypedValue(mModule->ResolveTypeRef(targetIdentifier, NULL, BfPopulateType_Declaration));
  15577. }
  15578. }
  15579. if (!thisValue.HasType())
  15580. return;
  15581. //thisValue = mResult;
  15582. }
  15583. else if (auto typeRef = BfNodeDynCast<BfTypeReference>(memberRefExpr->mTarget))
  15584. {
  15585. // Look up static field
  15586. thisValue = BfTypedValue(ResolveTypeRef(typeRef));
  15587. }
  15588. if (nameRefNode == NULL)
  15589. {
  15590. mModule->AssertErrorState();
  15591. return;
  15592. }
  15593. if (isNullCondLookup)
  15594. thisValue = SetupNullConditional(thisValue, memberRefExpr->mDotToken);
  15595. mResult = LookupField(nameRefNode, thisValue, findName);
  15596. if ((!mResult) && (mPropDef == NULL))
  15597. {
  15598. if (thisValue.mType != NULL)
  15599. {
  15600. BfTypeInstance* typeInst = thisValue.mType->ToTypeInstance();
  15601. auto compiler = mModule->mCompiler;
  15602. if ((typeInst != NULL) && (compiler->IsAutocomplete()) && (compiler->mResolvePassData->mAutoComplete->CheckFixit(memberRefExpr->mMemberName)))
  15603. {
  15604. FixitAddMember(typeInst, mExpectingType, findName, !thisValue.mValue);
  15605. }
  15606. }
  15607. if ((!thisValue.mValue) && (thisValue.mType != NULL))
  15608. {
  15609. if (auto targetIdentifier = BfNodeDynCast<BfIdentifierNode>(memberRefExpr->mMemberName))
  15610. {
  15611. mResult.mType = mModule->ResolveInnerType(thisValue.mType, targetIdentifier, BfPopulateType_Declaration);
  15612. }
  15613. }
  15614. if ((memberRefExpr->mTarget == NULL) && (expectingTypeInst != NULL) && (autoComplete != NULL))
  15615. {
  15616. if (autoComplete->CheckFixit(memberRefExpr->mMemberName))
  15617. {
  15618. autoComplete->FixitAddCase(expectingTypeInst, memberRefExpr->mMemberName->ToString(), BfTypeVector());
  15619. }
  15620. }
  15621. if (mResult.mType == NULL)
  15622. mModule->Fail("Unable to find member", nameRefNode);
  15623. }
  15624. if ((isNullCondLookup) && (mPropDef == NULL))
  15625. mResult = GetResult();
  15626. if (isCascade)
  15627. {
  15628. if (outCascadeValue != NULL)
  15629. *outCascadeValue = thisValue;
  15630. else
  15631. mModule->Fail("Unexpected cascade operation. Chaining can only be used for method invocations", memberRefExpr->mDotToken);
  15632. }
  15633. }
  15634. void BfExprEvaluator::Visit(BfMemberReferenceExpression* memberRefExpr)
  15635. {
  15636. DoMemberReference(memberRefExpr, NULL);
  15637. }
  15638. void BfExprEvaluator::Visit(BfIndexerExpression* indexerExpr)
  15639. {
  15640. BfTypedValue target;
  15641. bool wantStatic = false;
  15642. // Try first as a non-static indexer, then as a static indexer
  15643. for (int pass = 0; pass < 2; pass++)
  15644. {
  15645. ///
  15646. {
  15647. SetAndRestoreValue<BfEvalExprFlags> prevFlags(mBfEvalExprFlags, (BfEvalExprFlags)(mBfEvalExprFlags | BfEvalExprFlags_NoLookupError), pass == 0);
  15648. VisitChild(indexerExpr->mTarget);
  15649. }
  15650. ResolveGenericType();
  15651. target = GetResult(true);
  15652. if (target)
  15653. break;
  15654. if (pass == 0)
  15655. {
  15656. SetAndRestoreValue<bool> prevIgnoreErrors(mModule->mIgnoreErrors, (mModule->mIgnoreErrors) || (pass == 0));
  15657. auto staticType = mModule->ResolveTypeRef(indexerExpr->mTarget, {});
  15658. if (staticType != NULL)
  15659. {
  15660. wantStatic = true;
  15661. target.mType = staticType;
  15662. break;
  15663. }
  15664. }
  15665. }
  15666. if (!target.HasType())
  15667. return;
  15668. BfCheckedKind checkedKind = BfCheckedKind_NotSet;
  15669. bool isInlined = false;
  15670. if ((mModule->mAttributeState != NULL) && (mModule->mAttributeState->mCustomAttributes != NULL))
  15671. {
  15672. if (mModule->mAttributeState->mCustomAttributes->Contains(mModule->mCompiler->mInlineAttributeTypeDef))
  15673. {
  15674. isInlined = true;
  15675. mModule->mAttributeState->mUsed = true;
  15676. }
  15677. if (mModule->mAttributeState->mCustomAttributes->Contains(mModule->mCompiler->mCheckedAttributeTypeDef))
  15678. {
  15679. checkedKind = BfCheckedKind_Checked;
  15680. mModule->mAttributeState->mUsed = true;
  15681. }
  15682. if (mModule->mAttributeState->mCustomAttributes->Contains(mModule->mCompiler->mUncheckedAttributeTypeDef))
  15683. {
  15684. checkedKind = BfCheckedKind_Unchecked;
  15685. mModule->mAttributeState->mUsed = true;
  15686. }
  15687. }
  15688. bool isNullCondLookup = (indexerExpr->mOpenBracket != NULL) && (indexerExpr->mOpenBracket->GetToken() == BfToken_QuestionLBracket);
  15689. if (isNullCondLookup)
  15690. target = SetupNullConditional(target, indexerExpr->mOpenBracket);
  15691. if (target.mType->IsVar())
  15692. {
  15693. mResult = BfTypedValue(mModule->GetDefaultValue(target.mType), target.mType, true);
  15694. return;
  15695. }
  15696. if (target.mType->IsTypeInstance())
  15697. {
  15698. mIndexerValues.clear();
  15699. SizedArray<BfExpression*, 2> argExprs;
  15700. BfSizedArray<BfExpression*> sizedArgExprs(indexerExpr->mArguments);
  15701. BfResolvedArgs argValues(&sizedArgExprs);
  15702. ResolveArgValues(argValues, BfResolveArgFlag_DeferParamEval);
  15703. //exprEvaluator.MatchMethod(elementExpr, NULL, initValue, false, false, "Add", argValues, NULL);
  15704. mIndexerValues = argValues.mResolvedArgs;
  15705. for (auto& val : mIndexerValues)
  15706. if (!val.mTypedValue)
  15707. val.mTypedValue = mModule->GetDefaultTypedValue(mModule->mContext->mBfObjectType);
  15708. BfMethodMatcher methodMatcher(indexerExpr->mTarget, mModule, "[]", mIndexerValues, NULL);
  15709. methodMatcher.mCheckedKind = checkedKind;
  15710. //methodMatcher.CheckType(target.mType->ToTypeInstance(), target, false);
  15711. BfMethodDef* methodDef = NULL;
  15712. auto startCheckTypeInst = target.mType->ToTypeInstance();
  15713. for (int pass = 0; pass < 2; pass++)
  15714. {
  15715. bool isFailurePass = pass == 1;
  15716. auto curCheckType = startCheckTypeInst;
  15717. while (curCheckType != NULL)
  15718. {
  15719. BfProtectionCheckFlags protectionCheckFlags = BfProtectionCheckFlag_None;
  15720. BfPropertyDef* foundProp = NULL;
  15721. BfTypeInstance* foundPropTypeInst = NULL;
  15722. int matchedIndexCount = 0;
  15723. curCheckType->mTypeDef->PopulateMemberSets();
  15724. BfMemberSetEntry* entry;
  15725. BfPropertyDef* matchedProp = NULL;
  15726. BfPropertyDef* nextProp = NULL;
  15727. if (curCheckType->mTypeDef->mPropertySet.TryGetWith(String("[]"), &entry))
  15728. nextProp = (BfPropertyDef*)entry->mMemberDef;
  15729. while (nextProp != NULL)
  15730. {
  15731. auto prop = nextProp;
  15732. nextProp = nextProp->mNextWithSameName;
  15733. //TODO: Match against setMethod (minus last param) if we have no 'get' method
  15734. for (auto checkMethod : prop->mMethods)
  15735. {
  15736. if (checkMethod->mMethodType != BfMethodType_PropertyGetter)
  15737. continue;
  15738. // For generic params - check interface constraints for an indexer, call that method
  15739. BF_ASSERT(!target.mType->IsGenericParam());
  15740. if (checkMethod->mIsStatic != wantStatic)
  15741. continue;
  15742. if (checkMethod->mExplicitInterface != NULL)
  15743. continue;
  15744. auto autoComplete = GetAutoComplete();
  15745. bool wasCapturingMethodMatchInfo = false;
  15746. if (autoComplete != NULL)
  15747. {
  15748. // Set to false to make sure we don't capture method match info from 'params' array creation
  15749. wasCapturingMethodMatchInfo = autoComplete->mIsCapturingMethodMatchInfo;
  15750. autoComplete->mIsCapturingMethodMatchInfo = false;
  15751. }
  15752. defer
  15753. (
  15754. if (autoComplete != NULL)
  15755. autoComplete->mIsCapturingMethodMatchInfo = wasCapturingMethodMatchInfo;
  15756. );
  15757. if ((!isFailurePass) && (!methodMatcher.WantsCheckMethod(protectionCheckFlags, startCheckTypeInst, curCheckType, checkMethod)))
  15758. continue;
  15759. if (!methodMatcher.IsMemberAccessible(curCheckType, checkMethod->mDeclaringType))
  15760. continue;
  15761. methodMatcher.mCheckedKind = checkedKind;
  15762. methodMatcher.mTarget = target;
  15763. methodMatcher.CheckMethod(startCheckTypeInst, curCheckType, checkMethod, false);
  15764. if ((methodMatcher.mBestMethodDef == checkMethod) ||
  15765. ((foundProp == NULL) && (methodMatcher.mBackupMethodDef == checkMethod)))
  15766. {
  15767. foundPropTypeInst = curCheckType;
  15768. foundProp = prop;
  15769. matchedIndexCount = (int)checkMethod->mParams.size();
  15770. }
  15771. }
  15772. }
  15773. if (foundProp != NULL)
  15774. {
  15775. int indexDiff = matchedIndexCount - (int)mIndexerValues.size();
  15776. if (indexDiff > 0)
  15777. {
  15778. mModule->Fail(StrFormat("Expected %d more indices", indexDiff), indexerExpr->mTarget);
  15779. //mModule->mCompiler->mPassInstance->MoreInfo("See method declaration", methodInstance->mMethodDef->mMethodDeclaration);
  15780. }
  15781. else if (indexDiff < 0)
  15782. {
  15783. mModule->Fail(StrFormat("Expected %d fewer indices", -indexDiff), indexerExpr->mTarget);
  15784. }
  15785. else
  15786. {
  15787. mPropSrc = indexerExpr->mOpenBracket;
  15788. mPropDef = foundProp;
  15789. if (foundProp->mIsStatic)
  15790. {
  15791. mPropTarget = BfTypedValue(curCheckType);
  15792. }
  15793. else
  15794. {
  15795. if (target.mType != foundPropTypeInst)
  15796. mPropTarget = mModule->Cast(indexerExpr->mTarget, target, foundPropTypeInst);
  15797. else
  15798. mPropTarget = target;
  15799. }
  15800. mOrigPropTarget = mPropTarget;
  15801. if (isInlined)
  15802. mPropGetMethodFlags = (BfGetMethodInstanceFlags)(mPropGetMethodFlags | BfGetMethodInstanceFlag_ForceInline);
  15803. mPropCheckedKind = checkedKind;
  15804. }
  15805. return;
  15806. }
  15807. curCheckType = curCheckType->mBaseType;
  15808. }
  15809. }
  15810. mModule->Fail("Unable to find indexer property", indexerExpr->mTarget);
  15811. return;
  15812. }
  15813. bool wantsChecks = checkedKind == BfCheckedKind_Checked;
  15814. if (checkedKind == BfCheckedKind_NotSet)
  15815. wantsChecks = mModule->GetDefaultCheckedKind() == BfCheckedKind_Checked;
  15816. //target.mType = mModule->ResolveGenericType(target.mType);
  15817. if (target.mType->IsVar())
  15818. {
  15819. mResult = target;
  15820. return;
  15821. }
  15822. if ((!target.mType->IsPointer()) && (!target.mType->IsSizedArray()))
  15823. {
  15824. mModule->Fail("Expected pointer or array type", indexerExpr->mTarget);
  15825. return;
  15826. }
  15827. auto _GetDefaultResult = [&]()
  15828. {
  15829. return mModule->GetDefaultTypedValue(target.mType->GetUnderlyingType(), false, BfDefaultValueKind_Addr);
  15830. };
  15831. if (indexerExpr->mArguments.size() != 1)
  15832. {
  15833. mModule->Fail("Expected single index", indexerExpr->mOpenBracket);
  15834. mResult = _GetDefaultResult();
  15835. return;
  15836. }
  15837. if (indexerExpr->mArguments[0] == NULL)
  15838. {
  15839. mModule->AssertErrorState();
  15840. mResult = _GetDefaultResult();
  15841. return;
  15842. }
  15843. bool isUndefIndex = false;
  15844. auto indexArgument = mModule->CreateValueFromExpression(indexerExpr->mArguments[0]);
  15845. if (!indexArgument)
  15846. return;
  15847. if (!indexArgument.mType->IsIntegral())
  15848. {
  15849. if (indexArgument.mType->IsVar())
  15850. {
  15851. isUndefIndex = true;
  15852. indexArgument = mModule->GetDefaultTypedValue(mModule->GetPrimitiveType(BfTypeCode_IntPtr), false, BfDefaultValueKind_Undef);
  15853. }
  15854. else
  15855. {
  15856. indexArgument = mModule->Cast(indexerExpr->mArguments[0], indexArgument, mModule->GetPrimitiveType(BfTypeCode_IntPtr));
  15857. if (!indexArgument)
  15858. indexArgument = mModule->GetDefaultTypedValue(mModule->GetPrimitiveType(BfTypeCode_IntPtr));
  15859. }
  15860. }
  15861. if (indexArgument.mType->IsPrimitiveType())
  15862. {
  15863. auto primType = (BfPrimitiveType*)indexArgument.mType;
  15864. if ((!primType->IsSigned()) && (primType->mSize < 8))
  15865. {
  15866. // GEP will always do a signed upcast so we need to cast manually if we are unsigned
  15867. indexArgument = BfTypedValue(mModule->mBfIRBuilder->CreateNumericCast(indexArgument.mValue, false, BfTypeCode_IntPtr), mModule->GetPrimitiveType(BfTypeCode_IntPtr));
  15868. }
  15869. }
  15870. mModule->PopulateType(target.mType);
  15871. if (target.mType->IsSizedArray())
  15872. {
  15873. BfSizedArrayType* sizedArrayType = (BfSizedArrayType*)target.mType;
  15874. auto underlyingType = sizedArrayType->mElementType;
  15875. if (indexArgument.mValue.IsConst())
  15876. {
  15877. auto indexConst = mModule->mBfIRBuilder->GetConstant(indexArgument.mValue);
  15878. if (indexConst->mUInt64 >= (uint64)sizedArrayType->mElementCount)
  15879. {
  15880. if (!mModule->IsInSpecializedSection())
  15881. {
  15882. mModule->Fail(StrFormat("Index '%d' is out of bounds for type '%s'", indexConst->mInt32, mModule->TypeToString(target.mType).c_str()), indexerExpr->mArguments[0]);
  15883. mResult = _GetDefaultResult();
  15884. return;
  15885. }
  15886. else
  15887. {
  15888. // Is this any good?
  15889. mModule->mBfIRBuilder->CreateUnreachable();
  15890. }
  15891. }
  15892. }
  15893. else if (((mModule->HasCompiledOutput()) || (mModule->mIsConstModule)) &&
  15894. (wantsChecks))
  15895. {
  15896. if (checkedKind == BfCheckedKind_NotSet)
  15897. checkedKind = mModule->GetDefaultCheckedKind();
  15898. if (checkedKind == BfCheckedKind_Checked)
  15899. {
  15900. auto oobBlock = mModule->mBfIRBuilder->CreateBlock("oob", true);
  15901. auto contBlock = mModule->mBfIRBuilder->CreateBlock("cont", true);
  15902. auto indexType = (BfPrimitiveType*)indexArgument.mType;
  15903. if (!mModule->mSystem->DoesLiteralFit(indexType->mTypeDef->mTypeCode, sizedArrayType->mElementCount))
  15904. {
  15905. // We need to upsize the index so we can compare it against the larger elementCount
  15906. indexType = mModule->GetPrimitiveType(BfTypeCode_IntPtr);
  15907. indexArgument = mModule->Cast(indexerExpr->mArguments[0], indexArgument, indexType);
  15908. }
  15909. auto cmpRes = mModule->mBfIRBuilder->CreateCmpGTE(indexArgument.mValue, mModule->mBfIRBuilder->CreateConst(indexType->mTypeDef->mTypeCode, (uint64)sizedArrayType->mElementCount), false);
  15910. mModule->mBfIRBuilder->CreateCondBr(cmpRes, oobBlock, contBlock);
  15911. mModule->mBfIRBuilder->SetInsertPoint(oobBlock);
  15912. auto internalType = mModule->ResolveTypeDef(mModule->mCompiler->mInternalTypeDef);
  15913. auto oobFunc = mModule->GetMethodByName(internalType->ToTypeInstance(), "ThrowIndexOutOfRange");
  15914. if (oobFunc.mFunc)
  15915. {
  15916. /*if (!mModule->mCompiler->mIsResolveOnly)
  15917. {
  15918. OutputDebugStrF("-OOB %d %d\n", oobFunc.mFunc.mId, oobFunc.mFunc.mFlags);
  15919. }*/
  15920. if (mModule->mIsConstModule)
  15921. mModule->mCompiler->mCEMachine->QueueMethod(oobFunc.mMethodInstance, oobFunc.mFunc);
  15922. SizedArray<BfIRValue, 1> args;
  15923. args.push_back(mModule->GetConstValue(0));
  15924. mModule->mBfIRBuilder->CreateCall(oobFunc.mFunc, args);
  15925. mModule->mBfIRBuilder->CreateUnreachable();
  15926. mModule->mBfIRBuilder->SetInsertPoint(contBlock);
  15927. }
  15928. else
  15929. {
  15930. mModule->Fail("System.Internal class must contain method 'ThrowIndexOutOfRange'");
  15931. }
  15932. }
  15933. }
  15934. // If this is a 'bag of bytes', we should try hard not to have to make this addressable
  15935. if ((!target.IsAddr()) && (!target.mType->IsSizeAligned()))
  15936. mModule->MakeAddressable(target);
  15937. mModule->PopulateType(underlyingType);
  15938. if ((sizedArrayType->IsUnknownSizedArray()) || (isUndefIndex))
  15939. {
  15940. mResult = mModule->GetDefaultTypedValue(underlyingType, false, BfDefaultValueKind_Addr);
  15941. }
  15942. else if (sizedArrayType->IsValuelessType())
  15943. {
  15944. if (underlyingType->IsValuelessType())
  15945. mResult = BfTypedValue(mModule->mBfIRBuilder->GetFakeVal(), underlyingType, true);
  15946. else
  15947. {
  15948. mResult = mModule->GetDefaultTypedValue(underlyingType);
  15949. if (sizedArrayType->mElementCount != 0)
  15950. mModule->AssertErrorState();
  15951. }
  15952. }
  15953. else if (target.IsAddr())
  15954. {
  15955. if (target.mType->IsSizeAligned())
  15956. {
  15957. auto gepResult = mModule->mBfIRBuilder->CreateInBoundsGEP(target.mValue, mModule->GetConstValue(0), indexArgument.mValue);
  15958. mResult = BfTypedValue(gepResult, underlyingType, target.IsReadOnly() ? BfTypedValueKind_ReadOnlyAddr : BfTypedValueKind_Addr);
  15959. }
  15960. else
  15961. {
  15962. auto indexResult = mModule->CreateIndexedValue(underlyingType, target.mValue, indexArgument.mValue);
  15963. mResult = BfTypedValue(indexResult, underlyingType, target.IsReadOnly() ? BfTypedValueKind_ReadOnlyAddr : BfTypedValueKind_Addr);
  15964. }
  15965. }
  15966. else
  15967. {
  15968. if ((!target.mValue.IsConst()) && (!indexArgument.mValue.IsConst()))
  15969. {
  15970. mModule->Fail("Unable to index value", indexerExpr->mTarget);
  15971. return;
  15972. }
  15973. mModule->mBfIRBuilder->PopulateType(target.mType);
  15974. auto gepResult = mModule->mBfIRBuilder->CreateExtractValue(target.mValue, indexArgument.mValue);
  15975. if ((underlyingType->IsString()) || (underlyingType->IsPointer()))
  15976. {
  15977. auto resultConst = mModule->mBfIRBuilder->GetConstant(gepResult);
  15978. if ((resultConst != NULL) && (resultConst->mTypeCode == BfTypeCode_Int32))
  15979. {
  15980. int strId = resultConst->mInt32;
  15981. const StringImpl& str = mModule->mContext->mStringObjectIdMap[strId].mString;
  15982. if (underlyingType->IsString())
  15983. gepResult = mModule->GetStringObjectValue(str, false);
  15984. else
  15985. gepResult = mModule->GetStringCharPtr(strId);
  15986. }
  15987. }
  15988. mResult = BfTypedValue(gepResult, underlyingType, BfTypedValueKind_Value);
  15989. }
  15990. }
  15991. else
  15992. {
  15993. target = mModule->LoadValue(target);
  15994. BfPointerType* pointerType = (BfPointerType*)target.mType;
  15995. auto underlyingType = pointerType->mElementType;
  15996. mModule->mBfIRBuilder->PopulateType(underlyingType);
  15997. if (isUndefIndex)
  15998. {
  15999. mResult = mModule->GetDefaultTypedValue(underlyingType, false, BfDefaultValueKind_Addr);
  16000. }
  16001. else
  16002. {
  16003. BfIRValue result = mModule->CreateIndexedValue(underlyingType, target.mValue, indexArgument.mValue);
  16004. mResult = BfTypedValue(result, underlyingType, true);
  16005. }
  16006. }
  16007. }
  16008. void BfExprEvaluator::Visit(BfUnaryOperatorExpression* unaryOpExpr)
  16009. {
  16010. BfAutoParentNodeEntry autoParentNodeEntry(mModule, unaryOpExpr);
  16011. PerformUnaryOperation(unaryOpExpr->mExpression, unaryOpExpr->mOp, unaryOpExpr->mOpToken, BfUnaryOpFlag_None);
  16012. }
  16013. void BfExprEvaluator::PerformUnaryOperation(BfExpression* unaryOpExpr, BfUnaryOp unaryOp, BfTokenNode* opToken, BfUnaryOpFlags opFlags)
  16014. {
  16015. {
  16016. // If this is a cast, we don't want the value to be coerced before the unary operator is applied.
  16017. // WAIT: Why not?
  16018. //SetAndRestoreValue<BfType*> prevExpectingType(mExpectingType, NULL);
  16019. BfType* prevExpedcting = mExpectingType;
  16020. switch (unaryOp)
  16021. {
  16022. case BfUnaryOp_Negate:
  16023. case BfUnaryOp_Positive:
  16024. case BfUnaryOp_InvertBits:
  16025. // If we're expecting an int64 or uint64 then just leave the type as unknown
  16026. if ((mExpectingType != NULL) && (mExpectingType->IsInteger()) && (mExpectingType->mSize == 8))
  16027. mExpectingType = NULL;
  16028. // Otherwise keep expecting type
  16029. break;
  16030. default:
  16031. mExpectingType = NULL;
  16032. }
  16033. VisitChild(unaryOpExpr);
  16034. mExpectingType = prevExpedcting;
  16035. }
  16036. BfExprEvaluator::PerformUnaryOperation_OnResult(unaryOpExpr, unaryOp, opToken, opFlags);
  16037. }
  16038. BfTypedValue BfExprEvaluator::PerformUnaryOperation_TryOperator(const BfTypedValue& inValue, BfExpression* unaryOpExpr, BfUnaryOp unaryOp, BfTokenNode* opToken, BfUnaryOpFlags opFlags)
  16039. {
  16040. if ((!inValue.mType->IsTypeInstance()) && (!inValue.mType->IsGenericParam()))
  16041. return BfTypedValue();
  16042. SizedArray<BfResolvedArg, 1> args;
  16043. BfResolvedArg resolvedArg;
  16044. resolvedArg.mTypedValue = inValue;
  16045. args.push_back(resolvedArg);
  16046. BfMethodMatcher methodMatcher(opToken, mModule, "", args, NULL);
  16047. methodMatcher.mBfEvalExprFlags = BfEvalExprFlags_NoAutoComplete;
  16048. BfBaseClassWalker baseClassWalker(inValue.mType, NULL, mModule);
  16049. BfUnaryOp findOp = unaryOp;
  16050. bool isPostOp = false;
  16051. if (findOp == BfUnaryOp_PostIncrement)
  16052. {
  16053. findOp = BfUnaryOp_Increment;
  16054. isPostOp = true;
  16055. }
  16056. if (findOp == BfUnaryOp_PostDecrement)
  16057. {
  16058. findOp = BfUnaryOp_Decrement;
  16059. isPostOp = true;
  16060. }
  16061. bool isConstraintCheck = ((opFlags & BfUnaryOpFlag_IsConstraintCheck) != 0);
  16062. BfType* operatorConstraintReturnType = NULL;
  16063. BfType* bestSelfType = NULL;
  16064. while (true)
  16065. {
  16066. auto entry = baseClassWalker.Next();
  16067. auto checkType = entry.mTypeInstance;
  16068. if (checkType == NULL)
  16069. break;
  16070. for (auto operatorDef : checkType->mTypeDef->mOperators)
  16071. {
  16072. if (operatorDef->mOperatorDeclaration->mUnaryOp == findOp)
  16073. {
  16074. if (!methodMatcher.IsMemberAccessible(checkType, operatorDef->mDeclaringType))
  16075. continue;
  16076. int prevArgSize = (int)args.mSize;
  16077. if (!operatorDef->mIsStatic)
  16078. {
  16079. // Try without arg
  16080. args.mSize = 0;
  16081. }
  16082. if (isConstraintCheck)
  16083. {
  16084. auto returnType = mModule->CheckOperator(checkType, operatorDef, inValue, BfTypedValue());
  16085. if (returnType != NULL)
  16086. {
  16087. operatorConstraintReturnType = returnType;
  16088. methodMatcher.mBestMethodDef = operatorDef;
  16089. }
  16090. }
  16091. else
  16092. {
  16093. if (methodMatcher.CheckMethod(NULL, checkType, operatorDef, false))
  16094. methodMatcher.mSelfType = entry.mSrcType;
  16095. }
  16096. args.mSize = prevArgSize;
  16097. }
  16098. }
  16099. }
  16100. if (methodMatcher.mBestMethodDef == NULL)
  16101. {
  16102. // Check method generic constraints
  16103. if ((mModule->mCurMethodInstance != NULL) && (mModule->mCurMethodInstance->mIsUnspecialized) && (mModule->mCurMethodInstance->mMethodInfoEx != NULL))
  16104. {
  16105. for (int genericParamIdx = 0; genericParamIdx < mModule->mCurMethodInstance->mMethodInfoEx->mGenericParams.size(); genericParamIdx++)
  16106. {
  16107. auto genericParam = mModule->mCurMethodInstance->mMethodInfoEx->mGenericParams[genericParamIdx];
  16108. for (auto& opConstraint : genericParam->mOperatorConstraints)
  16109. {
  16110. if (opConstraint.mUnaryOp == findOp)
  16111. {
  16112. if (mModule->CanCast(args[0].mTypedValue, opConstraint.mRightType, isConstraintCheck ? BfCastFlags_IsConstraintCheck : BfCastFlags_None))
  16113. {
  16114. return BfTypedValue(mModule->mBfIRBuilder->GetFakeVal(), genericParam->mExternType);
  16115. }
  16116. }
  16117. }
  16118. }
  16119. }
  16120. // Check type generic constraints
  16121. if ((mModule->mCurTypeInstance->IsGenericTypeInstance()) && (mModule->mCurTypeInstance->IsUnspecializedType()))
  16122. {
  16123. auto genericTypeInst = (BfTypeInstance*)mModule->mCurTypeInstance;
  16124. for (int genericParamIdx = 0; genericParamIdx < genericTypeInst->mGenericTypeInfo->mGenericParams.size(); genericParamIdx++)
  16125. {
  16126. auto genericParam = mModule->GetGenericTypeParamInstance(genericParamIdx);
  16127. for (auto& opConstraint : genericParam->mOperatorConstraints)
  16128. {
  16129. if (opConstraint.mUnaryOp == findOp)
  16130. {
  16131. if (mModule->CanCast(args[0].mTypedValue, opConstraint.mRightType, isConstraintCheck ? BfCastFlags_IsConstraintCheck : BfCastFlags_None))
  16132. {
  16133. return BfTypedValue(mModule->mBfIRBuilder->GetFakeVal(), genericParam->mExternType);
  16134. }
  16135. }
  16136. }
  16137. }
  16138. }
  16139. return BfTypedValue();
  16140. }
  16141. if ((!baseClassWalker.mMayBeFromInterface) && (opToken != NULL))
  16142. mModule->SetElementType(opToken, BfSourceElementType_Method);
  16143. auto methodDef = methodMatcher.mBestMethodDef;
  16144. auto autoComplete = GetAutoComplete();
  16145. if ((autoComplete != NULL) && (autoComplete->IsAutocompleteNode(opToken)))
  16146. {
  16147. auto operatorDecl = BfNodeDynCast<BfOperatorDeclaration>(methodDef->mMethodDeclaration);
  16148. if ((operatorDecl != NULL) && (operatorDecl->mOpTypeToken != NULL))
  16149. autoComplete->SetDefinitionLocation(operatorDecl->mOpTypeToken);
  16150. }
  16151. SizedArray<BfExpression*, 2> argSrcs;
  16152. argSrcs.push_back(unaryOpExpr);
  16153. BfTypedValue targetVal = args[0].mTypedValue;
  16154. BfTypedValue postOpVal;
  16155. if (isPostOp)
  16156. postOpVal = mModule->LoadValue(targetVal);
  16157. BfTypedValue callTarget;
  16158. if (!methodMatcher.mBestMethodDef->mIsStatic)
  16159. {
  16160. callTarget = targetVal;
  16161. args.Clear();
  16162. }
  16163. BfTypedValue result;
  16164. if (isConstraintCheck)
  16165. {
  16166. result = BfTypedValue(mModule->mBfIRBuilder->GetFakeVal(), operatorConstraintReturnType);
  16167. }
  16168. else
  16169. {
  16170. SetAndRestoreValue<BfEvalExprFlags> prevFlags(mBfEvalExprFlags, (BfEvalExprFlags)(mBfEvalExprFlags | BfEvalExprFlags_NoAutoComplete));
  16171. result = CreateCall(&methodMatcher, callTarget);
  16172. }
  16173. if (!methodMatcher.mBestMethodDef->mIsStatic)
  16174. {
  16175. if (!isPostOp)
  16176. result = mModule->LoadValue(targetVal);
  16177. }
  16178. else if ((result.mType != NULL) && (methodMatcher.mSelfType != NULL) && (result.mType->IsSelf()))
  16179. {
  16180. BF_ASSERT(mModule->IsInGeneric());
  16181. result = mModule->GetDefaultTypedValue(methodMatcher.mSelfType);
  16182. }
  16183. if ((methodMatcher.mBestMethodInstance) &&
  16184. ((findOp == BfUnaryOp_Increment) || (findOp == BfUnaryOp_Decrement)))
  16185. {
  16186. if (methodMatcher.mBestMethodInstance.mMethodInstance->mIsIntrinsic)
  16187. {
  16188. if (args[0].mTypedValue.IsAddr())
  16189. mModule->mBfIRBuilder->CreateStore(result.mValue, args[0].mTypedValue.mValue);
  16190. else
  16191. {
  16192. mModule->AssertErrorState();
  16193. }
  16194. }
  16195. else
  16196. {
  16197. if (!result.mType->IsValuelessType())
  16198. {
  16199. if (targetVal.IsAddr())
  16200. {
  16201. result = mModule->LoadValue(result);
  16202. mModule->mBfIRBuilder->CreateStore(result.mValue, targetVal.mValue);
  16203. }
  16204. }
  16205. }
  16206. }
  16207. if (postOpVal)
  16208. result = postOpVal;
  16209. return result;
  16210. }
  16211. void BfExprEvaluator::PerformUnaryOperation_OnResult(BfExpression* unaryOpExpr, BfUnaryOp unaryOp, BfTokenNode* opToken, BfUnaryOpFlags opFlags)
  16212. {
  16213. BfAstNode* propSrc = mPropSrc;
  16214. BfTypedValue propTarget = mPropTarget;
  16215. BfPropertyDef* propDef = mPropDef;
  16216. SizedArray<BfResolvedArg, 2> indexerVals = mIndexerValues;
  16217. BfTypedValue writeToProp;
  16218. GetResult();
  16219. if (!mResult)
  16220. return;
  16221. if (mResult.mType->IsRef())
  16222. mResult.mType = mResult.mType->GetUnderlyingType();
  16223. if (mResult.mType->IsVar())
  16224. {
  16225. mResult = BfTypedValue(mModule->GetDefaultValue(mResult.mType), mResult.mType);
  16226. return;
  16227. }
  16228. if (BfCanOverloadOperator(unaryOp))
  16229. {
  16230. auto opResult = PerformUnaryOperation_TryOperator(mResult, unaryOpExpr, unaryOp, opToken, opFlags);
  16231. if (opResult)
  16232. {
  16233. mResult = opResult;
  16234. return;
  16235. }
  16236. }
  16237. bool numericFail = false;
  16238. switch (unaryOp)
  16239. {
  16240. case BfUnaryOp_Not:
  16241. {
  16242. CheckResultForReading(mResult);
  16243. auto boolType = mModule->GetPrimitiveType(BfTypeCode_Boolean);
  16244. auto value = mModule->LoadValue(mResult);
  16245. value = mModule->Cast(unaryOpExpr, value, boolType);
  16246. if (!value)
  16247. {
  16248. mResult = BfTypedValue();
  16249. return;
  16250. }
  16251. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateNot(value.mValue), boolType);
  16252. }
  16253. break;
  16254. case BfUnaryOp_Positive:
  16255. return;
  16256. case BfUnaryOp_Negate:
  16257. {
  16258. CheckResultForReading(mResult);
  16259. auto value = mModule->LoadValue(mResult);
  16260. if (!value)
  16261. {
  16262. mResult = BfTypedValue();
  16263. return;
  16264. }
  16265. BfType* origType = value.mType;
  16266. if (value.mType->IsTypedPrimitive())
  16267. value.mType = value.mType->GetUnderlyingType();
  16268. if (value.mType->IsIntegral())
  16269. {
  16270. auto primType = (BfPrimitiveType*)value.mType;
  16271. auto wantType = primType;
  16272. auto constant = mModule->mBfIRBuilder->GetConstant(value.mValue);
  16273. if ((constant != NULL) && (mModule->mBfIRBuilder->IsInt(constant->mTypeCode)))
  16274. {
  16275. if ((primType->mTypeDef->mTypeCode == BfTypeCode_UInt32) && (constant->mInt64 == 0x80000000LL))
  16276. {
  16277. mResult = BfTypedValue(mModule->GetConstValue32(-0x80000000LL), mModule->GetPrimitiveType(BfTypeCode_Int32));
  16278. return;
  16279. }
  16280. else if ((primType->mTypeDef->mTypeCode == BfTypeCode_UInt64) && (constant->mInt64 == 0x8000000000000000LL))
  16281. {
  16282. mResult = BfTypedValue(mModule->GetConstValue64(-0x8000000000000000LL), mModule->GetPrimitiveType(BfTypeCode_Int64));
  16283. return;
  16284. }
  16285. }
  16286. /*if (auto constantInt = dyn_cast<ConstantInt>((Value*)value.mValue))
  16287. {
  16288. int64 i64Val = constantInt->getSExtValue();
  16289. // This is a special case where the user entered -0x80000000 (maxint) but we thought "0x80000000" was a uint in the parser
  16290. // which would get upcasted to an int64 for this negate. Properly bring back down to an int32
  16291. if ((primType->mTypeDef->mTypeCode == BfTypeCode_UInt32) && (i64Val == -0x80000000LL))
  16292. {
  16293. mResult = BfTypedValue(mModule->GetConstValue((int)i64Val), mModule->GetPrimitiveType(BfTypeCode_Int32));
  16294. return;
  16295. }
  16296. }*/
  16297. if (!primType->IsSigned())
  16298. {
  16299. if (primType->mSize == 1)
  16300. wantType = mModule->GetPrimitiveType(BfTypeCode_Int16);
  16301. else if (primType->mSize == 2)
  16302. wantType = mModule->GetPrimitiveType(BfTypeCode_Int32);
  16303. else if (primType->mSize == 4)
  16304. wantType = mModule->GetPrimitiveType(BfTypeCode_Int64);
  16305. else
  16306. mModule->Fail("Operator '-' cannot be applied to uint64", opToken);
  16307. }
  16308. if (primType != wantType)
  16309. {
  16310. value = mModule->Cast(unaryOpExpr, value, wantType, BfCastFlags_Explicit);
  16311. if (!value)
  16312. {
  16313. mResult = BfTypedValue();
  16314. return;
  16315. }
  16316. }
  16317. if (origType->mSize == wantType->mSize) // Allow negative of primitive typed but not if we had to upsize
  16318. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateNeg(value.mValue), origType);
  16319. else
  16320. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateNeg(value.mValue), wantType);
  16321. }
  16322. else if (value.mType->IsFloat())
  16323. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateNeg(value.mValue), origType);
  16324. else
  16325. numericFail = true;
  16326. }
  16327. break;
  16328. case BfUnaryOp_InvertBits:
  16329. {
  16330. CheckResultForReading(mResult);
  16331. auto value = mModule->LoadValue(mResult);
  16332. if (!value)
  16333. return;
  16334. bool isInteger = value.mType->IsIntegral();
  16335. if (value.mType->IsTypedPrimitive())
  16336. isInteger = value.mType->GetUnderlyingType()->IsIntegral();
  16337. if (!isInteger)
  16338. {
  16339. mResult = BfTypedValue();
  16340. mModule->Fail("Operator can only be used on integer types", opToken);
  16341. return;
  16342. }
  16343. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateNot(value.mValue), value.mType);
  16344. }
  16345. break;
  16346. case BfUnaryOp_AddressOf:
  16347. {
  16348. MarkResultUsed();
  16349. mModule->FixIntUnknown(mResult);
  16350. mModule->PopulateType(mResult.mType);
  16351. auto ptrType = mModule->CreatePointerType(mResult.mType);
  16352. if (mResult.mType->IsValuelessType())
  16353. {
  16354. // Sentinel value
  16355. auto val = mModule->mBfIRBuilder->CreateIntToPtr(mModule->mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, 1), mModule->mBfIRBuilder->MapType(ptrType));
  16356. mResult = BfTypedValue(val, ptrType);
  16357. }
  16358. else if (!CheckModifyResult(mResult, unaryOpExpr, "take address of", false, true))
  16359. {
  16360. if (!mResult.IsAddr())
  16361. mResult = mModule->MakeAddressable(mResult);
  16362. mResult = BfTypedValue(mResult.mValue, ptrType, false);
  16363. }
  16364. else
  16365. mResult = BfTypedValue(mResult.mValue, ptrType, false);
  16366. }
  16367. break;
  16368. case BfUnaryOp_Dereference:
  16369. {
  16370. CheckResultForReading(mResult);
  16371. if (!mResult.mType->IsPointer())
  16372. {
  16373. mResult = BfTypedValue();
  16374. mModule->Fail("Cannot dereference non-pointer type", unaryOpExpr);
  16375. return;
  16376. }
  16377. if (mResult.mValue.IsConst())
  16378. {
  16379. auto constant = mModule->mBfIRBuilder->GetConstant(mResult.mValue);
  16380. bool isNull = constant->mTypeCode == BfTypeCode_NullPtr;
  16381. if (constant->mConstType == BfConstType_ExtractValue)
  16382. {
  16383. auto constExtract = (BfConstantExtractValue*)constant;
  16384. auto targetConst = mModule->mBfIRBuilder->GetConstantById(constExtract->mTarget);
  16385. if (targetConst->mConstType == BfConstType_AggZero)
  16386. isNull = true;
  16387. }
  16388. if (isNull)
  16389. {
  16390. mModule->Warn(0, "Cannot dereference a null pointer", unaryOpExpr);
  16391. mResult = mModule->GetDefaultTypedValue(mResult.mType, false, BfDefaultValueKind_Addr);
  16392. mResult = mModule->LoadValue(mResult);
  16393. }
  16394. }
  16395. auto derefTarget = mModule->LoadValue(mResult);
  16396. BfPointerType* pointerType = (BfPointerType*)derefTarget.mType;
  16397. auto resolvedType = mModule->ResolveType(pointerType->mElementType);
  16398. if (resolvedType == NULL)
  16399. {
  16400. mResult = BfTypedValue();
  16401. return;
  16402. }
  16403. mModule->PopulateType(resolvedType);
  16404. if (resolvedType->IsValuelessType())
  16405. mResult = BfTypedValue(mModule->mBfIRBuilder->GetFakeVal(), resolvedType, true);
  16406. else
  16407. mResult = BfTypedValue(derefTarget.mValue, resolvedType, true);
  16408. }
  16409. break;
  16410. case BfUnaryOp_PostIncrement:
  16411. case BfUnaryOp_Increment:
  16412. {
  16413. CheckResultForReading(mResult);
  16414. auto ptr = mResult;
  16415. //if ((propDef == NULL) && (!mModule->CheckModifyValue(ptr, opToken)))
  16416. if ((propDef == NULL) && (!CheckModifyResult(ptr, opToken, "increment")))
  16417. return;
  16418. BfTypedValue origTypedVal = mModule->LoadValue(ptr, NULL, mIsVolatileReference);
  16419. BfIRValue origVal = origTypedVal.mValue;
  16420. BfIRValue constValue = mModule->GetConstValue(1, ptr.mType);
  16421. BfIRValue resultValue;
  16422. if (ptr.mType->IsPointer())
  16423. {
  16424. BfPointerType* ptrType = (BfPointerType*)ptr.mType;
  16425. BfType* intPtrType = mModule->GetPrimitiveType(BfTypeCode_IntPtr);
  16426. constValue = mModule->GetConstValue(ptrType->mElementType->GetStride(), intPtrType);
  16427. auto i8PtrType = mModule->mBfIRBuilder->GetPointerTo(mModule->mBfIRBuilder->GetPrimitiveType(BfTypeCode_Int8));
  16428. BfIRValue origPtrValue = mModule->mBfIRBuilder->CreateBitCast(origVal, i8PtrType);
  16429. BfIRValue newPtrValue = mModule->mBfIRBuilder->CreateInBoundsGEP(origPtrValue, constValue);
  16430. resultValue = mModule->mBfIRBuilder->CreateBitCast(newPtrValue, mModule->mBfIRBuilder->MapType(ptr.mType));
  16431. }
  16432. else
  16433. {
  16434. constValue = mModule->GetConstValue(1, ptr.mType);
  16435. if (!constValue)
  16436. {
  16437. numericFail = true;
  16438. break;
  16439. }
  16440. if ((ptr.mType->IsIntegral()) || (ptr.mType->IsEnum()) || (ptr.mType->IsFloat()))
  16441. {
  16442. resultValue = mModule->mBfIRBuilder->CreateAdd(origVal, constValue/*, "inc"*/);
  16443. }
  16444. else
  16445. {
  16446. numericFail = true;
  16447. break;
  16448. }
  16449. }
  16450. if ((propDef != NULL) && (!ptr.IsAddr()))
  16451. writeToProp = BfTypedValue(resultValue, ptr.mType);
  16452. else
  16453. mModule->mBfIRBuilder->CreateStore(resultValue, ptr.mValue, mIsVolatileReference);
  16454. if (unaryOp == BfUnaryOp_PostIncrement)
  16455. mResult = BfTypedValue(origVal, ptr.mType, false);
  16456. else
  16457. mResult = BfTypedValue(resultValue, ptr.mType, false);
  16458. }
  16459. break;
  16460. case BfUnaryOp_PostDecrement:
  16461. case BfUnaryOp_Decrement:
  16462. {
  16463. CheckResultForReading(mResult);
  16464. auto ptr = mResult;
  16465. //if ((propDef == NULL) && (!mModule->CheckModifyValue(ptr, opToken)))
  16466. //return;
  16467. if ((propDef == NULL) && (!CheckModifyResult(ptr, opToken, "decrement")))
  16468. return;
  16469. BfTypedValue origTypedVal = mModule->LoadValue(ptr, NULL, mIsVolatileReference);
  16470. BfIRValue origVal = origTypedVal.mValue;
  16471. BfIRValue constValue = mModule->GetConstValue(1, ptr.mType);
  16472. BfIRValue resultValue;
  16473. if (ptr.mType->IsPointer())
  16474. {
  16475. BfPointerType* ptrType = (BfPointerType*)ptr.mType;
  16476. BfType* intPtrType = mModule->GetPrimitiveType(BfTypeCode_IntPtr);
  16477. constValue = mModule->GetConstValue(-ptrType->mElementType->GetStride(), intPtrType);
  16478. auto i8PtrType = mModule->mBfIRBuilder->GetPointerTo(mModule->mBfIRBuilder->GetPrimitiveType(BfTypeCode_Int8));
  16479. BfIRValue origPtrValue = mModule->mBfIRBuilder->CreateBitCast(origVal, i8PtrType);
  16480. BfIRValue newPtrValue = mModule->mBfIRBuilder->CreateInBoundsGEP(origPtrValue, constValue);
  16481. resultValue = mModule->mBfIRBuilder->CreateBitCast(newPtrValue, mModule->mBfIRBuilder->MapType(ptr.mType));
  16482. }
  16483. else
  16484. {
  16485. BfIRValue constValue = mModule->GetConstValue(1, ptr.mType);
  16486. if (!constValue)
  16487. {
  16488. numericFail = true;
  16489. break;
  16490. }
  16491. if ((ptr.mType->IsIntegral()) || (ptr.mType->IsEnum()))
  16492. {
  16493. resultValue = mModule->mBfIRBuilder->CreateSub(origVal, constValue);
  16494. }
  16495. else if (ptr.mType->IsFloat())
  16496. {
  16497. resultValue = mModule->mBfIRBuilder->CreateSub(origVal, constValue);
  16498. }
  16499. else
  16500. {
  16501. numericFail = true;
  16502. break;
  16503. }
  16504. }
  16505. if ((propDef != NULL) && (!ptr.IsAddr()))
  16506. writeToProp = BfTypedValue(resultValue, ptr.mType);
  16507. else
  16508. mModule->mBfIRBuilder->CreateStore(resultValue, ptr.mValue, mIsVolatileReference);
  16509. if (unaryOp == BfUnaryOp_PostDecrement)
  16510. mResult = BfTypedValue(origVal, ptr.mType, false);
  16511. else
  16512. mResult = BfTypedValue(resultValue, ptr.mType, false);
  16513. }
  16514. break;
  16515. case BfUnaryOp_Ref:
  16516. case BfUnaryOp_Mut:
  16517. {
  16518. if (mAllowReadOnlyReference)
  16519. {
  16520. if (mResult.mKind == BfTypedValueKind_ReadOnlyAddr)
  16521. mResult.mKind = BfTypedValueKind_Addr;
  16522. }
  16523. CheckResultForReading(mResult);
  16524. if ((unaryOp == BfUnaryOp_Mut) && (!mResult.mType->IsComposite()) && (!mResult.mType->IsGenericParam()))
  16525. {
  16526. // Non-composite types are already mutable, leave them alone...
  16527. break;
  16528. }
  16529. if ((unaryOp != BfUnaryOp_Mut) || (mResult.mKind != BfTypedValueKind_MutableValue))
  16530. {
  16531. if (!CheckModifyResult(mResult, unaryOpExpr, StrFormat("use '%s' on", BfGetOpName(unaryOp)).c_str()))
  16532. {
  16533. // Just leave the non-ref version in mResult
  16534. return;
  16535. }
  16536. }
  16537. if ((mBfEvalExprFlags & BfEvalExprFlags_AllowRefExpr) == 0)
  16538. {
  16539. mResult = BfTypedValue();
  16540. mModule->Fail(StrFormat("Invalid usage of '%s' expression", BfGetOpName(unaryOp)), opToken);
  16541. return;
  16542. }
  16543. ResolveGenericType();
  16544. if (mResult.mType->IsVar())
  16545. break;
  16546. mResult = BfTypedValue(mResult.mValue, mModule->CreateRefType(mResult.mType, (unaryOp == BfUnaryOp_Ref) ? BfRefType::RefKind_Ref : BfRefType::RefKind_Mut));
  16547. }
  16548. break;
  16549. case BfUnaryOp_Out:
  16550. {
  16551. if (!CheckModifyResult(mResult, unaryOpExpr, "use 'out' on"))
  16552. {
  16553. // Just leave the non-ref version in mResult
  16554. return;
  16555. }
  16556. if ((mBfEvalExprFlags & BfEvalExprFlags_AllowOutExpr) == 0)
  16557. {
  16558. mModule->Fail("Invalid usage of 'out' expression", opToken);
  16559. return;
  16560. }
  16561. if (mInsidePendingNullable)
  16562. {
  16563. // 'out' inside null conditionals never actually causes a definite assignment...
  16564. }
  16565. else
  16566. MarkResultAssigned();
  16567. MarkResultUsed();
  16568. ResolveGenericType();
  16569. if (mResult.mType->IsVar())
  16570. break;
  16571. mResult = BfTypedValue(mResult.mValue, mModule->CreateRefType(mResult.mType, BfRefType::RefKind_Out));
  16572. }
  16573. break;
  16574. case BfUnaryOp_Params:
  16575. {
  16576. bool allowParams = (mBfEvalExprFlags & BfEvalExprFlags_AllowParamsExpr) != 0;
  16577. if (allowParams)
  16578. {
  16579. if ((mResultLocalVar != NULL) && (mResultLocalVar->mCompositeCount >= 0)) // Delegate params
  16580. {
  16581. allowParams = true;
  16582. }
  16583. else
  16584. {
  16585. auto isValid = false;
  16586. auto genericTypeInst = mResult.mType->ToGenericTypeInstance();
  16587. if ((genericTypeInst != NULL) && (genericTypeInst->mTypeDef == mModule->mCompiler->mSpanTypeDef))
  16588. isValid = true;
  16589. else if (mResult.mType->IsArray())
  16590. isValid = true;
  16591. if (!isValid)
  16592. {
  16593. mModule->Fail(StrFormat("A 'params' expression cannot be used on type '%s'", mModule->TypeToString(mResult.mType).c_str()), opToken);
  16594. }
  16595. }
  16596. }
  16597. if (allowParams)
  16598. {
  16599. mResult = mModule->LoadValue(mResult);
  16600. if (mResult.IsSplat())
  16601. mResult.mKind = BfTypedValueKind_ParamsSplat;
  16602. else
  16603. mResult.mKind = BfTypedValueKind_Params;
  16604. }
  16605. else
  16606. {
  16607. mModule->Fail("Illegal use of 'params' expression", opToken);
  16608. }
  16609. }
  16610. break;
  16611. default:
  16612. mModule->Fail("INTERNAL ERROR: Unhandled unary operator", unaryOpExpr);
  16613. break;
  16614. }
  16615. if (numericFail)
  16616. {
  16617. if (opToken == NULL)
  16618. {
  16619. BF_ASSERT(mModule->mBfIRBuilder->mIgnoreWrites);
  16620. }
  16621. else if ((mResult.mType != NULL) && (mResult.mType->IsInterface()))
  16622. {
  16623. mModule->Fail(
  16624. StrFormat("Operator '%s' cannot be used on interface '%s'. Consider rewriting using generics and use this interface as a generic constraint.",
  16625. BfTokenToString(opToken->mToken), mModule->TypeToString(mResult.mType).c_str()), opToken);
  16626. }
  16627. else
  16628. {
  16629. mModule->Fail(
  16630. StrFormat("Operator '%s' cannot be used because type '%s' is neither a numeric type nor does it define an applicable operator overload",
  16631. BfTokenToString(opToken->mToken), mModule->TypeToString(mResult.mType).c_str()), opToken);
  16632. }
  16633. mResult = BfTypedValue();
  16634. }
  16635. if (writeToProp)
  16636. {
  16637. auto setMethod = GetPropertyMethodDef(propDef, BfMethodType_PropertySetter, mPropCheckedKind, mPropTarget);
  16638. if (setMethod == NULL)
  16639. {
  16640. mModule->Fail("Property has no setter", propSrc);
  16641. return;
  16642. }
  16643. auto methodInstance = GetPropertyMethodInstance(setMethod);
  16644. if (!methodInstance.mFunc)
  16645. return;
  16646. if (propSrc != NULL)
  16647. mModule->UpdateExprSrcPos(propSrc);
  16648. SizedArray<BfIRValue, 4> args;
  16649. if (!setMethod->mIsStatic)
  16650. PushThis(propSrc, propTarget, methodInstance.mMethodInstance, args);
  16651. //args.push_back(propTarget.mValue);
  16652. for (int paramIdx = 0; paramIdx < (int)indexerVals.size(); paramIdx++)
  16653. {
  16654. auto val = mModule->Cast(propSrc, indexerVals[paramIdx].mTypedValue, methodInstance.mMethodInstance->GetParamType(paramIdx));
  16655. if (!val)
  16656. return;
  16657. PushArg(val, args);
  16658. }
  16659. PushArg(writeToProp, args);
  16660. CreateCall(opToken, methodInstance.mMethodInstance, methodInstance.mFunc, false, args);
  16661. }
  16662. }
  16663. void BfExprEvaluator::PerformBinaryOperation(BfExpression* leftExpression, BfExpression* rightExpression, BfBinaryOp binaryOp, BfTokenNode* opToken, BfBinOpFlags flags, BfTypedValue leftValue)
  16664. {
  16665. BfTypedValue rightValue;
  16666. if (rightExpression == NULL)
  16667. {
  16668. mModule->AssertErrorState();
  16669. return;
  16670. }
  16671. if (!leftValue)
  16672. {
  16673. if (!rightValue)
  16674. mModule->CreateValueFromExpression(rightExpression, mExpectingType);
  16675. return;
  16676. }
  16677. if (leftValue.mType->IsRef())
  16678. leftValue.mType = leftValue.mType->GetUnderlyingType();
  16679. if ((binaryOp == BfBinaryOp_ConditionalAnd) || (binaryOp == BfBinaryOp_ConditionalOr))
  16680. {
  16681. if (mModule->mCurMethodState->mDeferredLocalAssignData != NULL)
  16682. mModule->mCurMethodState->mDeferredLocalAssignData->BreakExtendChain();
  16683. if (mModule->mCurMethodState->mCurScope->mScopeKind == BfScopeKind_StatementTarget)
  16684. mModule->mCurMethodState->mCurScope->mScopeKind = BfScopeKind_StatementTarget_Conditional;
  16685. bool isAnd = binaryOp == BfBinaryOp_ConditionalAnd;
  16686. auto boolType = mModule->GetPrimitiveType(BfTypeCode_Boolean);
  16687. leftValue = mModule->Cast(leftExpression, leftValue, boolType);
  16688. if (!leftValue)
  16689. {
  16690. mModule->CreateValueFromExpression(rightExpression);
  16691. return;
  16692. }
  16693. auto prevBB = mModule->mBfIRBuilder->GetInsertBlock();
  16694. SetAndRestoreValue<bool> prevInCondBlock(mModule->mCurMethodState->mInConditionalBlock, true);
  16695. // The RHS is not guaranteed to be executed
  16696. if ((mModule->mCurMethodState->mDeferredLocalAssignData != NULL) &&
  16697. (mModule->mCurMethodState->mDeferredLocalAssignData->mIsIfCondition))
  16698. mModule->mCurMethodState->mDeferredLocalAssignData->mIfMayBeSkipped = true;
  16699. if (isAnd)
  16700. {
  16701. bool isConstBranch = false;
  16702. bool constResult = false;
  16703. if (leftValue.mValue.IsConst())
  16704. {
  16705. auto constValue = mModule->mBfIRBuilder->GetConstant(leftValue.mValue);
  16706. if (constValue->mTypeCode == BfTypeCode_Boolean)
  16707. {
  16708. isConstBranch = true;
  16709. constResult = constValue->mBool;
  16710. }
  16711. }
  16712. if (isConstBranch)
  16713. {
  16714. if ((constResult) || (HasVariableDeclaration(rightExpression)))
  16715. {
  16716. // Only right side
  16717. rightValue = mModule->CreateValueFromExpression(rightExpression, boolType);
  16718. mResult = rightValue;
  16719. }
  16720. else
  16721. {
  16722. // Always false
  16723. SetAndRestoreValue<bool> prevIgnoreWrites(mModule->mBfIRBuilder->mIgnoreWrites, true);
  16724. rightValue = mModule->CreateValueFromExpression(rightExpression, boolType);
  16725. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConst(BfTypeCode_Boolean, 0), boolType);
  16726. }
  16727. }
  16728. else
  16729. {
  16730. auto rhsBB = mModule->mBfIRBuilder->CreateBlock("land.rhs");
  16731. auto endBB = mModule->mBfIRBuilder->CreateBlock("land.end");
  16732. // This makes any 'scope' allocs be dyn since we aren't sure if this will be short-circuited
  16733. SetAndRestoreValue<bool> prevIsConditional(mModule->mCurMethodState->mCurScope->mIsConditional, true);
  16734. mModule->mBfIRBuilder->CreateCondBr(leftValue.mValue, rhsBB, endBB);
  16735. mModule->AddBasicBlock(rhsBB);
  16736. rightValue = mModule->CreateValueFromExpression(rightExpression, boolType);
  16737. mModule->mBfIRBuilder->CreateBr(endBB);
  16738. auto endRhsBB = mModule->mBfIRBuilder->GetInsertBlock();
  16739. mModule->AddBasicBlock(endBB);
  16740. auto phi = mModule->mBfIRBuilder->CreatePhi(mModule->mBfIRBuilder->MapType(boolType), 2);
  16741. mModule->mBfIRBuilder->AddPhiIncoming(phi, mModule->GetConstValue(0, boolType), prevBB);
  16742. if (rightValue)
  16743. mModule->mBfIRBuilder->AddPhiIncoming(phi, rightValue.mValue, endRhsBB);
  16744. mResult = BfTypedValue(phi, boolType);
  16745. }
  16746. }
  16747. else
  16748. {
  16749. // Put variables in here into a 'possibly assigned' but never commit it.
  16750. // Because if we had "if ((Get(out a)) || (GetOther(out a))" then the LHS would already set it as defined, so
  16751. // the RHS is inconsequential
  16752. BfDeferredLocalAssignData deferredLocalAssignData;
  16753. deferredLocalAssignData.ExtendFrom(mModule->mCurMethodState->mDeferredLocalAssignData, false);
  16754. deferredLocalAssignData.mVarIdBarrier = mModule->mCurMethodState->GetRootMethodState()->mCurLocalVarId;
  16755. SetAndRestoreValue<BfDeferredLocalAssignData*> prevDLA(mModule->mCurMethodState->mDeferredLocalAssignData, &deferredLocalAssignData);
  16756. bool isConstBranch = false;
  16757. bool constResult = false;
  16758. if (leftValue.mValue.IsConst())
  16759. {
  16760. auto constValue = mModule->mBfIRBuilder->GetConstant(leftValue.mValue);
  16761. if (constValue->mTypeCode == BfTypeCode_Boolean)
  16762. {
  16763. isConstBranch = true;
  16764. constResult = constValue->mBool;
  16765. }
  16766. }
  16767. if (isConstBranch)
  16768. {
  16769. if ((constResult) && (!HasVariableDeclaration(rightExpression)))
  16770. {
  16771. // Always true
  16772. SetAndRestoreValue<bool> prevIgnoreWrites(mModule->mBfIRBuilder->mIgnoreWrites, true);
  16773. rightValue = mModule->CreateValueFromExpression(rightExpression, boolType);
  16774. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConst(BfTypeCode_Boolean, 1), boolType);
  16775. }
  16776. else
  16777. {
  16778. // Only right side
  16779. rightValue = mModule->CreateValueFromExpression(rightExpression, boolType);
  16780. mResult = rightValue;
  16781. }
  16782. }
  16783. else
  16784. {
  16785. auto rhsBB = mModule->mBfIRBuilder->CreateBlock("lor.rhs");
  16786. auto endBB = mModule->mBfIRBuilder->CreateBlock("lor.end");
  16787. // This makes any 'scope' allocs be dyn since we aren't sure if this will be short-circuited
  16788. SetAndRestoreValue<bool> prevIsConditional(mModule->mCurMethodState->mCurScope->mIsConditional, true);
  16789. mModule->mBfIRBuilder->CreateCondBr(leftValue.mValue, endBB, rhsBB);
  16790. mModule->AddBasicBlock(rhsBB);
  16791. rightValue = mModule->CreateValueFromExpression(rightExpression, boolType);
  16792. mModule->mBfIRBuilder->CreateBr(endBB);
  16793. auto endRhsBB = mModule->mBfIRBuilder->GetInsertBlock();
  16794. mModule->AddBasicBlock(endBB);
  16795. auto phi = mModule->mBfIRBuilder->CreatePhi(mModule->mBfIRBuilder->MapType(boolType), 2);
  16796. mModule->mBfIRBuilder->AddPhiIncoming(phi, mModule->GetConstValue(1, boolType), prevBB);
  16797. if (rightValue)
  16798. mModule->mBfIRBuilder->AddPhiIncoming(phi, rightValue.mValue, endRhsBB);
  16799. mResult = BfTypedValue(phi, boolType);
  16800. }
  16801. }
  16802. return;
  16803. }
  16804. BfType* wantType = leftValue.mType;
  16805. if ((binaryOp == BfBinaryOp_LeftShift) || (binaryOp == BfBinaryOp_RightShift))
  16806. wantType = NULL; // Don't presume
  16807. wantType = mModule->FixIntUnknown(wantType);
  16808. rightValue = mModule->CreateValueFromExpression(rightExpression, wantType, BfEvalExprFlags_NoCast);
  16809. if ((!leftValue) || (!rightValue))
  16810. return;
  16811. PerformBinaryOperation(leftExpression, rightExpression, binaryOp, opToken, flags, leftValue, rightValue);
  16812. }
  16813. void BfExprEvaluator::PerformBinaryOperation(BfExpression* leftExpression, BfExpression* rightExpression, BfBinaryOp binaryOp, BfTokenNode* opToken, BfBinOpFlags flags)
  16814. {
  16815. BfTypedValue leftValue;
  16816. if (leftExpression != NULL)
  16817. {
  16818. leftValue = mModule->CreateValueFromExpression(leftExpression, mExpectingType, (BfEvalExprFlags)(BfEvalExprFlags_NoCast | BfEvalExprFlags_AllowIntUnknown));
  16819. }
  16820. return PerformBinaryOperation(leftExpression, rightExpression, binaryOp, opToken, flags, leftValue);
  16821. }
  16822. bool BfExprEvaluator::CheckConstCompare(BfBinaryOp binaryOp, BfAstNode* opToken, const BfTypedValue& leftValue, const BfTypedValue& rightValue)
  16823. {
  16824. if ((binaryOp < BfBinaryOp_Equality) || (binaryOp > BfBinaryOp_LessThanOrEqual))
  16825. return false;
  16826. // LHS is expected to be a value and RHS is expected to be a const
  16827. if (!leftValue.mType->IsIntegral())
  16828. return false;
  16829. BF_ASSERT(rightValue.mValue.IsConst());
  16830. auto rightConst = mModule->mBfIRBuilder->GetConstant(rightValue.mValue);
  16831. if (!mModule->mBfIRBuilder->IsInt(rightConst->mTypeCode))
  16832. return false;
  16833. BfType* checkType = leftValue.mType;
  16834. if (checkType->IsTypedPrimitive())
  16835. checkType = checkType->GetUnderlyingType();
  16836. if (!checkType->IsPrimitiveType())
  16837. return false;
  16838. BfTypeCode typeCode = ((BfPrimitiveType*)checkType)->mTypeDef->mTypeCode;
  16839. int64 minValue = 0;
  16840. int64 maxValue = 0;
  16841. switch (typeCode)
  16842. {
  16843. case BfTypeCode_Int8:
  16844. minValue = -0x80;
  16845. maxValue = 0x7F;
  16846. break;
  16847. case BfTypeCode_Int16:
  16848. minValue = -0x8000;
  16849. maxValue = 0x7FFF;
  16850. break;
  16851. case BfTypeCode_Int32:
  16852. minValue = -0x80000000LL;
  16853. maxValue = 0x7FFFFFFF;
  16854. break;
  16855. case BfTypeCode_Int64:
  16856. minValue = -0x8000000000000000LL;
  16857. maxValue = 0x7FFFFFFFFFFFFFFFLL;
  16858. break;
  16859. case BfTypeCode_UInt8:
  16860. maxValue = 0xFF;
  16861. break;
  16862. case BfTypeCode_UInt16:
  16863. maxValue = 0xFFFF;
  16864. break;
  16865. case BfTypeCode_UInt32:
  16866. maxValue = 0xFFFFFFFF;
  16867. break;
  16868. default:
  16869. return false;
  16870. }
  16871. int constResult = -1;
  16872. if (typeCode == BfTypeCode_UInt64)
  16873. {
  16874. switch (binaryOp)
  16875. {
  16876. case BfBinaryOp_Equality:
  16877. case BfBinaryOp_StrictEquality:
  16878. if (rightConst->mInt64 < minValue)
  16879. constResult = 0;
  16880. break;
  16881. case BfBinaryOp_InEquality:
  16882. case BfBinaryOp_StrictInEquality:
  16883. if (rightConst->mInt64 < minValue)
  16884. constResult = 1;
  16885. break;
  16886. case BfBinaryOp_LessThan:
  16887. if (rightConst->mInt64 <= minValue)
  16888. constResult = 0;
  16889. break;
  16890. case BfBinaryOp_LessThanOrEqual:
  16891. if (rightConst->mInt64 < minValue)
  16892. constResult = 0;
  16893. break;
  16894. default: break;
  16895. }
  16896. return false;
  16897. }
  16898. else
  16899. {
  16900. switch (binaryOp)
  16901. {
  16902. case BfBinaryOp_Equality:
  16903. case BfBinaryOp_StrictEquality:
  16904. if (rightConst->mInt64 < minValue)
  16905. constResult = 0;
  16906. else if (rightConst->mInt64 > maxValue)
  16907. constResult = 0;
  16908. break;
  16909. case BfBinaryOp_InEquality:
  16910. case BfBinaryOp_StrictInEquality:
  16911. if (rightConst->mInt64 < minValue)
  16912. constResult = 1;
  16913. else if (rightConst->mInt64 > maxValue)
  16914. constResult = 1;
  16915. break;
  16916. case BfBinaryOp_LessThan:
  16917. if (rightConst->mInt64 <= minValue)
  16918. constResult = 0;
  16919. else if (rightConst->mInt64 > maxValue)
  16920. constResult = 1;
  16921. break;
  16922. case BfBinaryOp_LessThanOrEqual:
  16923. if (rightConst->mInt64 < minValue)
  16924. constResult = 0;
  16925. else if (rightConst->mInt64 >= maxValue)
  16926. constResult = 1;
  16927. break;
  16928. case BfBinaryOp_GreaterThan:
  16929. if (rightConst->mInt64 >= maxValue)
  16930. constResult = 0;
  16931. else if (rightConst->mInt64 < minValue)
  16932. constResult = 1;
  16933. break;
  16934. case BfBinaryOp_GreaterThanOrEqual:
  16935. if (rightConst->mInt64 > maxValue)
  16936. constResult = 0;
  16937. else if (rightConst->mInt64 <= minValue)
  16938. constResult = 1;
  16939. break;
  16940. default: break;
  16941. }
  16942. }
  16943. if (constResult == 0)
  16944. {
  16945. mModule->Warn(0, "The result of this operation is always 'false'", opToken);
  16946. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConst(BfTypeCode_Boolean, 1), mModule->GetPrimitiveType(BfTypeCode_Boolean));
  16947. return true;
  16948. }
  16949. else if (constResult == 1)
  16950. {
  16951. mModule->Warn(0, "The result of this operation is always 'true'", opToken);
  16952. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConst(BfTypeCode_Boolean, 1), mModule->GetPrimitiveType(BfTypeCode_Boolean));
  16953. return true;
  16954. }
  16955. return false;
  16956. }
  16957. void BfExprEvaluator::AddStrings(const BfTypedValue& leftValue, const BfTypedValue& rightValue, BfAstNode* refNode)
  16958. {
  16959. if ((leftValue.mValue.IsConst()) && (rightValue.mValue.IsConst()))
  16960. {
  16961. String* lhsStr = mModule->GetStringPoolString(leftValue.mValue, mModule->mBfIRBuilder);
  16962. String* rhsStr = mModule->GetStringPoolString(rightValue.mValue, mModule->mBfIRBuilder);
  16963. if ((lhsStr != NULL) && (rhsStr != NULL))
  16964. {
  16965. String resultStr = *lhsStr + *rhsStr;
  16966. BfVariant variant;
  16967. variant.mTypeCode = BfTypeCode_CharPtr;
  16968. variant.mString = &resultStr;
  16969. GetLiteral(refNode, variant);
  16970. return;
  16971. }
  16972. }
  16973. mModule->Fail("Strings can only be added when they are constants. Consider allocating a string and using Concat.", refNode);
  16974. return;
  16975. }
  16976. void BfExprEvaluator::PerformBinaryOperation(BfAstNode* leftExpression, BfAstNode* rightExpression, BfBinaryOp binaryOp, BfAstNode* opToken, BfBinOpFlags flags, BfTypedValue leftValue, BfTypedValue rightValue)
  16977. {
  16978. bool noClassify = (flags & BfBinOpFlag_NoClassify) != 0;
  16979. bool forceLeftType = (flags & BfBinOpFlag_ForceLeftType) != 0;
  16980. if ((rightValue.mValue.IsConst()) && (!leftValue.mValue.IsConst()))
  16981. {
  16982. if (CheckConstCompare(binaryOp, opToken, leftValue, rightValue))
  16983. return;
  16984. }
  16985. else if ((leftValue.mValue.IsConst()) && (!rightValue.mValue.IsConst()))
  16986. {
  16987. if (CheckConstCompare(BfGetOppositeBinaryOp(binaryOp), opToken, rightValue, leftValue))
  16988. return;
  16989. }
  16990. if ((binaryOp == BfBinaryOp_NullCoalesce) && ((leftValue.mType->IsPointer()) || (leftValue.mType->IsObject())))
  16991. {
  16992. auto prevBB = mModule->mBfIRBuilder->GetInsertBlock();
  16993. auto rhsBB = mModule->mBfIRBuilder->CreateBlock("nullc.rhs");
  16994. auto endBB = mModule->mBfIRBuilder->CreateBlock("nullc.end");
  16995. auto isNull = mModule->mBfIRBuilder->CreateIsNull(leftValue.mValue);
  16996. mModule->mBfIRBuilder->CreateCondBr(isNull, rhsBB, endBB);
  16997. mModule->AddBasicBlock(rhsBB);
  16998. if (!rightValue)
  16999. {
  17000. mModule->AssertErrorState();
  17001. return;
  17002. }
  17003. else
  17004. {
  17005. auto rightToLeftValue = mModule->CastToValue(rightExpression, rightValue, leftValue.mType, BfCastFlags_SilentFail);
  17006. if (rightToLeftValue)
  17007. {
  17008. rightValue = BfTypedValue(rightToLeftValue, leftValue.mType);
  17009. }
  17010. else
  17011. {
  17012. auto leftToRightValue = mModule->CastToValue(leftExpression, leftValue, rightValue.mType, BfCastFlags_SilentFail);
  17013. if (leftToRightValue)
  17014. {
  17015. leftValue = BfTypedValue(leftToRightValue, rightValue.mType);
  17016. }
  17017. else
  17018. {
  17019. // Note: Annoying trigraph split for '??'
  17020. mModule->Fail(StrFormat("Operator '?" "?' cannot be applied to operands of type '%s' and '%s'",
  17021. mModule->TypeToString(leftValue.mType).c_str(), mModule->TypeToString(rightValue.mType).c_str()), opToken);
  17022. leftValue = mModule->GetDefaultTypedValue(rightValue.mType);
  17023. }
  17024. }
  17025. }
  17026. mModule->mBfIRBuilder->CreateBr(endBB);
  17027. auto endRhsBB = mModule->mBfIRBuilder->GetInsertBlock();
  17028. mModule->AddBasicBlock(endBB);
  17029. auto phi = mModule->mBfIRBuilder->CreatePhi(mModule->mBfIRBuilder->MapType(leftValue.mType), 2);
  17030. mModule->mBfIRBuilder->AddPhiIncoming(phi, leftValue.mValue, prevBB);
  17031. mModule->mBfIRBuilder->AddPhiIncoming(phi, rightValue.mValue, endRhsBB);
  17032. mResult = BfTypedValue(phi, leftValue.mType);
  17033. return;
  17034. }
  17035. if ((binaryOp == BfBinaryOp_LeftShift) || (binaryOp == BfBinaryOp_RightShift))
  17036. {
  17037. forceLeftType = true;
  17038. }
  17039. if (rightValue.mType->IsRef())
  17040. rightValue.mType = rightValue.mType->GetUnderlyingType();
  17041. mModule->FixIntUnknown(leftValue, rightValue);
  17042. // Prefer floats, prefer chars
  17043. int leftCompareSize = leftValue.mType->mSize;
  17044. if (leftValue.mType->IsFloat())
  17045. leftCompareSize += 0x10;
  17046. if (leftValue.mType->IsChar())
  17047. leftCompareSize += 0x100;
  17048. if (!leftValue.mType->IsPrimitiveType())
  17049. leftCompareSize += 0x1000;
  17050. int rightCompareSize = rightValue.mType->mSize;
  17051. if (rightValue.mType->IsFloat())
  17052. rightCompareSize += 0x10;
  17053. if (rightValue.mType->IsChar())
  17054. rightCompareSize += 0x100;
  17055. if (!rightValue.mType->IsPrimitiveType())
  17056. rightCompareSize += 0x1000;
  17057. if ((leftValue.mType->IsTypeInstance()) && (rightValue.mType->IsTypeInstance()))
  17058. {
  17059. int leftInheritDepth = leftValue.mType->ToTypeInstance()->mInheritDepth;
  17060. int rightInheritDepth = rightValue.mType->ToTypeInstance()->mInheritDepth;
  17061. if (leftInheritDepth < rightInheritDepth)
  17062. {
  17063. // If both are type instances then choose the type with the lowest inherit depth
  17064. // so we will choose the base type when applicable
  17065. forceLeftType = true;
  17066. }
  17067. }
  17068. auto resultType = leftValue.mType;
  17069. if (!forceLeftType)
  17070. {
  17071. bool handled = false;
  17072. // If one of these is a constant that can be converted into a smaller type, then do that
  17073. if (rightValue.mValue.IsConst())
  17074. {
  17075. if (mModule->CanCast(rightValue, leftValue.mType, BfCastFlags_NoBox))
  17076. {
  17077. resultType = leftValue.mType;
  17078. handled = true;
  17079. }
  17080. }
  17081. // If left is an IntUnknown, allow the right to inform the type
  17082. if (leftValue.mType->IsIntUnknown())
  17083. {
  17084. if (leftValue.mValue.IsConst())
  17085. {
  17086. if (mModule->CanCast(leftValue, rightValue.mType))
  17087. {
  17088. resultType = rightValue.mType;
  17089. handled = true;
  17090. }
  17091. }
  17092. }
  17093. if ((leftValue.mType->IsPointer()) &&
  17094. (rightValue.mType->IsPointer()))
  17095. {
  17096. BfPointerType* leftPointerType = (BfPointerType*)leftValue.mType;
  17097. BfPointerType* rightPointerType = (BfPointerType*)rightValue.mType;
  17098. // If one is a pointer to a sized array then use the other type
  17099. if (leftPointerType->mElementType->IsSizedArray())
  17100. {
  17101. resultType = rightPointerType;
  17102. handled = true;
  17103. }
  17104. else if (rightPointerType->mElementType->IsSizedArray())
  17105. {
  17106. resultType = leftPointerType;
  17107. handled = true;
  17108. }
  17109. }
  17110. if (!handled)
  17111. {
  17112. if ((resultType->IsNull()) ||
  17113. (rightCompareSize > leftCompareSize) ||
  17114. (((rightCompareSize == leftCompareSize) && (!rightValue.mType->IsSigned()))) ||
  17115. (rightValue.mType->IsTypedPrimitive()))
  17116. {
  17117. // Select the type with the "most information"
  17118. if (!rightValue.mType->IsNull())
  17119. resultType = rightValue.mType;
  17120. }
  17121. if ((!resultType->IsPointer()) && (rightValue.mType->IsPointer()))
  17122. resultType = rightValue.mType;
  17123. }
  17124. }
  17125. bool explicitCast = false;
  17126. BfTypedValue* resultTypedValue;
  17127. BfTypedValue* otherTypedValue;
  17128. BfType* otherType;
  17129. BfAstNode* resultTypeSrc;
  17130. BfAstNode* otherTypeSrc;
  17131. if (resultType == leftValue.mType)
  17132. {
  17133. resultTypedValue = &leftValue;
  17134. resultTypeSrc = leftExpression;
  17135. otherTypedValue = &rightValue;
  17136. otherTypeSrc = rightExpression;
  17137. otherType = otherTypedValue->mType;
  17138. }
  17139. else
  17140. {
  17141. resultTypedValue = &rightValue;
  17142. resultTypeSrc = rightExpression;
  17143. otherTypedValue = &leftValue;
  17144. otherTypeSrc = leftExpression;
  17145. otherType = otherTypedValue->mType;
  17146. }
  17147. auto _OpFail = [&]()
  17148. {
  17149. if ((rightValue.mType != NULL) && (leftValue.mType != NULL))
  17150. {
  17151. if (rightValue.mType != leftValue.mType)
  17152. mModule->Fail(StrFormat("Cannot perform binary operation '%s' between types '%s' and '%s'",
  17153. BfGetOpName(binaryOp), mModule->TypeToString(leftValue.mType).c_str(), mModule->TypeToString(rightValue.mType).c_str()), opToken);
  17154. else
  17155. {
  17156. if (leftValue.mType->IsInterface())
  17157. {
  17158. 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.",
  17159. BfGetOpName(binaryOp), mModule->TypeToString(leftValue.mType).c_str()), opToken);
  17160. }
  17161. else
  17162. {
  17163. mModule->Fail(StrFormat("Cannot perform binary operation '%s' between two instances of type '%s'",
  17164. BfGetOpName(binaryOp), mModule->TypeToString(leftValue.mType).c_str()), opToken);
  17165. }
  17166. }
  17167. }
  17168. else
  17169. mModule->Fail(StrFormat("Cannot perform binary operation '%s'", BfGetOpName(binaryOp)), opToken);
  17170. };
  17171. // This case fixes cases like "c == 0" where "0" is technically an int but can be reduced
  17172. if (BfBinOpEqualityCheck(binaryOp))
  17173. {
  17174. if ((resultType != otherType) && (resultTypedValue->mValue.IsConst()) && (mModule->CanCast(*resultTypedValue, otherType)))
  17175. {
  17176. std::swap(resultTypedValue, otherTypedValue);
  17177. std::swap(resultTypeSrc, otherTypeSrc);
  17178. std::swap(resultType, otherType);
  17179. }
  17180. }
  17181. BfIRValue convLeftValue;
  17182. BfIRValue convRightValue;
  17183. if ((resultType->IsVar()) || (otherType->IsVar()))
  17184. {
  17185. bool isComparison = (binaryOp >= BfBinaryOp_Equality) && (binaryOp <= BfBinaryOp_LessThanOrEqual);
  17186. if (isComparison)
  17187. mResult = mModule->GetDefaultTypedValue(mModule->GetPrimitiveType(BfTypeCode_Boolean), false, BfDefaultValueKind_Addr);
  17188. else if (mExpectingType != NULL)
  17189. mResult = mModule->GetDefaultTypedValue(mExpectingType, false, BfDefaultValueKind_Addr);
  17190. else
  17191. mResult = mModule->GetDefaultTypedValue(resultType, false, BfDefaultValueKind_Addr);
  17192. return;
  17193. }
  17194. if ((otherType->IsNull()) && (BfBinOpEqualityCheck(binaryOp)))
  17195. {
  17196. bool isEquality = (binaryOp == BfBinaryOp_Equality) || (binaryOp == BfBinaryOp_StrictEquality);
  17197. if ((resultType->IsValueType()) && (!resultType->IsFunction()))
  17198. {
  17199. auto boolType = mModule->GetPrimitiveType(BfTypeCode_Boolean);
  17200. if (resultType->IsNullable())
  17201. {
  17202. auto elementType = resultType->GetUnderlyingType();
  17203. mModule->PopulateType(elementType);
  17204. if (elementType->IsValuelessType())
  17205. {
  17206. mModule->mBfIRBuilder->PopulateType(resultType);
  17207. BfTypedValue nullableTypedVale = mModule->MakeAddressable(*resultTypedValue);
  17208. BfIRValue hasValuePtr = mModule->mBfIRBuilder->CreateInBoundsGEP(nullableTypedVale.mValue, 0, 1);
  17209. BfIRValue hasValueValue = mModule->mBfIRBuilder->CreateLoad(hasValuePtr);
  17210. if (isEquality)
  17211. hasValueValue = mModule->mBfIRBuilder->CreateNot(hasValueValue);
  17212. mResult = BfTypedValue(hasValueValue, boolType);
  17213. }
  17214. else
  17215. {
  17216. mModule->mBfIRBuilder->PopulateType(resultType);
  17217. BfTypedValue nullableTypedVale = mModule->MakeAddressable(*resultTypedValue);
  17218. BfIRValue hasValuePtr = mModule->mBfIRBuilder->CreateInBoundsGEP(nullableTypedVale.mValue, 0, 2);
  17219. BfIRValue hasValueValue = mModule->mBfIRBuilder->CreateLoad(hasValuePtr);
  17220. if (isEquality)
  17221. hasValueValue = mModule->mBfIRBuilder->CreateNot(hasValueValue);
  17222. mResult = BfTypedValue(hasValueValue, boolType);
  17223. }
  17224. return;
  17225. }
  17226. if (resultType->IsNull())
  17227. {
  17228. // Null always equals null
  17229. mResult = BfTypedValue(mModule->GetConstValue(isEquality ? 1 : 0, boolType), boolType);
  17230. return;
  17231. }
  17232. if (!mModule->IsInSpecializedSection())
  17233. {
  17234. //CS0472: The result of the expression is always 'true' since a value of type 'int' is never equal to 'null' of type '<null>'
  17235. mModule->Warn(BfWarning_CS0472_ValueTypeNullCompare,
  17236. StrFormat("The result of the expression is always '%s' since a value of type '%s' can never be null",
  17237. isEquality ? "false" : "true", mModule->TypeToString(resultType).c_str()), otherTypeSrc);
  17238. }
  17239. // Valuetypes never equal null
  17240. mResult = BfTypedValue(mModule->GetConstValue(isEquality ? 0 : 1, boolType), boolType);
  17241. return;
  17242. }
  17243. }
  17244. // Check for constant equality checks (mostly for strings)
  17245. if (BfBinOpEqualityCheck(binaryOp))
  17246. {
  17247. auto leftConstant = mModule->mBfIRBuilder->GetConstant(leftValue.mValue);
  17248. auto rightConstant = mModule->mBfIRBuilder->GetConstant(rightValue.mValue);
  17249. if ((leftConstant != NULL) && (rightConstant != NULL))
  17250. {
  17251. auto boolType = mModule->GetPrimitiveType(BfTypeCode_Boolean);
  17252. int leftStringPoolIdx = mModule->GetStringPoolIdx(leftValue.mValue, mModule->mBfIRBuilder);
  17253. if (leftStringPoolIdx != -1)
  17254. {
  17255. int rightStringPoolIdx = mModule->GetStringPoolIdx(rightValue.mValue, mModule->mBfIRBuilder);
  17256. if (rightStringPoolIdx != -1)
  17257. {
  17258. bool isEqual = leftStringPoolIdx == rightStringPoolIdx;
  17259. if ((binaryOp == BfBinaryOp_InEquality) || (binaryOp == BfBinaryOp_StrictInEquality))
  17260. isEqual = !isEqual;
  17261. mResult = BfTypedValue(mModule->GetConstValue(isEqual ? 1 : 0, boolType), boolType);
  17262. return;
  17263. }
  17264. }
  17265. int eqResult = mModule->mBfIRBuilder->CheckConstEquality(leftValue.mValue, rightValue.mValue);
  17266. if (eqResult != -1)
  17267. {
  17268. bool isEqual = eqResult == 1;
  17269. if ((binaryOp == BfBinaryOp_InEquality) || (binaryOp == BfBinaryOp_StrictInEquality))
  17270. isEqual = !isEqual;
  17271. mResult = BfTypedValue(mModule->GetConstValue(isEqual ? 1 : 0, boolType), boolType);
  17272. return;
  17273. }
  17274. }
  17275. // Valueless types always compare as 'equal'
  17276. if (leftValue.mType == rightValue.mType)
  17277. {
  17278. mModule->PopulateType(leftValue.mType);
  17279. if (leftValue.mType->IsValuelessType())
  17280. {
  17281. auto boolType = mModule->GetPrimitiveType(BfTypeCode_Boolean);
  17282. bool isEqual = (binaryOp == BfBinaryOp_Equality) || (binaryOp == BfBinaryOp_StrictEquality);
  17283. mResult = BfTypedValue(mModule->GetConstValue(isEqual ? 1 : 0, boolType), boolType);
  17284. return;
  17285. }
  17286. }
  17287. }
  17288. if ((leftValue.mType->IsTypeInstance()) || (leftValue.mType->IsGenericParam()) ||
  17289. (rightValue.mType->IsTypeInstance()) || (rightValue.mType->IsGenericParam()))
  17290. {
  17291. // As an optimization, we don't call user operator overloads for null checks
  17292. bool skipOpOverload = false;
  17293. if ((binaryOp == BfBinaryOp_StrictEquality) || (binaryOp == BfBinaryOp_StrictInEquality))
  17294. skipOpOverload = true;
  17295. else if (BfBinOpEqualityCheck(binaryOp))
  17296. {
  17297. if (!leftValue.IsAddr())
  17298. {
  17299. auto leftConstant = mModule->mBfIRBuilder->GetConstant(leftValue.mValue);
  17300. if ((leftConstant != NULL) && (leftConstant->IsNull()))
  17301. skipOpOverload = true;
  17302. }
  17303. if (!rightValue.IsAddr())
  17304. {
  17305. auto rightConstant = mModule->mBfIRBuilder->GetConstant(rightValue.mValue);
  17306. if ((rightConstant != NULL) && (rightConstant->IsNull()))
  17307. skipOpOverload = true;
  17308. }
  17309. }
  17310. if (!skipOpOverload)
  17311. {
  17312. BfBinaryOp findBinaryOp = binaryOp;
  17313. bool isComparison = (binaryOp >= BfBinaryOp_Equality) && (binaryOp <= BfBinaryOp_LessThanOrEqual);
  17314. for (int pass = 0; pass < 2; pass++)
  17315. {
  17316. BfBinaryOp oppositeBinaryOp = BfGetOppositeBinaryOp(findBinaryOp);
  17317. bool foundOp = false;
  17318. SizedArray<BfResolvedArg, 2> args;
  17319. BfResolvedArg leftArg;
  17320. leftArg.mExpression = leftExpression;
  17321. leftArg.mTypedValue = leftValue;
  17322. BfResolvedArg rightArg;
  17323. rightArg.mExpression = rightExpression;
  17324. rightArg.mTypedValue = rightValue;
  17325. if (pass == 0)
  17326. {
  17327. args.push_back(leftArg);
  17328. args.push_back(rightArg);
  17329. }
  17330. else
  17331. {
  17332. args.push_back(rightArg);
  17333. args.push_back(leftArg);
  17334. }
  17335. BfMethodMatcher methodMatcher(opToken, mModule, "", args, NULL);
  17336. methodMatcher.mBfEvalExprFlags = BfEvalExprFlags_NoAutoComplete;
  17337. BfBaseClassWalker baseClassWalker(leftValue.mType, rightValue.mType, mModule);
  17338. bool invertResult = false;
  17339. BfType* operatorConstraintReturnType = NULL;
  17340. bool wasTransformedUsage = pass == 1;
  17341. while (true)
  17342. {
  17343. auto entry = baseClassWalker.Next();
  17344. auto checkType = entry.mTypeInstance;
  17345. if (checkType == NULL)
  17346. break;
  17347. bool foundExactMatch = false;
  17348. Array<BfOperatorDef*> oppositeOperatorDefs;
  17349. for (auto operatorDef : checkType->mTypeDef->mOperators)
  17350. {
  17351. bool allowOp = operatorDef->mOperatorDeclaration->mBinOp == findBinaryOp;
  17352. if ((isComparison) && (operatorDef->mOperatorDeclaration->mBinOp == BfBinaryOp_Compare))
  17353. allowOp = true;
  17354. if (allowOp)
  17355. {
  17356. foundOp = true;
  17357. if (!methodMatcher.IsMemberAccessible(checkType, operatorDef->mDeclaringType))
  17358. continue;
  17359. if ((flags & BfBinOpFlag_IsConstraintCheck) != 0)
  17360. {
  17361. // We can't do CheckMethod because circular referencing means we may have to evaluate this before our type is complete,
  17362. // which means before method processing has occurred
  17363. auto returnType = mModule->CheckOperator(checkType, operatorDef, args[0].mTypedValue, args[1].mTypedValue);
  17364. if (returnType != NULL)
  17365. {
  17366. operatorConstraintReturnType = returnType;
  17367. methodMatcher.mBestMethodDef = operatorDef;
  17368. foundExactMatch = true;
  17369. }
  17370. }
  17371. else
  17372. {
  17373. if (methodMatcher.CheckMethod(NULL, checkType, operatorDef, false))
  17374. {
  17375. methodMatcher.mSelfType = entry.mSrcType;
  17376. if (operatorDef->mOperatorDeclaration->mBinOp == findBinaryOp)
  17377. foundExactMatch = true;
  17378. }
  17379. }
  17380. }
  17381. else if (operatorDef->mOperatorDeclaration->mBinOp == oppositeBinaryOp)
  17382. oppositeOperatorDefs.Add(operatorDef);
  17383. }
  17384. if ((((methodMatcher.mBestMethodDef == NULL) && (operatorConstraintReturnType == NULL)) || (!foundExactMatch)) && (!oppositeOperatorDefs.IsEmpty()))
  17385. {
  17386. foundOp = true;
  17387. for (auto oppositeOperatorDef : oppositeOperatorDefs)
  17388. {
  17389. if ((flags & BfBinOpFlag_IsConstraintCheck) != 0)
  17390. {
  17391. auto returnType = mModule->CheckOperator(checkType, oppositeOperatorDef, args[0].mTypedValue, args[1].mTypedValue);
  17392. if (returnType != NULL)
  17393. {
  17394. operatorConstraintReturnType = returnType;
  17395. methodMatcher.mBestMethodDef = oppositeOperatorDef;
  17396. methodMatcher.mSelfType = entry.mSrcType;
  17397. wasTransformedUsage = true;
  17398. }
  17399. }
  17400. else
  17401. {
  17402. if (methodMatcher.CheckMethod(NULL, checkType, oppositeOperatorDef, false))
  17403. {
  17404. methodMatcher.mSelfType = entry.mSrcType;
  17405. wasTransformedUsage = true;
  17406. }
  17407. }
  17408. }
  17409. }
  17410. }
  17411. bool hadMatch = (methodMatcher.mBestMethodDef != NULL);
  17412. if ((methodMatcher.mBestMethodDef != NULL) && ((flags & BfBinOpFlag_IgnoreOperatorWithWrongResult) != 0))
  17413. {
  17414. auto matchedOp = ((BfOperatorDeclaration*)methodMatcher.mBestMethodDef->mMethodDeclaration)->mBinOp;
  17415. methodMatcher.mBestMethodInstance = GetSelectedMethod(methodMatcher.mTargetSrc, methodMatcher.mBestMethodTypeInstance, methodMatcher.mBestMethodDef, methodMatcher);
  17416. if ((methodMatcher.mBestMethodInstance.mMethodInstance->mReturnType != mExpectingType) &&
  17417. ((matchedOp == binaryOp) || (matchedOp == oppositeBinaryOp)))
  17418. {
  17419. if (binaryOp == BfBinaryOp_Equality)
  17420. binaryOp = BfBinaryOp_StrictEquality;
  17421. if (binaryOp == BfBinaryOp_InEquality)
  17422. binaryOp = BfBinaryOp_StrictEquality;
  17423. hadMatch = false;
  17424. break;
  17425. }
  17426. }
  17427. if (hadMatch)
  17428. {
  17429. methodMatcher.FlushAmbiguityError();
  17430. auto matchedOp = ((BfOperatorDeclaration*)methodMatcher.mBestMethodDef->mMethodDeclaration)->mBinOp;
  17431. bool invertResult = matchedOp == oppositeBinaryOp;
  17432. auto methodDef = methodMatcher.mBestMethodDef;
  17433. auto autoComplete = GetAutoComplete();
  17434. bool wasCapturingMethodInfo = false;
  17435. if ((autoComplete != NULL) && (autoComplete->IsAutocompleteNode(opToken)))
  17436. {
  17437. auto operatorDecl = BfNodeDynCast<BfOperatorDeclaration>(methodDef->mMethodDeclaration);
  17438. if ((operatorDecl != NULL) && (operatorDecl->mOpTypeToken != NULL))
  17439. autoComplete->SetDefinitionLocation(operatorDecl->mOpTypeToken);
  17440. }
  17441. if ((wasTransformedUsage) && (methodDef->mCommutableKind != BfCommutableKind_Operator))
  17442. {
  17443. auto error = mModule->Warn(BfWarning_BF4206_OperatorCommutableUsage, "Transformed operator usage requires 'Commutable' attribute to be added to the operator declaration", opToken);
  17444. if ((error != NULL) && (methodDef->GetRefNode() != NULL))
  17445. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("See operator declaration"), methodDef->GetRefNode());
  17446. }
  17447. if (opToken != NULL)
  17448. {
  17449. if ((opToken->IsA<BfTokenNode>()) && (!noClassify) && (!baseClassWalker.mMayBeFromInterface))
  17450. mModule->SetElementType(opToken, BfSourceElementType_Method);
  17451. }
  17452. if ((flags & BfBinOpFlag_IsConstraintCheck) != 0)
  17453. {
  17454. mResult = BfTypedValue(mModule->mBfIRBuilder->GetFakeVal(), operatorConstraintReturnType);
  17455. }
  17456. else
  17457. {
  17458. SetAndRestoreValue<BfEvalExprFlags> prevFlags(mBfEvalExprFlags, (BfEvalExprFlags)(mBfEvalExprFlags | BfEvalExprFlags_NoAutoComplete));
  17459. mResult = CreateCall(&methodMatcher, BfTypedValue());
  17460. }
  17461. if ((mResult.mType != NULL) && (methodMatcher.mSelfType != NULL) && (mResult.mType->IsSelf()))
  17462. {
  17463. BF_ASSERT(mModule->IsInGeneric());
  17464. mResult = mModule->GetDefaultTypedValue(methodMatcher.mSelfType, false, BfDefaultValueKind_Value);
  17465. }
  17466. if ((invertResult) && (mResult.mType == mModule->GetPrimitiveType(BfTypeCode_Boolean)))
  17467. mResult.mValue = mModule->mBfIRBuilder->CreateNot(mResult.mValue);
  17468. if (pass == 1)
  17469. {
  17470. if (findBinaryOp == BfBinaryOp_Compare)
  17471. {
  17472. mResult = mModule->LoadValue(mResult);
  17473. if (mResult.mType->IsIntegral())
  17474. mResult.mValue = mModule->mBfIRBuilder->CreateNeg(mResult.mValue);
  17475. }
  17476. }
  17477. if ((isComparison) && (matchedOp == BfBinaryOp_Compare))
  17478. {
  17479. auto intType = mModule->GetPrimitiveType(BfTypeCode_IntPtr);
  17480. mResult = mModule->LoadValue(mResult);
  17481. if (mResult.mType != intType)
  17482. mResult = mModule->GetDefaultTypedValue(intType);
  17483. auto zeroVal = mModule->mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, 0);
  17484. auto useBinaryOp = binaryOp;
  17485. if (pass == 1)
  17486. useBinaryOp = BfGetFlippedBinaryOp(useBinaryOp);
  17487. auto boolType = mModule->GetPrimitiveType(BfTypeCode_Boolean);
  17488. switch (useBinaryOp)
  17489. {
  17490. case BfBinaryOp_Equality:
  17491. case BfBinaryOp_StrictEquality:
  17492. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateCmpEQ(mResult.mValue, zeroVal), boolType);
  17493. break;
  17494. case BfBinaryOp_InEquality:
  17495. case BfBinaryOp_StrictInEquality:
  17496. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateCmpNE(mResult.mValue, zeroVal), boolType);
  17497. break;
  17498. case BfBinaryOp_GreaterThan:
  17499. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateCmpGT(mResult.mValue, zeroVal, true), boolType);
  17500. break;
  17501. case BfBinaryOp_LessThan:
  17502. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateCmpLT(mResult.mValue, zeroVal, true), boolType);
  17503. break;
  17504. case BfBinaryOp_GreaterThanOrEqual:
  17505. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateCmpGTE(mResult.mValue, zeroVal, true), boolType);
  17506. break;
  17507. case BfBinaryOp_LessThanOrEqual:
  17508. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateCmpLTE(mResult.mValue, zeroVal, true), boolType);
  17509. break;
  17510. default: break;
  17511. }
  17512. }
  17513. return;
  17514. }
  17515. auto _CheckBinaryOp = [&](BfGenericParamInstance* genericParam)
  17516. {
  17517. for (auto& opConstraint : genericParam->mOperatorConstraints)
  17518. {
  17519. BfType* returnType = genericParam->mExternType;
  17520. bool works = false;
  17521. if (opConstraint.mBinaryOp == findBinaryOp)
  17522. {
  17523. if ((mModule->CanCast(args[0].mTypedValue, opConstraint.mLeftType)) &&
  17524. (mModule->CanCast(args[1].mTypedValue, opConstraint.mRightType)))
  17525. {
  17526. works = true;
  17527. }
  17528. }
  17529. if ((isComparison) && (opConstraint.mBinaryOp == BfBinaryOp_Compare))
  17530. {
  17531. if ((mModule->CanCast(args[0].mTypedValue, opConstraint.mLeftType)) &&
  17532. (mModule->CanCast(args[1].mTypedValue, opConstraint.mRightType)))
  17533. {
  17534. works = true;
  17535. }
  17536. else if ((mModule->CanCast(args[0].mTypedValue, opConstraint.mRightType)) &&
  17537. (mModule->CanCast(args[1].mTypedValue, opConstraint.mLeftType)))
  17538. {
  17539. works = true;
  17540. }
  17541. if (works)
  17542. {
  17543. returnType = mModule->GetPrimitiveType(BfTypeCode_Boolean);
  17544. }
  17545. }
  17546. if (works)
  17547. {
  17548. BF_ASSERT(genericParam->mExternType != NULL);
  17549. mResult = BfTypedValue(mModule->mBfIRBuilder->GetFakeVal(), returnType);
  17550. return true;
  17551. }
  17552. }
  17553. return false;
  17554. };
  17555. // Check method generic constraints
  17556. if ((mModule->mCurMethodInstance != NULL) && (mModule->mCurMethodInstance->mIsUnspecialized) && (mModule->mCurMethodInstance->mMethodInfoEx != NULL))
  17557. {
  17558. for (int genericParamIdx = 0; genericParamIdx < mModule->mCurMethodInstance->mMethodInfoEx->mGenericParams.size(); genericParamIdx++)
  17559. {
  17560. auto genericParam = mModule->mCurMethodInstance->mMethodInfoEx->mGenericParams[genericParamIdx];
  17561. if (_CheckBinaryOp(genericParam))
  17562. return;
  17563. }
  17564. }
  17565. // Check type generic constraints
  17566. if ((mModule->mCurTypeInstance->IsGenericTypeInstance()) && (mModule->mCurTypeInstance->IsUnspecializedType()))
  17567. {
  17568. SizedArray<BfGenericParamInstance*, 4> genericParams;
  17569. mModule->GetActiveTypeGenericParamInstances(genericParams);
  17570. for (auto genericParam : genericParams)
  17571. {
  17572. if (_CheckBinaryOp(genericParam))
  17573. return;
  17574. }
  17575. }
  17576. if (pass == 1)
  17577. break;
  17578. findBinaryOp = BfGetFlippedBinaryOp(findBinaryOp);
  17579. if (findBinaryOp == BfBinaryOp_None)
  17580. break;
  17581. }
  17582. }
  17583. }
  17584. if (mModule->IsUnboundGeneric(resultType))
  17585. {
  17586. mResult = mModule->GetDefaultTypedValue(mModule->GetPrimitiveType(BfTypeCode_Var));
  17587. return;
  17588. }
  17589. if (resultType->IsPointer() && otherType->IsPointer())
  17590. {
  17591. if ((binaryOp == BfBinaryOp_Add) && (resultType == otherType) &&
  17592. (resultType->GetUnderlyingType() == mModule->GetPrimitiveType(BfTypeCode_Char8)))
  17593. {
  17594. AddStrings(leftValue, rightValue, opToken);
  17595. return;
  17596. }
  17597. //TODO: Allow all pointer comparisons, but only allow SUBTRACTION between equal pointer types
  17598. if (binaryOp == BfBinaryOp_Subtract)
  17599. {
  17600. if (!mModule->CanCast(*otherTypedValue, resultType))
  17601. {
  17602. mModule->Fail(StrFormat("Operands '%s' and '%s' are not comparable types.",
  17603. mModule->TypeToString(leftValue.mType).c_str(), mModule->TypeToString(rightValue.mType).c_str()),
  17604. opToken);
  17605. return;
  17606. }
  17607. BfPointerType* resultPointerType = (BfPointerType*)resultType;
  17608. BfType* intPtrType = mModule->GetPrimitiveType(BfTypeCode_IntPtr);
  17609. convLeftValue = mModule->CastToValue(leftExpression, leftValue, intPtrType, (BfCastFlags)(BfCastFlags_Explicit | BfCastFlags_FromCompiler));
  17610. convRightValue = mModule->CastToValue(rightExpression, rightValue, intPtrType, (BfCastFlags)(BfCastFlags_Explicit | BfCastFlags_FromCompiler));
  17611. BfIRValue diffValue = mModule->mBfIRBuilder->CreateSub(convLeftValue, convRightValue);
  17612. diffValue = mModule->mBfIRBuilder->CreateDiv(diffValue, mModule->GetConstValue(resultPointerType->mElementType->mSize, intPtrType), true);
  17613. mResult = BfTypedValue(diffValue, intPtrType);
  17614. return;
  17615. }
  17616. else if ((binaryOp != BfBinaryOp_Equality) && (binaryOp != BfBinaryOp_StrictEquality) &&
  17617. (binaryOp != BfBinaryOp_InEquality) && (binaryOp != BfBinaryOp_StrictInEquality) &&
  17618. (binaryOp != BfBinaryOp_LessThan) && (binaryOp != BfBinaryOp_LessThanOrEqual) &&
  17619. (binaryOp != BfBinaryOp_GreaterThan) && (binaryOp != BfBinaryOp_GreaterThanOrEqual))
  17620. {
  17621. mModule->Fail("Invalid operation on pointers", opToken);
  17622. return;
  17623. }
  17624. if ((!BfBinOpEqualityCheck(binaryOp)) || (resultType != otherType))
  17625. {
  17626. resultType = mModule->GetPrimitiveType(BfTypeCode_UIntPtr);
  17627. explicitCast = true;
  17628. }
  17629. }
  17630. else if (resultType->IsPointer())
  17631. {
  17632. if (otherType->IsNull())
  17633. {
  17634. if (!BfBinOpEqualityCheck(binaryOp))
  17635. {
  17636. mModule->Fail(StrFormat("Invalid operation between '%s' and null", mModule->TypeToString(resultType).c_str()), opToken);
  17637. return;
  17638. }
  17639. if ((binaryOp == BfBinaryOp_Equality) || (binaryOp == BfBinaryOp_StrictEquality))
  17640. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateIsNull(resultTypedValue->mValue), mModule->GetPrimitiveType(BfTypeCode_Boolean));
  17641. else
  17642. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateIsNotNull(resultTypedValue->mValue), mModule->GetPrimitiveType(BfTypeCode_Boolean));
  17643. return;
  17644. }
  17645. // One pointer
  17646. if ((!otherType->IsIntegral()) ||
  17647. ((binaryOp != BfBinaryOp_Add) && (binaryOp != BfBinaryOp_Subtract)))
  17648. {
  17649. _OpFail();
  17650. return;
  17651. }
  17652. auto underlyingType = resultType->GetUnderlyingType();
  17653. BfIRValue addValue = otherTypedValue->mValue;
  17654. if ((!otherTypedValue->mType->IsSigned()) && (otherTypedValue->mType->mSize < mModule->mSystem->mPtrSize))
  17655. addValue = mModule->mBfIRBuilder->CreateNumericCast(addValue, false, BfTypeCode_UIntPtr);
  17656. if (binaryOp == BfBinaryOp_Subtract)
  17657. {
  17658. if (resultTypeSrc == rightExpression)
  17659. mModule->Fail("Cannot subtract a pointer from an integer", resultTypeSrc);
  17660. addValue = mModule->mBfIRBuilder->CreateNeg(addValue);
  17661. }
  17662. mModule->PopulateType(underlyingType);
  17663. if (underlyingType->IsValuelessType())
  17664. {
  17665. if (!mModule->IsInSpecializedSection())
  17666. {
  17667. mModule->Warn(0, "Adding to a pointer to a zero-sized element has no effect", opToken);
  17668. }
  17669. mResult = *resultTypedValue;
  17670. return;
  17671. }
  17672. mModule->mBfIRBuilder->PopulateType(underlyingType);
  17673. mResult = BfTypedValue(mModule->CreateIndexedValue(underlyingType, resultTypedValue->mValue, addValue), resultType);
  17674. return;
  17675. }
  17676. if ((resultType->IsFunction()) || (resultType->IsPointer()) || (resultType->IsObject()) || (resultType->IsInterface()) || (resultType->IsGenericParam()))
  17677. {
  17678. if ((binaryOp == BfBinaryOp_Add) &&
  17679. (resultType->IsInstanceOf(mModule->mCompiler->mStringTypeDef)) &&
  17680. (otherType->IsInstanceOf(mModule->mCompiler->mStringTypeDef)))
  17681. {
  17682. AddStrings(leftValue, rightValue, opToken);
  17683. return;
  17684. }
  17685. if (!BfGetBinaryOpPrecendence(binaryOp))
  17686. {
  17687. //mModule->Fail("Invalid operation for objects", opToken);
  17688. _OpFail();
  17689. return;
  17690. }
  17691. if ((binaryOp == BfBinaryOp_Equality) || (binaryOp == BfBinaryOp_StrictEquality) || (binaryOp == BfBinaryOp_InEquality) || (binaryOp == BfBinaryOp_StrictInEquality))
  17692. {
  17693. if (resultType->IsInterface())
  17694. {
  17695. // Compare as objects instead
  17696. resultType = mModule->mContext->mBfObjectType;
  17697. *resultTypedValue = mModule->Cast(resultTypeSrc, *resultTypedValue, resultType);
  17698. }
  17699. if (otherType->IsNull())
  17700. {
  17701. if (resultType->IsFunction())
  17702. {
  17703. if ((binaryOp == BfBinaryOp_Equality) || (binaryOp == BfBinaryOp_StrictEquality))
  17704. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateCmpEQ(mModule->mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, 0), resultTypedValue->mValue), mModule->GetPrimitiveType(BfTypeCode_Boolean));
  17705. else
  17706. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateCmpNE(mModule->mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, 0), resultTypedValue->mValue), mModule->GetPrimitiveType(BfTypeCode_Boolean));
  17707. }
  17708. else
  17709. {
  17710. if ((binaryOp == BfBinaryOp_Equality) || (binaryOp == BfBinaryOp_StrictEquality))
  17711. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateIsNull(resultTypedValue->mValue), mModule->GetPrimitiveType(BfTypeCode_Boolean));
  17712. else
  17713. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateIsNotNull(resultTypedValue->mValue), mModule->GetPrimitiveType(BfTypeCode_Boolean));
  17714. }
  17715. }
  17716. else
  17717. {
  17718. auto convertedValue = mModule->Cast(otherTypeSrc, *otherTypedValue, resultType, BfCastFlags_NoBox);
  17719. if (!convertedValue)
  17720. return;
  17721. convertedValue = mModule->LoadValue(convertedValue);
  17722. if ((binaryOp == BfBinaryOp_Equality) || (binaryOp == BfBinaryOp_StrictEquality))
  17723. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateCmpEQ(resultTypedValue->mValue, convertedValue.mValue), mModule->GetPrimitiveType(BfTypeCode_Boolean));
  17724. else
  17725. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateCmpNE(resultTypedValue->mValue, convertedValue.mValue), mModule->GetPrimitiveType(BfTypeCode_Boolean));
  17726. }
  17727. return;
  17728. }
  17729. }
  17730. if (resultType->IsTypedPrimitive())
  17731. {
  17732. bool needsOtherCast = true;
  17733. if (otherType != resultType)
  17734. {
  17735. if ((otherType->IsPrimitiveType()) && (!otherType->IsValuelessType()))
  17736. {
  17737. // Allow zero comparisons to match all typed primitives
  17738. if ((binaryOp == BfBinaryOp_Equality) || (binaryOp == BfBinaryOp_InEquality))
  17739. {
  17740. auto constant = mModule->mBfIRBuilder->GetConstant(otherTypedValue->mValue);
  17741. if ((constant != NULL) && (mModule->mBfIRBuilder->IsInt(constant->mTypeCode)) && (constant->mInt64 == 0))
  17742. needsOtherCast = false;
  17743. }
  17744. // Allow integer offsetting
  17745. if ((binaryOp == BfBinaryOp_Add) || (binaryOp == BfBinaryOp_Subtract))
  17746. {
  17747. if (otherType->IsIntegral())
  17748. needsOtherCast = false;
  17749. }
  17750. }
  17751. if (needsOtherCast)
  17752. {
  17753. // The only purpose of this cast is to potentially throw a casting error
  17754. BfIRValue otherCastResult = mModule->CastToValue(otherTypeSrc, *otherTypedValue, resultType, explicitCast ? BfCastFlags_Explicit : BfCastFlags_None);
  17755. if (!otherCastResult)
  17756. return;
  17757. }
  17758. }
  17759. auto underlyingType = resultType->GetUnderlyingType();
  17760. BfIRValue convResultValue = mModule->CastToValue(resultTypeSrc, *resultTypedValue, underlyingType, BfCastFlags_Explicit);
  17761. BfIRValue convOtherValue = mModule->CastToValue(otherTypeSrc, *otherTypedValue, underlyingType, BfCastFlags_Explicit);
  17762. if ((!underlyingType->IsValuelessType()) && ((!convResultValue) || (!convOtherValue)))
  17763. return;
  17764. if (resultTypedValue == &leftValue)
  17765. PerformBinaryOperation(underlyingType, convResultValue, convOtherValue, binaryOp, opToken);
  17766. else
  17767. PerformBinaryOperation(underlyingType, convOtherValue, convResultValue, binaryOp, opToken);
  17768. if (mResult.mType == underlyingType)
  17769. mResult.mType = resultType;
  17770. return;
  17771. }
  17772. auto _CallValueTypeEquals = [&]()
  17773. {
  17774. BfModuleMethodInstance moduleMethodInstance;
  17775. auto typeInst = leftValue.mType->ToTypeInstance();
  17776. if (typeInst != NULL)
  17777. {
  17778. if ((binaryOp == BfBinaryOp_StrictEquality) || (binaryOp == BfBinaryOp_StrictInEquality))
  17779. moduleMethodInstance = mModule->GetMethodByName(typeInst, BF_METHODNAME_DEFAULT_STRICT_EQUALS);
  17780. else
  17781. moduleMethodInstance = mModule->GetMethodByName(typeInst, BF_METHODNAME_DEFAULT_EQUALS);
  17782. }
  17783. else
  17784. {
  17785. BF_ASSERT(leftValue.mType->IsSizedArray() || leftValue.mType->IsMethodRef());
  17786. auto valueTypeInst = mModule->ResolveTypeDef(mModule->mCompiler->mValueTypeTypeDef)->ToTypeInstance();
  17787. BfMethodDef* equalsMethodDef = mModule->mCompiler->mValueTypeTypeDef->GetMethodByName("Equals");
  17788. BfTypeVector typeVec;
  17789. typeVec.push_back(leftValue.mType);
  17790. moduleMethodInstance = mModule->GetMethodInstance(valueTypeInst, equalsMethodDef, typeVec);
  17791. }
  17792. if (moduleMethodInstance)
  17793. {
  17794. if ((opToken != NULL) && (!noClassify))
  17795. mModule->SetElementType(opToken, BfSourceElementType_Method);
  17796. SizedArray<BfResolvedArg, 4> argValues;
  17797. BfResolvedArg resolvedArg;
  17798. resolvedArg.mTypedValue = leftValue;
  17799. argValues.push_back(resolvedArg);
  17800. resolvedArg.mTypedValue = rightValue;
  17801. argValues.push_back(resolvedArg);
  17802. mResult = CreateCall(opToken, BfTypedValue(), BfTypedValue(), moduleMethodInstance.mMethodInstance->mMethodDef, moduleMethodInstance, false, argValues);
  17803. if ((mResult) &&
  17804. ((binaryOp == BfBinaryOp_InEquality) || (binaryOp == BfBinaryOp_StrictInEquality)))
  17805. mResult.mValue = mModule->mBfIRBuilder->CreateNot(mResult.mValue);
  17806. return true;
  17807. }
  17808. return false;
  17809. };
  17810. //if (((leftValue.mType->IsComposite()) || (leftValue.mType->IsObject())))
  17811. if (((resultType->IsComposite()) || (resultType->IsObject())))
  17812. {
  17813. bool areEquivalentTuples = false;
  17814. if ((leftValue.mType->IsTuple()) && (rightValue.mType->IsTuple()))
  17815. {
  17816. auto leftTupleType = (BfTypeInstance*)leftValue.mType;
  17817. auto rightTupleType = (BfTypeInstance*)rightValue.mType;
  17818. // We only do this for tuples, because we would allow an implicit struct
  17819. // truncation if we allow it for all structs, which would result in only
  17820. // the base class's fields being compared
  17821. if (mModule->CanCast(rightValue, leftValue.mType))
  17822. rightValue = mModule->Cast(opToken, rightValue, leftValue.mType, BfCastFlags_Explicit);
  17823. else if (mModule->CanCast(leftValue, rightValue.mType))
  17824. leftValue = mModule->Cast(opToken, leftValue, rightValue.mType, BfCastFlags_Explicit);
  17825. }
  17826. if (leftValue.mType == rightValue.mType)
  17827. {
  17828. if (BfBinOpEqualityCheck(binaryOp))
  17829. {
  17830. auto intCoercibleType = mModule->GetIntCoercibleType(leftValue.mType);
  17831. if (intCoercibleType != NULL)
  17832. {
  17833. auto intLHS = mModule->GetIntCoercible(leftValue);
  17834. auto intRHS = mModule->GetIntCoercible(rightValue);
  17835. auto boolType = mModule->GetPrimitiveType(BfTypeCode_Boolean);
  17836. if ((binaryOp == BfBinaryOp_Equality) || (binaryOp == BfBinaryOp_StrictEquality))
  17837. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateCmpEQ(intLHS.mValue, intRHS.mValue), boolType);
  17838. else
  17839. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateCmpNE(intLHS.mValue, intRHS.mValue), boolType);
  17840. return;
  17841. }
  17842. if (_CallValueTypeEquals())
  17843. return;
  17844. }
  17845. mModule->Fail(StrFormat("Operator '%s' cannot be applied to operands of type '%s'",
  17846. BfGetOpName(binaryOp),
  17847. mModule->TypeToString(leftValue.mType).c_str()), opToken);
  17848. return;
  17849. }
  17850. else
  17851. {
  17852. bool handled = false;
  17853. for (int pass = 0; pass < 2; pass++)
  17854. {
  17855. BfTypedValue& fromValue = (pass == 0) ? leftValue : rightValue;
  17856. BfType* toType = (pass == 0) ? rightValue.mType : leftValue.mType;
  17857. if (mModule->CanCast(fromValue, toType))
  17858. {
  17859. auto result = mModule->Cast(opToken, fromValue, toType);
  17860. if (result)
  17861. {
  17862. resultType = toType;
  17863. fromValue = result;
  17864. handled = true;
  17865. break;
  17866. }
  17867. }
  17868. }
  17869. if (!handled)
  17870. {
  17871. mModule->Fail(StrFormat("Operator '%s' cannot be applied to operands of type '%s' and '%s'",
  17872. BfGetOpName(binaryOp),
  17873. mModule->TypeToString(leftValue.mType).c_str(),
  17874. mModule->TypeToString(rightValue.mType).c_str()), opToken);
  17875. return;
  17876. }
  17877. }
  17878. }
  17879. if (resultType->IsMethodRef() && otherType->IsMethodRef())
  17880. {
  17881. if (BfBinOpEqualityCheck(binaryOp))
  17882. {
  17883. auto boolType = mModule->GetPrimitiveType(BfTypeCode_Boolean);
  17884. BfMethodRefType* lhsMethodRefType = (BfMethodRefType*)leftValue.mType;
  17885. BfMethodRefType* rhsMethodRefType = (BfMethodRefType*)rightValue.mType;
  17886. if (lhsMethodRefType->mMethodRef != rhsMethodRefType->mMethodRef)
  17887. {
  17888. mResult = BfTypedValue(mModule->GetConstValue(((binaryOp == BfBinaryOp_Equality) || (binaryOp == BfBinaryOp_StrictEquality)) ? 0 : 1, boolType), boolType);
  17889. return;
  17890. }
  17891. if (_CallValueTypeEquals())
  17892. return;
  17893. }
  17894. }
  17895. if (resultType->IsIntegral())
  17896. {
  17897. if ((binaryOp == BfBinaryOp_LeftShift) || (binaryOp == BfBinaryOp_RightShift))
  17898. {
  17899. if (rightValue.mValue.IsConst())
  17900. {
  17901. auto constVal = mModule->mBfIRBuilder->GetConstant(rightValue.mValue);
  17902. if ((constVal->mInt64 < 0) || (constVal->mInt64 >= 8 * resultType->mSize))
  17903. {
  17904. mModule->Fail(StrFormat("Shift value '%lld' is out of range for type '%s'", constVal->mInt64, mModule->TypeToString(resultType).c_str()), opToken);
  17905. }
  17906. }
  17907. }
  17908. // We're trying a simplified scheme that doesn't always try to up-convert into an 'int'
  17909. if (leftValue.mType != rightValue.mType)
  17910. {
  17911. bool isBitwiseExpr =
  17912. (binaryOp == BfBinaryOp_BitwiseAnd) ||
  17913. (binaryOp == BfBinaryOp_BitwiseOr) ||
  17914. (binaryOp == BfBinaryOp_ExclusiveOr) ||
  17915. (binaryOp == BfBinaryOp_LeftShift) ||
  17916. (binaryOp == BfBinaryOp_RightShift) ||
  17917. (binaryOp == BfBinaryOp_Equality) ||
  17918. (binaryOp == BfBinaryOp_InEquality) ||
  17919. (binaryOp == BfBinaryOp_StrictEquality) ||
  17920. (binaryOp == BfBinaryOp_StrictInEquality);
  17921. if ((binaryOp == BfBinaryOp_LeftShift) || (binaryOp == BfBinaryOp_RightShift))
  17922. {
  17923. // For shifts we have more lenient rules - shifts are naturally limited so any int type is equally valid
  17924. if (rightValue.mType->IsIntegral())
  17925. explicitCast = true;
  17926. }
  17927. else if (((binaryOp == BfBinaryOp_Add) || (binaryOp == BfBinaryOp_Subtract)) && (resultType->IsChar()) && (otherType->IsInteger()))
  17928. {
  17929. // charVal += intVal;
  17930. explicitCast = true;
  17931. }
  17932. else if ((!resultType->IsSigned()) && (otherType->IsSigned()))
  17933. {
  17934. if (mModule->CanCast(*otherTypedValue, resultType))
  17935. {
  17936. // If we can convert the 'other' value implicitly then it's a convertible literal, leave as uint
  17937. }
  17938. else
  17939. {
  17940. mModule->Fail(StrFormat("Operator cannot be applied to operands of type '%s' and '%s'",
  17941. mModule->TypeToString(leftValue.mType).c_str(),
  17942. mModule->TypeToString(rightValue.mType).c_str()), opToken);
  17943. return;
  17944. }
  17945. }
  17946. else if ((isBitwiseExpr) && (otherType->IsIntegral()) && (resultType->mSize == otherType->mSize))
  17947. {
  17948. // Forget about signed/unsigned mismatches for bitwise operations
  17949. explicitCast = true;
  17950. }
  17951. else
  17952. {
  17953. if ((binaryOp == BfBinaryOp_Subtract) && (resultType->IsChar()) && (otherType->IsChar()))
  17954. {
  17955. // "wchar - char" subtraction will always fit into int32, because of unicode range
  17956. resultType = mModule->GetPrimitiveType(BfTypeCode_Int32);
  17957. explicitCast = true;
  17958. }
  17959. else if ((otherType->IsChar()) &&
  17960. ((binaryOp == BfBinaryOp_Add) || (binaryOp == BfBinaryOp_Subtract)))
  17961. {
  17962. mModule->Fail(StrFormat("Cannot perform operation between types '%s' and '%s'",
  17963. mModule->TypeToString(leftValue.mType).c_str(),
  17964. mModule->TypeToString(rightValue.mType).c_str()), opToken);
  17965. }
  17966. }
  17967. }
  17968. else if ((!resultType->IsSigned()) && (binaryOp == BfBinaryOp_Subtract) && (!forceLeftType))
  17969. {
  17970. if ((mExpectingType == NULL) || (mExpectingType->IsSigned()) || (resultType->IsChar()))
  17971. {
  17972. if ((resultType->IsChar()) && (resultType->mSize == 4))
  17973. {
  17974. // "wchar - wchar" subtraction will always fit into int32, because of unicode range
  17975. resultType = mModule->GetPrimitiveType(BfTypeCode_Int32);
  17976. }
  17977. else
  17978. {
  17979. // The result of uint8 - uint8 is int16 (for example)
  17980. switch (resultType->mSize)
  17981. {
  17982. case 1:
  17983. resultType = mModule->GetPrimitiveType(BfTypeCode_Int16);
  17984. break;
  17985. case 2:
  17986. resultType = mModule->GetPrimitiveType(BfTypeCode_Int32);
  17987. break;
  17988. case 4:
  17989. resultType = mModule->GetPrimitiveType(BfTypeCode_Int64);
  17990. break;
  17991. }
  17992. }
  17993. explicitCast = true;
  17994. }
  17995. }
  17996. else if (resultType->IsChar())
  17997. {
  17998. bool canDoOp =
  17999. (binaryOp == BfBinaryOp_BitwiseAnd) ||
  18000. (binaryOp == BfBinaryOp_BitwiseOr) ||
  18001. ((binaryOp >= BfBinaryOp_Equality) && (binaryOp <= BfBinaryOp_Compare));
  18002. if (!canDoOp)
  18003. {
  18004. mModule->Fail(StrFormat("Cannot perform operation on type '%s'", mModule->TypeToString(resultType).c_str()), opToken);
  18005. return;
  18006. }
  18007. }
  18008. }
  18009. if (!convLeftValue)
  18010. convLeftValue = mModule->CastToValue(leftExpression, leftValue, resultType,
  18011. explicitCast ? (BfCastFlags)(BfCastFlags_Explicit | BfCastFlags_FromCompiler) : BfCastFlags_None);
  18012. if (!convRightValue)
  18013. convRightValue = mModule->CastToValue(rightExpression, rightValue, resultType,
  18014. explicitCast ? (BfCastFlags)(BfCastFlags_Explicit | BfCastFlags_FromCompiler) : BfCastFlags_None);
  18015. PerformBinaryOperation(resultType, convLeftValue, convRightValue, binaryOp, opToken);
  18016. }
  18017. void BfExprEvaluator::PerformBinaryOperation(BfType* resultType, BfIRValue convLeftValue, BfIRValue convRightValue, BfBinaryOp binaryOp, BfAstNode* opToken)
  18018. {
  18019. if (resultType->IsValuelessType())
  18020. {
  18021. switch (binaryOp)
  18022. {
  18023. case BfBinaryOp_Equality:
  18024. case BfBinaryOp_StrictEquality:
  18025. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConst(BfTypeCode_Boolean, 1),
  18026. mModule->GetPrimitiveType(BfTypeCode_Boolean));
  18027. break;
  18028. case BfBinaryOp_InEquality:
  18029. case BfBinaryOp_StrictInEquality:
  18030. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConst(BfTypeCode_Boolean, 0),
  18031. mModule->GetPrimitiveType(BfTypeCode_Boolean));
  18032. break;
  18033. default:
  18034. mModule->Fail("Invalid operation for void", opToken);
  18035. break;
  18036. }
  18037. return;
  18038. }
  18039. if ((!convLeftValue) || (!convRightValue))
  18040. return;
  18041. if (resultType->IsPrimitiveType())
  18042. {
  18043. auto primType = (BfPrimitiveType*)resultType;
  18044. if (primType->mTypeDef->mTypeCode == BfTypeCode_Boolean)
  18045. {
  18046. switch (binaryOp)
  18047. {
  18048. case BfBinaryOp_Equality:
  18049. case BfBinaryOp_StrictEquality:
  18050. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateCmpEQ(convLeftValue, convRightValue),
  18051. mModule->GetPrimitiveType(BfTypeCode_Boolean));
  18052. break;
  18053. case BfBinaryOp_InEquality:
  18054. case BfBinaryOp_StrictInEquality:
  18055. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateCmpNE(convLeftValue, convRightValue),
  18056. mModule->GetPrimitiveType(BfTypeCode_Boolean));
  18057. break;
  18058. case BfBinaryOp_BitwiseAnd:
  18059. case BfBinaryOp_ConditionalAnd:
  18060. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateAnd(convLeftValue, convRightValue),
  18061. mModule->GetPrimitiveType(BfTypeCode_Boolean));
  18062. break;
  18063. case BfBinaryOp_BitwiseOr:
  18064. case BfBinaryOp_ConditionalOr:
  18065. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateOr(convLeftValue, convRightValue),
  18066. mModule->GetPrimitiveType(BfTypeCode_Boolean));
  18067. break;
  18068. case BfBinaryOp_ExclusiveOr:
  18069. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateXor(convLeftValue, convRightValue),
  18070. mModule->GetPrimitiveType(BfTypeCode_Boolean));
  18071. break;
  18072. default:
  18073. mModule->Fail("Invalid operation for booleans", opToken);
  18074. break;
  18075. }
  18076. return;
  18077. }
  18078. }
  18079. if ((!resultType->IsIntegral()) && (!resultType->IsFloat()))
  18080. {
  18081. mModule->Fail(StrFormat("Cannot perform operation on type '%s'", mModule->TypeToString(resultType).c_str()), opToken);
  18082. return;
  18083. }
  18084. if (resultType->IsIntegral())
  18085. {
  18086. switch (binaryOp)
  18087. {
  18088. case BfBinaryOp_BitwiseAnd:
  18089. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateAnd(convLeftValue, convRightValue), resultType);
  18090. return;
  18091. case BfBinaryOp_BitwiseOr:
  18092. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateOr(convLeftValue, convRightValue), resultType);
  18093. return;
  18094. case BfBinaryOp_ExclusiveOr:
  18095. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateXor(convLeftValue, convRightValue), resultType);
  18096. return;
  18097. case BfBinaryOp_LeftShift:
  18098. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateShl(convLeftValue, convRightValue), resultType);
  18099. mModule->CheckRangeError(resultType, opToken);
  18100. return;
  18101. case BfBinaryOp_RightShift:
  18102. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateShr(convLeftValue, convRightValue, resultType->IsSigned()), resultType);
  18103. return;
  18104. default: break;
  18105. }
  18106. }
  18107. if ((resultType->IsChar()) &&
  18108. ((binaryOp == BfBinaryOp_Multiply) ||
  18109. (binaryOp == BfBinaryOp_Divide) ||
  18110. (binaryOp == BfBinaryOp_Modulus)))
  18111. {
  18112. mModule->Fail(StrFormat("Cannot perform operation on type '%s'", mModule->TypeToString(resultType).c_str()), opToken);
  18113. return;
  18114. }
  18115. switch (binaryOp)
  18116. {
  18117. case BfBinaryOp_Add:
  18118. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateAdd(convLeftValue, convRightValue), resultType);
  18119. mModule->CheckRangeError(resultType, opToken);
  18120. break;
  18121. case BfBinaryOp_Subtract:
  18122. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateSub(convLeftValue, convRightValue), resultType);
  18123. mModule->CheckRangeError(resultType, opToken);
  18124. break;
  18125. case BfBinaryOp_Multiply:
  18126. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateMul(convLeftValue, convRightValue), resultType);
  18127. mModule->CheckRangeError(resultType, opToken);
  18128. break;
  18129. case BfBinaryOp_Divide:
  18130. {
  18131. bool isZero = false;
  18132. if (convRightValue.IsConst())
  18133. {
  18134. auto constVal = mModule->mBfIRBuilder->GetConstant(convRightValue);
  18135. if (BfIRBuilder::IsInt(constVal->mTypeCode))
  18136. isZero = constVal->mInt64 == 0;
  18137. }
  18138. if (isZero)
  18139. {
  18140. mModule->Fail("Divide by zero", opToken);
  18141. mResult = mModule->GetDefaultTypedValue(resultType);
  18142. }
  18143. else
  18144. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateDiv(convLeftValue, convRightValue, resultType->IsSigned()), resultType);
  18145. }
  18146. break;
  18147. case BfBinaryOp_Modulus:
  18148. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateRem(convLeftValue, convRightValue, resultType->IsSigned()), resultType);
  18149. break;
  18150. case BfBinaryOp_Equality:
  18151. case BfBinaryOp_StrictEquality:
  18152. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateCmpEQ(convLeftValue, convRightValue),
  18153. mModule->GetPrimitiveType(BfTypeCode_Boolean));
  18154. break;
  18155. case BfBinaryOp_InEquality:
  18156. case BfBinaryOp_StrictInEquality:
  18157. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateCmpNE(convLeftValue, convRightValue),
  18158. mModule->GetPrimitiveType(BfTypeCode_Boolean));
  18159. break;
  18160. case BfBinaryOp_LessThan:
  18161. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateCmpLT(convLeftValue, convRightValue, resultType->IsSignedInt()),
  18162. mModule->GetPrimitiveType(BfTypeCode_Boolean));
  18163. break;
  18164. case BfBinaryOp_LessThanOrEqual:
  18165. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateCmpLTE(convLeftValue, convRightValue, resultType->IsSignedInt()),
  18166. mModule->GetPrimitiveType(BfTypeCode_Boolean));
  18167. break;
  18168. case BfBinaryOp_GreaterThan:
  18169. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateCmpGT(convLeftValue, convRightValue, resultType->IsSignedInt()),
  18170. mModule->GetPrimitiveType(BfTypeCode_Boolean));
  18171. break;
  18172. case BfBinaryOp_GreaterThanOrEqual:
  18173. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateCmpGTE(convLeftValue, convRightValue, resultType->IsSignedInt()),
  18174. mModule->GetPrimitiveType(BfTypeCode_Boolean));
  18175. break;
  18176. case BfBinaryOp_Compare:
  18177. {
  18178. auto intType = mModule->GetPrimitiveType(BfTypeCode_IntPtr);
  18179. if ((convLeftValue.IsConst()) && (convRightValue.IsConst()))
  18180. {
  18181. auto cmpLtVal = mModule->mBfIRBuilder->CreateCmpLT(convLeftValue, convRightValue, resultType->IsSignedInt());
  18182. auto ltConstant = mModule->mBfIRBuilder->GetConstant(cmpLtVal);
  18183. if (ltConstant->mBool)
  18184. {
  18185. mResult = BfTypedValue(mModule->GetConstValue(-1, mModule->GetPrimitiveType(BfTypeCode_IntPtr)), intType);
  18186. }
  18187. else
  18188. {
  18189. auto cmpGtVal = mModule->mBfIRBuilder->CreateCmpGT(convLeftValue, convRightValue, resultType->IsSignedInt());
  18190. auto rtConstant = mModule->mBfIRBuilder->GetConstant(cmpGtVal);
  18191. if (rtConstant->mBool)
  18192. mResult = BfTypedValue(mModule->GetConstValue(1, mModule->GetPrimitiveType(BfTypeCode_IntPtr)), intType);
  18193. else
  18194. mResult = BfTypedValue(mModule->GetConstValue(0, mModule->GetPrimitiveType(BfTypeCode_IntPtr)), intType);
  18195. }
  18196. }
  18197. else if ((resultType->IsIntegral()) && (resultType->mSize < intType->mSize))
  18198. {
  18199. auto leftIntValue = mModule->mBfIRBuilder->CreateNumericCast(convLeftValue, resultType->IsSignedInt(), BfTypeCode_IntPtr);
  18200. auto rightIntValue = mModule->mBfIRBuilder->CreateNumericCast(convRightValue, resultType->IsSignedInt(), BfTypeCode_IntPtr);
  18201. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateSub(leftIntValue, rightIntValue), intType);
  18202. }
  18203. else
  18204. {
  18205. BfIRBlock checkGtBlock = mModule->mBfIRBuilder->CreateBlock("cmpCheckGt");
  18206. BfIRBlock eqBlock = mModule->mBfIRBuilder->CreateBlock("cmpEq");
  18207. BfIRBlock endBlock = mModule->mBfIRBuilder->CreateBlock("cmpEnd");
  18208. auto startBlock = mModule->mBfIRBuilder->GetInsertBlock();
  18209. auto cmpLtVal = mModule->mBfIRBuilder->CreateCmpLT(convLeftValue, convRightValue, resultType->IsSignedInt());
  18210. mModule->mBfIRBuilder->CreateCondBr(cmpLtVal, endBlock, checkGtBlock);
  18211. mModule->mBfIRBuilder->AddBlock(checkGtBlock);
  18212. mModule->mBfIRBuilder->SetInsertPoint(checkGtBlock);
  18213. auto cmpGtVal = mModule->mBfIRBuilder->CreateCmpGT(convLeftValue, convRightValue, resultType->IsSignedInt());
  18214. mModule->mBfIRBuilder->CreateCondBr(cmpGtVal, endBlock, eqBlock);
  18215. mModule->mBfIRBuilder->AddBlock(eqBlock);
  18216. mModule->mBfIRBuilder->SetInsertPoint(eqBlock);
  18217. mModule->mBfIRBuilder->CreateBr(endBlock);
  18218. mModule->mBfIRBuilder->AddBlock(endBlock);
  18219. mModule->mBfIRBuilder->SetInsertPoint(endBlock);
  18220. auto phiVal = mModule->mBfIRBuilder->CreatePhi(mModule->mBfIRBuilder->MapType(intType), 3);
  18221. mModule->mBfIRBuilder->AddPhiIncoming(phiVal, mModule->mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, -1), startBlock);
  18222. mModule->mBfIRBuilder->AddPhiIncoming(phiVal, mModule->mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, 1), checkGtBlock);
  18223. mModule->mBfIRBuilder->AddPhiIncoming(phiVal, mModule->mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, 0), eqBlock);
  18224. mResult = BfTypedValue(phiVal, intType);
  18225. }
  18226. }
  18227. break;
  18228. default:
  18229. mModule->Fail("Invalid operation", opToken);
  18230. break;
  18231. }
  18232. }
  18233. void BfExprEvaluator::Visit(BfBinaryOperatorExpression* binOpExpr)
  18234. {
  18235. BfAutoParentNodeEntry autoParentNodeEntry(mModule, binOpExpr);
  18236. // There are a few binary operations that could actually be casts followed by an unary operation
  18237. // We can't determine that until we know whether the identifier in the parens is a typename or not
  18238. // (double)-1.0 (intptr)&val (BaseStruct)*val
  18239. BfUnaryOp unaryOp = BfUnaryOp_None;
  18240. switch (binOpExpr->mOp)
  18241. {
  18242. case BfBinaryOp_Add: unaryOp = BfUnaryOp_Positive; break;
  18243. case BfBinaryOp_Subtract: unaryOp = BfUnaryOp_Negate; break;
  18244. case BfBinaryOp_Multiply: unaryOp = BfUnaryOp_Dereference; break;
  18245. case BfBinaryOp_BitwiseAnd: unaryOp = BfUnaryOp_AddressOf; break;
  18246. default: break;
  18247. }
  18248. if (unaryOp != BfUnaryOp_None)
  18249. {
  18250. if (auto parenExpr = BfNodeDynCast<BfParenthesizedExpression>(binOpExpr->mLeft))
  18251. {
  18252. if (auto castTypeExpr = BfNodeDynCast<BfIdentifierNode>(parenExpr->mExpression))
  18253. {
  18254. SetAndRestoreValue<bool> prevIgnoreError(mModule->mIgnoreErrors, true);
  18255. auto resolvedType = mModule->ResolveTypeRef(castTypeExpr, NULL);
  18256. prevIgnoreError.Restore();
  18257. if (resolvedType != NULL)
  18258. {
  18259. if (auto rightBinOpExpr = BfNodeDynCast<BfBinaryOperatorExpression>(binOpExpr->mRight))
  18260. {
  18261. int leftPrecedence = BfGetBinaryOpPrecendence(binOpExpr->mOp);
  18262. int rightPrecedence = BfGetBinaryOpPrecendence(rightBinOpExpr->mOp);
  18263. // Do we have a precedence order issue due to mis-parsing this?
  18264. // An example is: "(int)-5.5 * 10"
  18265. if (rightPrecedence > leftPrecedence)
  18266. {
  18267. mModule->FailAfter("Cast target must be wrapped in parentheses", binOpExpr->mLeft);
  18268. }
  18269. }
  18270. PerformUnaryOperation(binOpExpr->mRight, unaryOp, binOpExpr->mOpToken, BfUnaryOpFlag_None);
  18271. if (mResult)
  18272. {
  18273. mResult = mModule->LoadValue(mResult);
  18274. mResult = mModule->Cast(binOpExpr, mResult, resolvedType, BfCastFlags_Explicit);
  18275. }
  18276. return;
  18277. }
  18278. }
  18279. }
  18280. }
  18281. if ((binOpExpr->mOp == BfBinaryOp_LeftShift) || (binOpExpr->mOp == BfBinaryOp_RightShift) ||
  18282. (binOpExpr->mOp == BfBinaryOp_BitwiseAnd) || (binOpExpr->mOp == BfBinaryOp_BitwiseOr) ||
  18283. (binOpExpr->mOp == BfBinaryOp_ExclusiveOr))
  18284. {
  18285. for (int side = 0; side < 2; side++)
  18286. {
  18287. if (auto innerBinOpExpr = BfNodeDynCast<BfBinaryOperatorExpression>((side == 0) ? binOpExpr->mLeft : binOpExpr->mRight))
  18288. {
  18289. if ((innerBinOpExpr->mOp == BfBinaryOp_Add) || (innerBinOpExpr->mOp == BfBinaryOp_Subtract))
  18290. {
  18291. mModule->Warn(BfWarning_C4554_PossiblePrecedenceError, "Check operator precedence for possible error. Consider using parentheses to clarify precedence", innerBinOpExpr);
  18292. }
  18293. }
  18294. }
  18295. }
  18296. if (binOpExpr->mRight == NULL)
  18297. {
  18298. // We visit the children for autocompletion only
  18299. if (binOpExpr->mLeft != NULL)
  18300. VisitChild(binOpExpr->mLeft);
  18301. if (mResult)
  18302. {
  18303. auto autoComplete = GetAutoComplete();
  18304. if (autoComplete != NULL)
  18305. autoComplete->CheckEmptyStart(binOpExpr->mOpToken, mResult.mType);
  18306. }
  18307. if (binOpExpr->mRight != NULL)
  18308. VisitChild(binOpExpr->mRight);
  18309. return;
  18310. }
  18311. PerformBinaryOperation(binOpExpr->mLeft, binOpExpr->mRight, binOpExpr->mOp, binOpExpr->mOpToken, BfBinOpFlag_None);
  18312. }