BfExprEvaluator.cpp 612 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137
  1. #pragma warning(push)
  2. #pragma warning(disable:4800)
  3. #pragma warning(disable:4244)
  4. #pragma warning(disable:4141)
  5. #pragma warning(disable:4624)
  6. #pragma warning(disable:4146)
  7. #pragma warning(disable:4267)
  8. #pragma warning(disable:4291)
  9. #include "BfExprEvaluator.h"
  10. #include "BfConstResolver.h"
  11. #include "BfAutoComplete.h"
  12. #include "BeefySysLib/util/PerfTimer.h"
  13. #include "BeefySysLib/util/BeefPerf.h"
  14. #include "BfParser.h"
  15. #include "BfMangler.h"
  16. #include "BfResolvePass.h"
  17. #include "BfUtil.h"
  18. #include "BfDeferEvalChecker.h"
  19. #include "BfVarDeclChecker.h"
  20. #pragma warning(pop)
  21. #include "BeefySysLib/util/AllocDebug.h"
  22. USING_NS_BF;
  23. using namespace llvm;
  24. //////////////////////////////////////////////////////////////////////////
  25. DeferredTupleAssignData::~DeferredTupleAssignData()
  26. {
  27. for (auto entry : mChildren)
  28. {
  29. delete entry.mExprEvaluator;
  30. delete entry.mInnerTuple;
  31. }
  32. }
  33. //////////////////////////////////////////////////////////////////////////
  34. BfBaseClassWalker::BfBaseClassWalker(BfType* typeA, BfType* typeB, BfModule* module)
  35. {
  36. mMayBeFromInterface = false;
  37. if ((typeA != NULL) && (!typeA->IsInterface()))
  38. mTypes[0] = typeA->ToTypeInstance();
  39. else
  40. mTypes[0] = NULL;
  41. if ((typeB != NULL) && (!typeB->IsInterface()))
  42. mTypes[1] = typeB->ToTypeInstance();
  43. else
  44. mTypes[1] = NULL;
  45. if ((typeA != NULL) && (typeA->IsGenericParam()))
  46. {
  47. mMayBeFromInterface = true;
  48. AddConstraints(typeA, module->GetGenericParamInstance((BfGenericParamType*)typeA));
  49. }
  50. if ((typeB != NULL) && (typeB->IsGenericParam()))
  51. {
  52. mMayBeFromInterface = true;
  53. AddConstraints(typeB, module->GetGenericParamInstance((BfGenericParamType*)typeB));
  54. }
  55. }
  56. /*BfBaseClassWalker::BfBaseClassWalker(BfTypeInstance* typeA, BfTypeInstance* typeB)
  57. {
  58. mTypes[0] = typeA;
  59. mTypes[1] = typeB;
  60. }*/
  61. BfBaseClassWalker::BfBaseClassWalker()
  62. {
  63. mMayBeFromInterface = false;
  64. mTypes[0] = NULL;
  65. mTypes[1] = NULL;
  66. }
  67. void BfBaseClassWalker::AddConstraints(BfType* srcType, BfGenericParamInstance* genericParam)
  68. {
  69. if (genericParam->mTypeConstraint != NULL)
  70. {
  71. auto typeInst = genericParam->mTypeConstraint->ToTypeInstance();
  72. {
  73. Entry entry(srcType, typeInst);
  74. if ((typeInst != NULL) && (!mManualList.Contains(entry)))
  75. mManualList.Add(entry);
  76. }
  77. }
  78. for (auto typeInst : genericParam->mInterfaceConstraints)
  79. {
  80. Entry entry(srcType, typeInst);
  81. if ((typeInst != NULL) && (!mManualList.Contains(entry)))
  82. mManualList.Add(entry);
  83. }
  84. }
  85. BfBaseClassWalker::Entry BfBaseClassWalker::Next()
  86. {
  87. if (!mManualList.IsEmpty())
  88. {
  89. auto entry = mManualList.back();
  90. mManualList.pop_back();
  91. return entry;
  92. }
  93. // Check the most specific type instance first (highest inheritance level)
  94. auto checkInstance = mTypes[0];
  95. if (mTypes[0] == NULL)
  96. checkInstance = mTypes[1];
  97. else if ((mTypes[1] != NULL) && (mTypes[1]->mInheritDepth > mTypes[0]->mInheritDepth))
  98. checkInstance = mTypes[1];
  99. if (checkInstance == NULL)
  100. return Entry();
  101. // Do it this was so if we reach the same base class for both types that we only handle each base type once
  102. if (checkInstance == mTypes[0])
  103. mTypes[0] = checkInstance->mBaseType;
  104. if (checkInstance == mTypes[1])
  105. mTypes[1] = checkInstance->mBaseType;
  106. Entry entry;
  107. entry.mSrcType = checkInstance;
  108. entry.mTypeInstance = checkInstance;
  109. return entry;
  110. }
  111. //////////////////////////////////////////////////////////////////////////
  112. BfMethodMatcher::BfMethodMatcher(BfAstNode* targetSrc, BfModule* module, const StringImpl& methodName, SizedArrayImpl<BfResolvedArg>& arguments, BfSizedArray<ASTREF(BfTypeReference*)>* methodGenericArguments) :
  113. mArguments(arguments)
  114. {
  115. mTargetSrc = targetSrc;
  116. mModule = module;
  117. mMethodName = methodName;
  118. Init(/*arguments, */methodGenericArguments);
  119. }
  120. BfMethodMatcher::BfMethodMatcher(BfAstNode* targetSrc, BfModule* module, BfMethodInstance* interfaceMethodInstance, SizedArrayImpl<BfResolvedArg>& arguments, BfSizedArray<ASTREF(BfTypeReference*)>* methodGenericArguments) :
  121. mArguments(arguments)
  122. {
  123. mTargetSrc = targetSrc;
  124. mModule = module;
  125. Init(/*arguments, */methodGenericArguments);
  126. mInterfaceMethodInstance = interfaceMethodInstance;
  127. mMethodName = mInterfaceMethodInstance->mMethodDef->mName;
  128. }
  129. void BfMethodMatcher::Init(/*SizedArrayImpl<BfResolvedArg>& arguments, */BfSizedArray<ASTREF(BfTypeReference*)>* methodGenericArguments)
  130. {
  131. //mArguments = arguments;
  132. mActiveTypeDef = NULL;
  133. mBestMethodDef = NULL;
  134. mBackupMethodDef = NULL;
  135. mBestMethodTypeInstance = NULL;
  136. mExplicitInterfaceCheck = NULL;
  137. mSelfType = NULL;
  138. mMethodType = BfMethodType_Normal;
  139. mHadExplicitGenericArguments = false;
  140. mHasVarArguments = false;
  141. mInterfaceMethodInstance = NULL;
  142. mFakeConcreteTarget = false;
  143. mBypassVirtual = false;
  144. mAllowStatic = true;
  145. mAllowNonStatic = true;
  146. mSkipImplicitParams = false;
  147. mAllowImplicitThis = false;
  148. mMethodCheckCount = 0;
  149. mInferGenericProgressIdx = 0;
  150. mCheckedKind = BfCheckedKind_NotSet;
  151. mMatchFailKind = MatchFailKind_None;
  152. for (auto& arg : mArguments)
  153. {
  154. auto bfType = arg.mTypedValue.mType;
  155. if (bfType != NULL)
  156. mHasVarArguments |= bfType->IsVar();
  157. }
  158. if (methodGenericArguments != NULL)
  159. {
  160. for (BfTypeReference* genericArg : *methodGenericArguments)
  161. {
  162. auto genericArgType = mModule->ResolveTypeRef(genericArg);
  163. // if (genericArgType == NULL)
  164. // return;
  165. mExplicitMethodGenericArguments.push_back(genericArgType);
  166. }
  167. mHadExplicitGenericArguments = true;
  168. }
  169. }
  170. bool BfMethodMatcher::IsMemberAccessible(BfTypeInstance* typeInst, BfTypeDef* declaringType)
  171. {
  172. if (mActiveTypeDef == NULL)
  173. mActiveTypeDef = mModule->GetActiveTypeDef();
  174. if (!typeInst->IsTypeMemberIncluded(declaringType, mActiveTypeDef, mModule))
  175. return false;
  176. // This may not be completely correct - BUT if we don't have this then even Dictionary TKey's operator == won't be considered accessible
  177. if (!mModule->IsInSpecializedSection())
  178. {
  179. if (!typeInst->IsTypeMemberAccessible(declaringType, mActiveTypeDef))
  180. return false;
  181. }
  182. return true;
  183. }
  184. bool BfMethodMatcher::InferGenericArgument(BfMethodInstance* methodInstance, BfType* argType, BfType* wantType, BfIRValue argValue)
  185. {
  186. if (argType == NULL)
  187. return false;
  188. if (argType->IsVar())
  189. return false;
  190. if (wantType->IsGenericParam())
  191. {
  192. auto wantGenericParam = (BfGenericParamType*)wantType;
  193. BfType* methodGenericTypeConstraint = NULL;
  194. auto _SetGeneric = [&]()
  195. {
  196. if (mCheckMethodGenericArguments[wantGenericParam->mGenericParamIdx] != argType)
  197. {
  198. if (methodGenericTypeConstraint != NULL)
  199. {
  200. if (methodGenericTypeConstraint->IsGenericTypeInstance())
  201. {
  202. auto wantGenericType = (BfGenericTypeInstance*)methodGenericTypeConstraint;
  203. auto checkArgType = argType;
  204. while (checkArgType != NULL)
  205. {
  206. if (checkArgType->IsGenericTypeInstance())
  207. {
  208. auto argGenericType = (BfGenericTypeInstance*)checkArgType;
  209. if (argGenericType->mTypeDef == wantGenericType->mTypeDef)
  210. {
  211. for (int genericArgIdx = 0; genericArgIdx < (int)argGenericType->mTypeGenericArguments.size(); genericArgIdx++)
  212. InferGenericArgument(methodInstance, argGenericType->mTypeGenericArguments[genericArgIdx], wantGenericType->mTypeGenericArguments[genericArgIdx], BfIRValue());
  213. }
  214. }
  215. else if (checkArgType->IsSizedArray())
  216. {
  217. auto sizedArrayType = (BfSizedArrayType*)checkArgType;
  218. if (wantGenericType->mTypeDef == mModule->mCompiler->mSizedArrayTypeDef)
  219. {
  220. InferGenericArgument(methodInstance, sizedArrayType->mElementType, wantGenericType->mTypeGenericArguments[0], BfIRValue());
  221. auto intType = mModule->GetPrimitiveType(BfTypeCode_IntPtr);
  222. BfTypedValue arraySize = BfTypedValue(mModule->mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, (uint64)sizedArrayType->mElementCount), intType);
  223. InferGenericArgument(methodInstance, mModule->CreateConstExprValueType(arraySize), wantGenericType->mTypeGenericArguments[1], BfIRValue());
  224. }
  225. }
  226. else if (checkArgType->IsPointer())
  227. {
  228. auto pointerType = (BfPointerType*)checkArgType;
  229. if (wantGenericType->mTypeDef == mModule->mCompiler->mPointerTTypeDef)
  230. {
  231. InferGenericArgument(methodInstance, pointerType->mElementType, wantGenericType->mTypeGenericArguments[0], BfIRValue());
  232. }
  233. }
  234. auto checkTypeInst = checkArgType->ToTypeInstance();
  235. if ((checkTypeInst == NULL) || (!checkTypeInst->mHasParameterizedBase))
  236. break;
  237. checkArgType = checkTypeInst->mBaseType;
  238. }
  239. }
  240. }
  241. mInferGenericProgressIdx++;
  242. mCheckMethodGenericArguments[wantGenericParam->mGenericParamIdx] = argType;
  243. }
  244. mCheckMethodGenericArguments[wantGenericParam->mGenericParamIdx] = argType;
  245. mPrevArgValues[wantGenericParam->mGenericParamIdx] = argValue;
  246. };
  247. if (wantGenericParam->mGenericParamKind == BfGenericParamKind_Method)
  248. {
  249. auto genericParamInst = methodInstance->mMethodInfoEx->mGenericParams[wantGenericParam->mGenericParamIdx];
  250. methodGenericTypeConstraint = genericParamInst->mTypeConstraint;
  251. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_Const) != 0)
  252. {
  253. if (argValue.IsConst())
  254. {
  255. argType = mModule->CreateConstExprValueType(BfTypedValue(argValue, argType));
  256. }
  257. else if (!argType->IsConstExprValue())
  258. {
  259. return false;
  260. }
  261. }
  262. if (argType == mModule->mContext->mBfObjectType)
  263. {
  264. if ((genericParamInst->mTypeConstraint != NULL) && (genericParamInst->mTypeConstraint->IsDelegate()))
  265. {
  266. argType = genericParamInst->mTypeConstraint;
  267. }
  268. }
  269. auto prevGenericMethodArg = mCheckMethodGenericArguments[wantGenericParam->mGenericParamIdx];
  270. auto prevArgValue = mPrevArgValues[wantGenericParam->mGenericParamIdx];
  271. if (prevGenericMethodArg == NULL)
  272. {
  273. _SetGeneric();
  274. return true;
  275. }
  276. if ((prevGenericMethodArg->IsIntUnknown()) && (!argType->IsIntUnknown()))
  277. {
  278. // Old int fits into new argType, that's good
  279. if (mModule->CanImplicitlyCast(BfTypedValue(prevArgValue, prevGenericMethodArg), argType))
  280. {
  281. _SetGeneric();
  282. return true;
  283. }
  284. // Doesn't fit, upgrade type to 'int'
  285. argType = mModule->GetPrimitiveType(BfTypeCode_IntPtr);
  286. if (mModule->CanImplicitlyCast(BfTypedValue(prevArgValue, prevGenericMethodArg), argType))
  287. {
  288. _SetGeneric();
  289. return true;
  290. }
  291. }
  292. if (argType->IsIntUnknown())
  293. {
  294. // New int fits into previous arg type, that's good
  295. if (mModule->CanImplicitlyCast(BfTypedValue(argValue, argType), prevGenericMethodArg))
  296. return true;
  297. // Doesn't fit, upgrade type to 'int'
  298. argType = mModule->GetPrimitiveType(BfTypeCode_IntPtr);
  299. }
  300. else
  301. {
  302. // Prev is already best
  303. if (mModule->CanImplicitlyCast(mModule->GetFakeTypedValue(argType), prevGenericMethodArg))
  304. return true;
  305. }
  306. // New best?
  307. if (mModule->CanImplicitlyCast(mModule->GetFakeTypedValue(prevGenericMethodArg), argType))
  308. {
  309. _SetGeneric();
  310. return true;
  311. }
  312. // No implicit conversion, FAIL!
  313. mCheckMethodGenericArguments[wantGenericParam->mGenericParamIdx] = NULL;
  314. return false;
  315. }
  316. return true;
  317. }
  318. if (wantType->IsGenericTypeInstance())
  319. {
  320. auto wantGenericType = (BfGenericTypeInstance*)wantType;
  321. if (!argType->IsGenericTypeInstance())
  322. return true;
  323. auto argGenericType = (BfGenericTypeInstance*)argType;
  324. if (argGenericType->mTypeDef != wantGenericType->mTypeDef)
  325. return true;
  326. for (int genericArgIdx = 0; genericArgIdx < (int)argGenericType->mTypeGenericArguments.size(); genericArgIdx++)
  327. InferGenericArgument(methodInstance, argGenericType->mTypeGenericArguments[genericArgIdx], wantGenericType->mTypeGenericArguments[genericArgIdx], BfIRValue());
  328. return true;
  329. }
  330. if (wantType->IsRef())
  331. {
  332. auto wantRefType = (BfRefType*)wantType;
  333. if (!argType->IsRef())
  334. {
  335. // Match to non-ref
  336. InferGenericArgument(methodInstance, argType, wantRefType->mElementType, BfIRValue());
  337. return true;
  338. }
  339. auto argRefType = (BfRefType*)argType;
  340. //TODO: We removed this check so we still infer even if we have the wrong ref kind
  341. //if (wantRefType->mRefKind != argRefType->mRefKind)
  342. //return true;
  343. InferGenericArgument(methodInstance, argRefType->mElementType, wantRefType->mElementType, BfIRValue());
  344. return true;
  345. }
  346. if (wantType->IsPointer())
  347. {
  348. if (!argType->IsPointer())
  349. return true;
  350. auto wantPointerType = (BfPointerType*) wantType;
  351. auto argPointerType = (BfPointerType*) argType;
  352. InferGenericArgument(methodInstance, argPointerType->mElementType, wantPointerType->mElementType, BfIRValue());
  353. return true;
  354. }
  355. if (wantType->IsUnknownSizedArray())
  356. {
  357. auto wantArrayType = (BfUnknownSizedArrayType*)wantType;
  358. if (argType->IsUnknownSizedArray())
  359. {
  360. auto argArrayType = (BfUnknownSizedArrayType*)argType;
  361. InferGenericArgument(methodInstance, argArrayType->mElementCountSource, wantArrayType->mElementCountSource, BfIRValue());
  362. }
  363. else if (argType->IsSizedArray())
  364. {
  365. auto argArrayType = (BfSizedArrayType*)argType;
  366. BfTypedValue sizeValue(mModule->GetConstValue(argArrayType->mElementCount), mModule->GetPrimitiveType(BfTypeCode_IntPtr));
  367. auto sizedType = mModule->CreateConstExprValueType(sizeValue);
  368. InferGenericArgument(methodInstance, sizedType, wantArrayType->mElementCountSource, BfIRValue());
  369. }
  370. }
  371. if (wantType->IsSizedArray())
  372. {
  373. if (argType->IsSizedArray())
  374. {
  375. auto wantArrayType = (BfSizedArrayType*)wantType;
  376. auto argArrayType = (BfSizedArrayType*)argType;
  377. InferGenericArgument(methodInstance, argArrayType->mElementType, wantArrayType->mElementType, BfIRValue());
  378. }
  379. }
  380. return true;
  381. }
  382. void BfMethodMatcher::CompareMethods(BfMethodInstance* prevMethodInstance, BfTypeVector* prevGenericArgumentsSubstitute,
  383. BfMethodInstance* newMethodInstance, BfTypeVector* genericArgumentsSubstitute,
  384. bool* outNewIsBetter, bool* outNewIsWorse, bool allowSpecializeFail)
  385. {
  386. #define SET_BETTER_OR_WORSE(lhs, rhs) \
  387. if ((!isBetter) && (lhs) && !(rhs)) isBetter = true; \
  388. if ((!isWorse) && !(lhs) && (rhs)) isWorse = true;
  389. #define RETURN_BETTER_OR_WORSE(lhs, rhs) \
  390. if ((!isBetter) && (lhs) && !(rhs)) { *outNewIsBetter = true; *outNewIsWorse = false; return; } \
  391. if ((!isWorse) && !(lhs) && (rhs)) { *outNewIsBetter = false; *outNewIsWorse = true; return; };
  392. #define RETURN_RESULTS \
  393. *outNewIsBetter = isBetter; \
  394. *outNewIsWorse = isWorse; \
  395. return;
  396. int numUsedParams = 0;
  397. int prevNumUsedParams = 0;
  398. bool usedExtendedForm = false;
  399. bool prevUsedExtendedForm = false;
  400. bool isBetter = false;
  401. bool isWorse = false;
  402. int argIdx;
  403. BfMethodDef* prevMethodDef = prevMethodInstance->mMethodDef;
  404. BfMethodDef* newMethodDef = newMethodInstance->mMethodDef;
  405. if (newMethodDef->mExplicitInterface != prevMethodDef->mExplicitInterface)
  406. {
  407. if (mModule->CompareMethodSignatures(newMethodInstance, prevMethodInstance))
  408. {
  409. SET_BETTER_OR_WORSE(newMethodDef->mExplicitInterface != NULL, prevMethodDef->mExplicitInterface != NULL);
  410. *outNewIsBetter = isBetter;
  411. *outNewIsWorse = isWorse;
  412. return;
  413. }
  414. }
  415. int newImplicitParamCount = newMethodInstance->GetImplicitParamCount();
  416. if (newMethodInstance->mMethodDef->mHasAppend)
  417. newImplicitParamCount++;
  418. int prevImplicitParamCount = prevMethodInstance->GetImplicitParamCount();
  419. if (prevMethodInstance->mMethodDef->mHasAppend)
  420. prevImplicitParamCount++;
  421. bool hadEnoughArgs = newMethodInstance->GetParamCount() - newImplicitParamCount < (int)mArguments.size();
  422. bool prevHadEnoughArgs = prevMethodInstance->GetParamCount() - prevImplicitParamCount < (int)mArguments.size();
  423. RETURN_BETTER_OR_WORSE(hadEnoughArgs, prevHadEnoughArgs);
  424. bool chainSkip = (newMethodInstance->mChainType == BfMethodChainType_ChainMember) || (newMethodInstance->mChainType == BfMethodChainType_ChainSkip);
  425. bool prevChainSkip = (prevMethodInstance->mChainType == BfMethodChainType_ChainMember) || (prevMethodInstance->mChainType == BfMethodChainType_ChainSkip);
  426. RETURN_BETTER_OR_WORSE(!chainSkip, !prevChainSkip);
  427. // If one of these methods is local to the current extension then choose that one
  428. auto activeDef = mModule->GetActiveTypeDef();
  429. RETURN_BETTER_OR_WORSE(newMethodDef->mDeclaringType == activeDef, prevMethodDef->mDeclaringType == activeDef);
  430. RETURN_BETTER_OR_WORSE(newMethodDef->mDeclaringType->IsExtension(), prevMethodDef->mDeclaringType->IsExtension());
  431. if ((!isBetter) && (!isWorse))
  432. {
  433. bool betterByGenericParam = false;
  434. bool worseByGenericParam = false;
  435. for (argIdx = 0; argIdx < (int)mArguments.size(); argIdx++)
  436. {
  437. BfResolvedArg resolvedArg = mArguments[argIdx];;
  438. BfTypedValue arg = resolvedArg.mTypedValue;
  439. int newArgIdx = argIdx + newImplicitParamCount;
  440. int prevArgIdx = argIdx + prevImplicitParamCount;
  441. bool wasGenericParam = newMethodInstance->WasGenericParam(newArgIdx);
  442. bool prevWasGenericParam = prevMethodInstance->WasGenericParam(prevArgIdx);
  443. BfType* paramType = newMethodInstance->GetParamType(newArgIdx);
  444. BfType* prevParamType = prevMethodInstance->GetParamType(prevArgIdx);
  445. numUsedParams++;
  446. prevNumUsedParams++;
  447. BfType* origParamType = paramType;
  448. BfType* origPrevParamType = prevParamType;
  449. if ((genericArgumentsSubstitute != NULL) && (paramType->IsUnspecializedType()))
  450. paramType = mModule->ResolveGenericType(paramType, *genericArgumentsSubstitute, allowSpecializeFail);
  451. if ((prevGenericArgumentsSubstitute != NULL) && (prevParamType->IsUnspecializedType()))
  452. prevParamType = mModule->ResolveGenericType(prevParamType, *prevGenericArgumentsSubstitute, allowSpecializeFail);
  453. if ((wasGenericParam) || (prevWasGenericParam))
  454. {
  455. if ((wasGenericParam) && (!prevWasGenericParam))
  456. worseByGenericParam = true;
  457. else if ((!wasGenericParam) && (prevWasGenericParam))
  458. betterByGenericParam = true;
  459. }
  460. if ((prevParamType == NULL) || (paramType == NULL))
  461. {
  462. SET_BETTER_OR_WORSE(paramType != NULL, prevParamType != NULL);
  463. }
  464. else if (paramType != prevParamType)
  465. {
  466. bool isUnspecializedParam = paramType->IsUnspecializedType();
  467. bool isPrevUnspecializedParam = prevParamType->IsUnspecializedType();
  468. SET_BETTER_OR_WORSE((!isUnspecializedParam) && (!paramType->IsVar()),
  469. (!isPrevUnspecializedParam) && (!prevParamType->IsVar()));
  470. if ((!isBetter) && (!isWorse))
  471. SET_BETTER_OR_WORSE(paramType->IsConstExprValue(), prevParamType->IsConstExprValue());
  472. if ((!isBetter) && (!isWorse) && (!isUnspecializedParam) && (!isPrevUnspecializedParam))
  473. {
  474. SET_BETTER_OR_WORSE((paramType != NULL) && (!paramType->IsUnspecializedType()),
  475. (prevParamType != NULL) && (!prevParamType->IsUnspecializedType()));
  476. if ((!isBetter) && (!isWorse))
  477. {
  478. // The resolved argument type may actually match for both considered functions. IE:
  479. // Method(int8 val) and Method(int16 val) called with Method(0) will create arguments that match their param types
  480. if ((paramType == arg.mType) && (prevParamType != resolvedArg.mBestBoundType))
  481. isBetter = true;
  482. else if ((prevParamType == arg.mType) && (paramType != arg.mType))
  483. isWorse = true;
  484. else
  485. {
  486. bool canCastFromCurToPrev = mModule->CanImplicitlyCast(mModule->GetFakeTypedValue(paramType), prevParamType);
  487. bool canCastFromPrevToCur = mModule->CanImplicitlyCast(mModule->GetFakeTypedValue(prevParamType), paramType);
  488. if ((canCastFromCurToPrev) && (!canCastFromPrevToCur))
  489. isBetter = true;
  490. else if ((canCastFromPrevToCur) && (!canCastFromCurToPrev))
  491. isWorse = true;
  492. else if ((paramType->IsIntegral()) && (prevParamType->IsIntegral()))
  493. {
  494. if (paramType == arg.mType)
  495. isBetter = true;
  496. else if (prevParamType == arg.mType)
  497. isWorse = true;
  498. else
  499. {
  500. if (paramType->mSize < prevParamType->mSize)
  501. isBetter = true;
  502. else if (paramType->mSize > prevParamType->mSize)
  503. isWorse = true;
  504. else if (paramType->IsSigned())
  505. isBetter = true;
  506. else
  507. isWorse = true;
  508. }
  509. }
  510. }
  511. /*if ((paramType->IsIntegral()) && (prevParamType->IsIntegral()))
  512. {
  513. if (paramType == arg.mType)
  514. isBetter = true;
  515. else if (prevParamType == arg.mType)
  516. isWorse = true;
  517. else
  518. {
  519. if (paramType->mSize < prevParamType->mSize)
  520. isBetter = true;
  521. else if (paramType->mSize > prevParamType->mSize)
  522. isWorse = true;
  523. else if (paramType->IsSigned())
  524. isBetter = true;
  525. else
  526. isWorse = true;
  527. }
  528. }
  529. else
  530. {
  531. if (mModule->CanImplicitlyCast(mModule->GetFakeTypedValue(paramType), prevParamType))
  532. isBetter = true;
  533. if (mModule->CanImplicitlyCast(mModule->GetFakeTypedValue(prevParamType), paramType))
  534. isWorse = true;
  535. }*/
  536. }
  537. }
  538. }
  539. else if ((wasGenericParam) || (prevWasGenericParam))
  540. {
  541. if (!wasGenericParam)
  542. isBetter = true;
  543. else if (!prevWasGenericParam)
  544. isWorse = true;
  545. }
  546. if (newMethodInstance->GetParamKind(newArgIdx) == BfParamKind_Params)
  547. usedExtendedForm = true;
  548. if (prevMethodInstance->GetParamKind(prevArgIdx) == BfParamKind_Params)
  549. prevUsedExtendedForm = true;
  550. if ((usedExtendedForm) || (prevUsedExtendedForm))
  551. break;
  552. }
  553. if ((!isBetter) && (!isWorse))
  554. {
  555. isBetter = betterByGenericParam;
  556. isWorse = worseByGenericParam;
  557. }
  558. if ((isBetter) || (isWorse))
  559. {
  560. RETURN_RESULTS;
  561. }
  562. }
  563. // Check for unused extended params as next param - that still counts as using extended form
  564. usedExtendedForm = newMethodInstance->HasParamsArray();
  565. prevUsedExtendedForm = prevMethodInstance->HasParamsArray();
  566. // Non-generic is better than generic.
  567. // The only instance where we can disambiguate is when we have the same number of generic arguments, and the
  568. // constraints for one method's generic argument is a superset of another's. More specific is better.
  569. //TODO: WE changed this to compare the constraints of the ARGUMENTS
  570. // if (newMethodInstance->GetNumGenericArguments() == prevMethodInstance->GetNumGenericArguments())
  571. // {
  572. // if (newMethodInstance->GetNumGenericArguments() != 0)
  573. // {
  574. // for (int genericIdx = 0; genericIdx < (int)newMethodInstance->mMethodInfoEx->mMethodGenericArguments.size(); genericIdx++)
  575. // {
  576. // auto newMethodGenericParam = newMethodInstance->mMethodInfoEx->mGenericParams[genericIdx];
  577. // auto prevMethodGenericParam = prevMethodInstance->mMethodInfoEx->mGenericParams[genericIdx];
  578. // RETURN_BETTER_OR_WORSE(mModule->AreConstraintsSubset(prevMethodGenericParam, newMethodGenericParam), mModule->AreConstraintsSubset(newMethodGenericParam, prevMethodGenericParam));
  579. // }
  580. // }
  581. // }
  582. // else
  583. RETURN_BETTER_OR_WORSE(newMethodInstance->GetNumGenericArguments() == 0, prevMethodInstance->GetNumGenericArguments() == 0);
  584. // Not using generic delegate params is better
  585. RETURN_BETTER_OR_WORSE(!newMethodInstance->mHadGenericDelegateParams, !prevMethodInstance->mHadGenericDelegateParams);
  586. // Normal form trumps extended form
  587. RETURN_BETTER_OR_WORSE(!usedExtendedForm, !prevUsedExtendedForm);
  588. // More used params trumps less params
  589. int paramDiff = (int) numUsedParams - (int) prevNumUsedParams;
  590. RETURN_BETTER_OR_WORSE(paramDiff > 0, paramDiff < 0);
  591. // Fewer defaults trumps more defaults
  592. // Since we know the number of used params is the same (previous check), we infer that the rest are defaults
  593. paramDiff = (int) newMethodInstance->GetParamCount() - (int) prevMethodInstance->GetParamCount();
  594. RETURN_BETTER_OR_WORSE(paramDiff < 0, paramDiff > 0);
  595. // Check specificity of args
  596. std::function<void(BfType*, BfType*)> _CompareParamTypes = [&](BfType* newType, BfType* prevType)
  597. {
  598. if ((newType->IsGenericParam()) && (prevType->IsGenericParam()))
  599. {
  600. auto newGenericParamType = (BfGenericParamType*)newType;
  601. auto prevGenericParamType = (BfGenericParamType*)prevType;
  602. if ((newGenericParamType->mGenericParamKind == BfGenericParamKind_Method) && (prevGenericParamType->mGenericParamKind == BfGenericParamKind_Method))
  603. {
  604. auto newMethodGenericParam = newMethodInstance->mMethodInfoEx->mGenericParams[newGenericParamType->mGenericParamIdx];
  605. auto prevMethodGenericParam = prevMethodInstance->mMethodInfoEx->mGenericParams[prevGenericParamType->mGenericParamIdx];
  606. SET_BETTER_OR_WORSE(mModule->AreConstraintsSubset(prevMethodGenericParam, newMethodGenericParam), mModule->AreConstraintsSubset(newMethodGenericParam, prevMethodGenericParam));
  607. }
  608. }
  609. else if (newType == prevType)
  610. {
  611. if ((newType->IsUnspecializedType()) && (newType->IsGenericTypeInstance()))
  612. {
  613. BfGenericTypeInstance* newGenericType = (BfGenericTypeInstance*)newType;
  614. BfGenericTypeInstance* prevGenericType = (BfGenericTypeInstance*)prevType;
  615. for (int genericArgIdx = 0; genericArgIdx < (int)newGenericType->mTypeGenericArguments.size(); genericArgIdx++)
  616. {
  617. _CompareParamTypes(newGenericType->mTypeGenericArguments[genericArgIdx], prevGenericType->mTypeGenericArguments[genericArgIdx]);
  618. }
  619. }
  620. }
  621. else
  622. {
  623. //TODO: Why did we need this?
  624. //isBetter |= mModule->IsTypeMoreSpecific(newType, prevType);
  625. //isWorse |= mModule->IsTypeMoreSpecific(prevType, newType);
  626. }
  627. };
  628. int paramCheckCount = (int)BF_MIN(newMethodInstance->GetParamCount() - newImplicitParamCount, prevMethodInstance->GetParamCount() - prevImplicitParamCount);
  629. for (argIdx = 0; argIdx < (int)paramCheckCount/*mArguments.size()*/; argIdx++)
  630. {
  631. int newArgIdx = argIdx + newImplicitParamCount;
  632. int prevArgIdx = argIdx + prevImplicitParamCount;
  633. _CompareParamTypes(newMethodInstance->GetParamType(newArgIdx), prevMethodInstance->GetParamType(prevArgIdx));
  634. }
  635. // Do generic constraint subset test directly to handle cases like "NotDisposed<T>()" vs "NOtDisposed<T>() where T : IDisposable"
  636. if ((newMethodInstance->GetNumGenericArguments() > 0) && (newMethodInstance->GetNumGenericArguments() == prevMethodInstance->GetNumGenericArguments()))
  637. {
  638. for (int genericParamIdx = 0; genericParamIdx < (int)newMethodInstance->GetNumGenericArguments(); genericParamIdx++)
  639. {
  640. auto newMethodGenericParam = newMethodInstance->mMethodInfoEx->mGenericParams[genericParamIdx];
  641. auto prevMethodGenericParam = prevMethodInstance->mMethodInfoEx->mGenericParams[genericParamIdx];
  642. SET_BETTER_OR_WORSE(mModule->AreConstraintsSubset(prevMethodGenericParam, newMethodGenericParam), mModule->AreConstraintsSubset(newMethodGenericParam, prevMethodGenericParam));
  643. }
  644. }
  645. if ((isBetter) || (isWorse))
  646. {
  647. RETURN_RESULTS;
  648. }
  649. // Does one have a body and one doesn't? Obvious!
  650. isBetter = prevMethodDef->IsEmptyPartial();
  651. isWorse = newMethodDef->IsEmptyPartial();
  652. if ((isBetter) && (isWorse))
  653. {
  654. // If both are empty partials then just bind to either
  655. isWorse = true;
  656. RETURN_RESULTS;
  657. }
  658. // For operators, prefer explicit comparison over '<=>' comparison operator
  659. if ((!isBetter) && (!isWorse))
  660. {
  661. if ((prevMethodDef->mIsOperator) && (newMethodDef->mIsOperator))
  662. {
  663. bool newIsComparison = ((BfOperatorDeclaration*)newMethodDef->mMethodDeclaration)->mBinOp == BfBinaryOp_Compare;
  664. bool prevIsComparison = ((BfOperatorDeclaration*)prevMethodDef->mMethodDeclaration)->mBinOp == BfBinaryOp_Compare;
  665. RETURN_BETTER_OR_WORSE(!newIsComparison, !prevIsComparison);
  666. }
  667. }
  668. // For extensions, select the version in the most-specific project (only applicable for ctors)
  669. if ((!isBetter) && (!isWorse))
  670. {
  671. auto newProject = newMethodDef->mDeclaringType->mProject;
  672. auto prevProject = prevMethodDef->mDeclaringType->mProject;
  673. if (newProject != prevProject)
  674. {
  675. RETURN_BETTER_OR_WORSE(newProject->ContainsReference(prevProject), prevProject->ContainsReference(newProject));
  676. }
  677. }
  678. // If we have conditional type extensions that both define an implementation for a method, use the most-specific conditional extension constraints
  679. auto owner = newMethodInstance->GetOwner();
  680. if ((newMethodDef->mDeclaringType != prevMethodDef->mDeclaringType) && (owner->IsGenericTypeInstance()))
  681. {
  682. auto genericOwner = (BfGenericTypeInstance*)owner;
  683. if (genericOwner->mGenericExtensionInfo != NULL)
  684. {
  685. BfGenericExtensionEntry* newGenericExtesionEntry = NULL;
  686. BfGenericExtensionEntry* prevGenericExtesionEntry = NULL;
  687. if ((genericOwner->mGenericExtensionInfo->mExtensionMap.TryGetValue(newMethodDef->mDeclaringType, &newGenericExtesionEntry)) &&
  688. (genericOwner->mGenericExtensionInfo->mExtensionMap.TryGetValue(prevMethodDef->mDeclaringType, &prevGenericExtesionEntry)))
  689. {
  690. if ((newGenericExtesionEntry->mGenericParams.size() == prevGenericExtesionEntry->mGenericParams.size()))
  691. {
  692. for (int genericParamIdx = 0; genericParamIdx < (int)newGenericExtesionEntry->mGenericParams.size(); genericParamIdx++)
  693. {
  694. auto newMethodGenericParam = newGenericExtesionEntry->mGenericParams[genericParamIdx];
  695. auto prevMethodGenericParam = prevGenericExtesionEntry->mGenericParams[genericParamIdx];
  696. SET_BETTER_OR_WORSE(mModule->AreConstraintsSubset(prevMethodGenericParam, newMethodGenericParam), mModule->AreConstraintsSubset(newMethodGenericParam, prevMethodGenericParam));
  697. }
  698. }
  699. if ((isBetter) || (isWorse))
  700. {
  701. RETURN_RESULTS;
  702. }
  703. }
  704. }
  705. }
  706. RETURN_BETTER_OR_WORSE(newMethodDef->mCheckedKind == mCheckedKind, prevMethodDef->mCheckedKind == mCheckedKind);
  707. RETURN_BETTER_OR_WORSE(newMethodDef->mCommutableKind != BfCommutableKind_Reverse, prevMethodDef->mCommutableKind != BfCommutableKind_Reverse);
  708. RETURN_RESULTS;
  709. }
  710. BfTypedValue BfMethodMatcher::ResolveArgTypedValue(BfResolvedArg& resolvedArg, BfType* checkType, BfTypeVector* genericArgumentsSubstitute)
  711. {
  712. BfTypedValue argTypedValue = resolvedArg.mTypedValue;
  713. if ((resolvedArg.mArgFlags & BfArgFlag_DelegateBindAttempt) != 0)
  714. {
  715. //TODO: See if we can bind it to a delegate type
  716. BfExprEvaluator exprEvaluator(mModule);
  717. exprEvaluator.mExpectingType = checkType;
  718. BF_ASSERT(resolvedArg.mExpression->IsA<BfDelegateBindExpression>());
  719. auto delegateBindExpr = BfNodeDynCast<BfDelegateBindExpression>(resolvedArg.mExpression);
  720. BfMethodInstance* boundMethodInstance = NULL;
  721. if (exprEvaluator.CanBindDelegate(delegateBindExpr, &boundMethodInstance))
  722. {
  723. if (delegateBindExpr->mNewToken == NULL)
  724. {
  725. resolvedArg.mExpectedType = checkType;
  726. auto methodRefType = mModule->CreateMethodRefType(boundMethodInstance);
  727. mModule->AddDependency(methodRefType, mModule->mCurTypeInstance, BfDependencyMap::DependencyFlag_Calls);
  728. mModule->AddCallDependency(boundMethodInstance);
  729. argTypedValue = BfTypedValue(mModule->mBfIRBuilder->GetFakeVal(), methodRefType);
  730. }
  731. else
  732. argTypedValue = BfTypedValue(BfTypedValueKind_UntypedValue);
  733. //argTypedValue = BfTypedValue(mModule->mBfIRBuilder->GetFakeVal(), checkType);
  734. }
  735. }
  736. else if ((resolvedArg.mArgFlags & BfArgFlag_LambdaBindAttempt) != 0)
  737. {
  738. BfExprEvaluator exprEvaluator(mModule);
  739. exprEvaluator.mExpectingType = checkType;
  740. BF_ASSERT(resolvedArg.mExpression->IsA<BfLambdaBindExpression>());
  741. auto lambdaBindExpr = (BfLambdaBindExpression*)resolvedArg.mExpression;
  742. if ((checkType != NULL) && (checkType->IsDelegate()))
  743. {
  744. BfMethodInstance* methodInstance = mModule->GetRawMethodInstanceAtIdx(checkType->ToTypeInstance(), 0, "Invoke");
  745. if (methodInstance != NULL)
  746. {
  747. if (methodInstance->GetParamCount() == (int)lambdaBindExpr->mParams.size())
  748. {
  749. if (lambdaBindExpr->mNewToken == NULL)
  750. {
  751. if (!resolvedArg.mTypedValue)
  752. {
  753. // Resolve for real
  754. resolvedArg.mTypedValue = mModule->CreateValueFromExpression(lambdaBindExpr, checkType, BfEvalExprFlags_NoCast);
  755. }
  756. argTypedValue = resolvedArg.mTypedValue;
  757. }
  758. else
  759. argTypedValue = BfTypedValue(BfTypedValueKind_UntypedValue);
  760. //argTypedValue = BfTypedValue(mModule->mBfIRBuilder->GetFakeVal(), checkType);
  761. }
  762. }
  763. }
  764. }
  765. else if ((resolvedArg.mArgFlags & BfArgFlag_UnqualifiedDotAttempt) != 0)
  766. {
  767. if ((checkType != NULL) && (checkType->IsPayloadEnum()))
  768. {
  769. // Should we actually check the member name?
  770. argTypedValue = BfTypedValue(BfTypedValueKind_UntypedValue);
  771. }
  772. }
  773. else if ((resolvedArg.mArgFlags & BfArgFlag_UntypedDefault) != 0)
  774. {
  775. if (checkType != NULL)
  776. argTypedValue = BfTypedValue(BfTypedValueKind_UntypedValue);
  777. }
  778. else if ((resolvedArg.mArgFlags & BfArgFlag_DeferredEval) != 0)
  779. {
  780. if (resolvedArg.mExpression != NULL)
  781. {
  782. if ((resolvedArg.mExpectedType != checkType) || (resolvedArg.mExpectedType == NULL)) // Did our last check match for this type?
  783. {
  784. SetAndRestoreValue<bool> prevIgnoreWrites(mModule->mBfIRBuilder->mIgnoreWrites, true);
  785. SetAndRestoreValue<bool> prevIgnoreError(mModule->mIgnoreErrors, true);
  786. bool prevNoBind = false;
  787. if (mModule->mCurMethodState != NULL)
  788. {
  789. prevNoBind = mModule->mCurMethodState->mNoBind;
  790. mModule->mCurMethodState->mNoBind = true;
  791. }
  792. auto prevBlock = mModule->mBfIRBuilder->GetInsertBlock();
  793. BfExprEvaluator exprEvaluator(mModule);
  794. exprEvaluator.mBfEvalExprFlags = (BfEvalExprFlags)(exprEvaluator.mBfEvalExprFlags | BfEvalExprFlags_AllowIntUnknown | BfEvalExprFlags_NoAutoComplete);
  795. if ((resolvedArg.mArgFlags & BfArgFlag_ParamsExpr) != 0)
  796. exprEvaluator.mBfEvalExprFlags = (BfEvalExprFlags)(exprEvaluator.mBfEvalExprFlags | BfEvalExprFlags_AllowParamsExpr);
  797. auto expectType = checkType;
  798. if (expectType != NULL)
  799. {
  800. if (expectType->IsRef())
  801. {
  802. auto refType = (BfRefType*)expectType;
  803. expectType = refType->mElementType;
  804. }
  805. if (genericArgumentsSubstitute != NULL)
  806. expectType = mModule->ResolveGenericType(expectType, *genericArgumentsSubstitute, true);
  807. }
  808. exprEvaluator.mExpectingType = expectType;
  809. exprEvaluator.Evaluate(resolvedArg.mExpression);
  810. argTypedValue = exprEvaluator.GetResult();
  811. if (mModule->mCurMethodState != NULL)
  812. mModule->mCurMethodState->mNoBind = prevNoBind;
  813. if (argTypedValue)
  814. {
  815. if (checkType != NULL)
  816. resolvedArg.mExpectedType = checkType;
  817. auto storeTypedValue = argTypedValue;
  818. if ((storeTypedValue.mValue) & (!storeTypedValue.mValue.IsFake()))
  819. {
  820. // We actually want to ensure that this cached value is a fake val. There are potential cases where a fake val
  821. // won't be generated but we should throw an error, so we need to make sure we actually re-evaluate when the call
  822. // is generated
  823. //storeTypedValue.mValue = mModule->mBfIRBuilder->GetFakeVal();
  824. resolvedArg.mWantsRecalc = true;
  825. }
  826. resolvedArg.mTypedValue = storeTypedValue;
  827. //BF_ASSERT(argTypedValue.mValue.mId != -1);
  828. }
  829. mModule->mBfIRBuilder->SetInsertPoint(prevBlock);
  830. }
  831. }
  832. }
  833. else if ((resolvedArg.mArgFlags & BfArgFlag_VariableDeclaration) != 0)
  834. {
  835. if ((checkType != NULL) && (checkType->IsRef()))
  836. argTypedValue = BfTypedValue(BfTypedValueKind_UntypedValue);
  837. }
  838. return argTypedValue;
  839. }
  840. bool BfMethodMatcher::WantsCheckMethod(BfProtectionCheckFlags& flags, BfTypeInstance* startTypeInstance, BfTypeInstance* checkTypeInstance, BfMethodDef* checkMethod)
  841. {
  842. MatchFailKind matchFailKind = MatchFailKind_None;
  843. if (!mModule->CheckProtection(flags, checkTypeInstance, checkMethod->mProtection, startTypeInstance))
  844. {
  845. if ((mBypassVirtual) && (checkMethod->mProtection == BfProtection_Protected) && (mModule->TypeIsSubTypeOf(mModule->mCurTypeInstance, startTypeInstance)))
  846. {
  847. // Allow explicit 'base' call
  848. }
  849. else
  850. {
  851. return false;
  852. }
  853. }
  854. if (mCheckedKind != checkMethod->mCheckedKind)
  855. {
  856. bool passes = true;
  857. if (mCheckedKind != BfCheckedKind_NotSet)
  858. {
  859. passes = false;
  860. }
  861. else
  862. {
  863. auto defaultCheckedKind = mModule->GetDefaultCheckedKind();
  864. if (defaultCheckedKind != checkMethod->mCheckedKind)
  865. passes = false;
  866. }
  867. if (!passes)
  868. {
  869. return false;
  870. }
  871. }
  872. return true;
  873. }
  874. bool BfMethodMatcher::InferFromGenericConstraints(BfGenericParamInstance* genericParamInst, BfTypeVector* methodGenericArgs)
  875. {
  876. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_Equals) == 0)
  877. return false;
  878. if (!genericParamInst->mExternType->IsGenericParam())
  879. return false;
  880. auto genericParamType = (BfGenericParamType*)genericParamInst->mExternType;
  881. if (genericParamType->mGenericParamKind != BfGenericParamKind_Method)
  882. return false;
  883. BfType* checkArgType = NULL;
  884. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_Equals_Type) != 0)
  885. {
  886. checkArgType = genericParamInst->mTypeConstraint;
  887. }
  888. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_Equals_IFace) != 0)
  889. {
  890. if (!genericParamInst->mInterfaceConstraints.IsEmpty())
  891. checkArgType = genericParamInst->mInterfaceConstraints[0];
  892. }
  893. for (auto& checkOpConstraint : genericParamInst->mOperatorConstraints)
  894. {
  895. auto leftType = checkOpConstraint.mLeftType;
  896. if ((leftType != NULL) && (leftType->IsUnspecializedType()))
  897. leftType = mModule->ResolveGenericType(leftType, *methodGenericArgs);
  898. if (leftType != NULL)
  899. leftType = mModule->FixIntUnknown(leftType);
  900. auto rightType = checkOpConstraint.mRightType;
  901. if ((rightType != NULL) && (rightType->IsUnspecializedType()))
  902. rightType = mModule->ResolveGenericType(rightType, *methodGenericArgs);
  903. if (rightType != NULL)
  904. rightType = mModule->FixIntUnknown(rightType);
  905. BfConstraintState constraintSet;
  906. constraintSet.mPrevState = mModule->mContext->mCurConstraintState;
  907. constraintSet.mGenericParamInstance = genericParamInst;
  908. constraintSet.mLeftType = leftType;
  909. constraintSet.mRightType = rightType;
  910. SetAndRestoreValue<BfConstraintState*> prevConstraintSet(mModule->mContext->mCurConstraintState, &constraintSet);
  911. if (!mModule->CheckConstraintState(NULL))
  912. return false;
  913. if (checkOpConstraint.mBinaryOp != BfBinaryOp_None)
  914. {
  915. BfExprEvaluator exprEvaluator(mModule);
  916. BfTypedValue leftValue(mModule->mBfIRBuilder->GetFakeVal(), leftType);
  917. BfTypedValue rightValue(mModule->mBfIRBuilder->GetFakeVal(), rightType);
  918. //
  919. {
  920. SetAndRestoreValue<bool> prevIgnoreErrors(mModule->mIgnoreErrors, true);
  921. SetAndRestoreValue<bool> prevIgnoreWrites(mModule->mBfIRBuilder->mIgnoreWrites, true);
  922. exprEvaluator.PerformBinaryOperation(NULL, NULL, checkOpConstraint.mBinaryOp, NULL, BfBinOpFlag_NoClassify, leftValue, rightValue);
  923. }
  924. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_Equals_Op) != 0)
  925. checkArgType = exprEvaluator.mResult.mType;
  926. }
  927. else
  928. {
  929. BfTypedValue rightValue(mModule->mBfIRBuilder->GetFakeVal(), rightType);
  930. StringT<128> failedOpName;
  931. if (checkOpConstraint.mCastToken == BfToken_Implicit)
  932. {
  933. }
  934. else
  935. {
  936. SetAndRestoreValue<bool> prevIgnoreErrors(mModule->mIgnoreErrors, true);
  937. SetAndRestoreValue<bool> prevIgnoreWrites(mModule->mBfIRBuilder->mIgnoreWrites, true);
  938. if (checkOpConstraint.mCastToken == BfToken_Explicit)
  939. {
  940. }
  941. else
  942. {
  943. BfExprEvaluator exprEvaluator(mModule);
  944. exprEvaluator.mResult = rightValue;
  945. exprEvaluator.PerformUnaryOperation(NULL, checkOpConstraint.mUnaryOp, NULL);
  946. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_Equals_Op) != 0)
  947. checkArgType = exprEvaluator.mResult.mType;
  948. }
  949. }
  950. }
  951. }
  952. if (checkArgType == NULL)
  953. return false;
  954. (*methodGenericArgs)[genericParamType->mGenericParamIdx] = checkArgType;
  955. return true;
  956. }
  957. bool BfMethodMatcher::CheckMethod(BfTypeInstance* typeInstance, BfMethodDef* checkMethod, bool isFailurePass)
  958. {
  959. BP_ZONE("BfMethodMatcher::CheckMethod");
  960. bool hadMatch = false;
  961. // Never consider overrides - they only get found at original method declaration
  962. // mBypassVirtual gets set when we are doing an explicit "base" call, or when we are a struct --
  963. // because on structs we know the exact type
  964. if ((checkMethod->mIsOverride) && (!mBypassVirtual) && (!typeInstance->IsValueType()))
  965. return false;
  966. mMethodCheckCount++;
  967. BfMethodInstance* methodInstance = mModule->GetRawMethodInstance(typeInstance, checkMethod);
  968. if (methodInstance == NULL)
  969. {
  970. BF_FATAL("Failed to get raw method in BfMethodMatcher::CheckMethod");
  971. return false;
  972. }
  973. if ((mInterfaceMethodInstance != NULL) && (methodInstance->GetExplicitInterface() != NULL))
  974. {
  975. BfTypeInstance* wantInterface = mInterfaceMethodInstance->mMethodInstanceGroup->mOwner;
  976. if (wantInterface != methodInstance->GetExplicitInterface())
  977. return false;
  978. }
  979. HashSet<int> allowEmptyGenericSet;
  980. BfAutoComplete* autoComplete = NULL;
  981. if ((mModule->mCompiler->mResolvePassData != NULL) && (!isFailurePass))
  982. autoComplete = mModule->mCompiler->mResolvePassData->mAutoComplete;
  983. if (((checkMethod->mIsStatic) && (!mAllowStatic)) ||
  984. ((!checkMethod->mIsStatic) && (!mAllowNonStatic)))
  985. {
  986. if (!typeInstance->IsFunction())
  987. autoComplete = NULL;
  988. }
  989. if ((autoComplete != NULL) && (autoComplete->mIsCapturingMethodMatchInfo))
  990. {
  991. BfAutoComplete::MethodMatchEntry methodMatchEntry;
  992. methodMatchEntry.mMethodDef = checkMethod;
  993. methodMatchEntry.mTypeInstance = typeInstance;
  994. methodMatchEntry.mCurMethodInstance = mModule->mCurMethodInstance;
  995. autoComplete->mMethodMatchInfo->mInstanceList.push_back(methodMatchEntry);
  996. }
  997. BfTypeVector* genericArgumentsSubstitute = NULL;
  998. int argIdx = 0;
  999. int argMatchCount = 0;
  1000. bool needInferGenericParams = (checkMethod->mGenericParams.size() != 0) && (!mHadExplicitGenericArguments);
  1001. int paramIdx = 0;
  1002. BfType* paramsElementType = NULL;
  1003. if (checkMethod->mHasAppend)
  1004. paramIdx++;
  1005. // int outmostGenericCount = 0;
  1006. // if (checkMethod->mIsLocalMethod)
  1007. // outmostGenericCount = (int)mModule->mCurMethodState->GetRootMethodState()->mMethodInstance->mGenericParams.size();
  1008. int uniqueGenericStartIdx = mModule->GetLocalInferrableGenericArgCount(checkMethod);
  1009. if ((mHadExplicitGenericArguments) && (checkMethod->mGenericParams.size() != mExplicitMethodGenericArguments.size() + uniqueGenericStartIdx))
  1010. goto NoMatch;
  1011. for (auto& checkGenericArgRef : mCheckMethodGenericArguments)
  1012. checkGenericArgRef = NULL;
  1013. mCheckMethodGenericArguments.resize(checkMethod->mGenericParams.size());
  1014. mPrevArgValues.resize(checkMethod->mGenericParams.size());
  1015. for (auto& genericArgRef : mCheckMethodGenericArguments)
  1016. genericArgRef = NULL;
  1017. if (mHadExplicitGenericArguments)
  1018. {
  1019. if (uniqueGenericStartIdx > 0)
  1020. {
  1021. genericArgumentsSubstitute = &mCheckMethodGenericArguments;
  1022. mCheckMethodGenericArguments.clear();
  1023. mCheckMethodGenericArguments.reserve(mExplicitMethodGenericArguments.size() + uniqueGenericStartIdx);
  1024. for (int i = 0; i < uniqueGenericStartIdx; i++)
  1025. mCheckMethodGenericArguments.Add(NULL);
  1026. for (int i = 0; i < (int)mExplicitMethodGenericArguments.size(); i++)
  1027. mCheckMethodGenericArguments.Add(mExplicitMethodGenericArguments[i]);
  1028. }
  1029. else
  1030. {
  1031. genericArgumentsSubstitute = &mExplicitMethodGenericArguments;
  1032. }
  1033. }
  1034. else if (needInferGenericParams)
  1035. genericArgumentsSubstitute = &mCheckMethodGenericArguments;
  1036. if (mSkipImplicitParams)
  1037. {
  1038. //paramOfs = methodInstance->GetImplicitParamCount();
  1039. //paramIdx += paramOfs;
  1040. }
  1041. if (needInferGenericParams)
  1042. {
  1043. int paramOfs = methodInstance->GetImplicitParamCount();
  1044. int paramCount = methodInstance->GetParamCount();
  1045. if (checkMethod->mHasAppend)
  1046. paramOfs++;
  1047. for (int argIdx = 0; argIdx < (int)mArguments.size(); argIdx++)
  1048. {
  1049. if (argIdx >= (int)checkMethod->mParams.size())
  1050. break;
  1051. int paramIdx = argIdx + paramOfs;
  1052. if (paramIdx >= paramCount)
  1053. break; // Possible for delegate 'params' type methods
  1054. auto wantType = methodInstance->GetParamType(argIdx + paramOfs);
  1055. auto checkType = wantType;
  1056. auto origCheckType = checkType;
  1057. if (checkType->IsGenericParam())
  1058. {
  1059. BfGenericParamInstance* genericParamInstance = NULL;
  1060. auto genericParamType = (BfGenericParamType*)checkType;
  1061. checkType = NULL;
  1062. if (genericParamType->mGenericParamKind == BfGenericParamKind_Method)
  1063. {
  1064. if ((genericArgumentsSubstitute != NULL) && (genericParamType->mGenericParamIdx < (int)genericArgumentsSubstitute->size()))
  1065. checkType = (*genericArgumentsSubstitute)[genericParamType->mGenericParamIdx];
  1066. genericParamInstance = methodInstance->mMethodInfoEx->mGenericParams[genericParamType->mGenericParamIdx];
  1067. }
  1068. else
  1069. genericParamInstance = mModule->GetGenericParamInstance(genericParamType);
  1070. if (checkType == NULL)
  1071. checkType = genericParamInstance->mTypeConstraint;
  1072. }
  1073. if ((checkType != NULL) && (genericArgumentsSubstitute != NULL) && (checkType->IsUnspecializedTypeVariation()))
  1074. {
  1075. checkType = mModule->ResolveGenericType(origCheckType, *genericArgumentsSubstitute);
  1076. }
  1077. if (wantType->IsUnspecializedType())
  1078. {
  1079. BfTypedValue argTypedValue = ResolveArgTypedValue(mArguments[argIdx], checkType, genericArgumentsSubstitute);
  1080. if (!argTypedValue.IsUntypedValue())
  1081. {
  1082. auto type = argTypedValue.mType;
  1083. if ((!argTypedValue) || (!InferGenericArgument(methodInstance, type, wantType, argTypedValue.mValue)))
  1084. goto NoMatch;
  1085. }
  1086. }
  1087. }
  1088. //
  1089. {
  1090. int paramIdx = (int)mArguments.size() + paramOfs;
  1091. while (paramIdx < checkMethod->mParams.size())
  1092. {
  1093. if ((paramIdx < methodInstance->mDefaultValues.size()) && (methodInstance->mDefaultValues[paramIdx]))
  1094. {
  1095. auto wantType = methodInstance->GetParamType(paramIdx);
  1096. auto checkType = wantType;
  1097. if (checkType->IsGenericParam())
  1098. {
  1099. BfGenericParamInstance* genericParamInstance = NULL;
  1100. auto genericParamType = (BfGenericParamType*)checkType;
  1101. if (genericParamType->mGenericParamKind == BfGenericParamKind_Method)
  1102. {
  1103. if ((genericArgumentsSubstitute != NULL) && (genericParamType->mGenericParamIdx < (int)genericArgumentsSubstitute->size()))
  1104. checkType = (*genericArgumentsSubstitute)[genericParamType->mGenericParamIdx];
  1105. genericParamInstance = methodInstance->mMethodInfoEx->mGenericParams[genericParamType->mGenericParamIdx];
  1106. if ((genericParamInstance->mGenericParamFlags & BfGenericParamFlag_Const) != 0)
  1107. {
  1108. if (mCheckMethodGenericArguments[genericParamType->mGenericParamIdx] == NULL)
  1109. allowEmptyGenericSet.Add(genericParamType->mGenericParamIdx);
  1110. }
  1111. }
  1112. }
  1113. }
  1114. paramIdx++;
  1115. }
  1116. }
  1117. //
  1118. for (int genericArgIdx = uniqueGenericStartIdx; genericArgIdx < (int)checkMethod->mGenericParams.size(); genericArgIdx++)
  1119. {
  1120. auto& genericArg = mCheckMethodGenericArguments[genericArgIdx];
  1121. if (genericArg == NULL)
  1122. {
  1123. auto genericParam = methodInstance->mMethodInfoEx->mGenericParams[genericArgIdx];
  1124. InferFromGenericConstraints(genericParam, &mCheckMethodGenericArguments);
  1125. if (genericArg != NULL)
  1126. continue;
  1127. if (!allowEmptyGenericSet.Contains(genericArgIdx))
  1128. goto NoMatch;
  1129. }
  1130. }
  1131. }
  1132. // Iterate through params
  1133. while (true)
  1134. {
  1135. // Too many arguments
  1136. if (paramIdx >= (int)methodInstance->GetParamCount())
  1137. {
  1138. break;
  1139. }
  1140. bool isDeferredEval = false;
  1141. if ((methodInstance->GetParamKind(paramIdx) == BfParamKind_Params) && (paramsElementType == NULL))
  1142. {
  1143. if (paramIdx >= (int) mArguments.size())
  1144. break; // No params
  1145. BfTypedValue argTypedValue = ResolveArgTypedValue(mArguments[argIdx], NULL, genericArgumentsSubstitute);
  1146. if (!argTypedValue)
  1147. goto NoMatch;
  1148. if ((!argTypedValue.HasType()) && (!mArguments[argIdx].IsDeferredEval()))
  1149. goto NoMatch;
  1150. auto paramsArrayType = methodInstance->GetParamType(paramIdx);
  1151. if ((mArguments[argIdx].mArgFlags & BfArgFlag_ParamsExpr) != 0)
  1152. {
  1153. // Direct-pass params
  1154. if ((argTypedValue.IsUntypedValue()) || (mModule->CanImplicitlyCast(argTypedValue, paramsArrayType)))
  1155. {
  1156. argIdx++;
  1157. argMatchCount++;
  1158. paramIdx++;
  1159. break;
  1160. }
  1161. goto NoMatch;
  1162. }
  1163. if (paramsArrayType->IsArray())
  1164. {
  1165. auto arrayType = (BfArrayType*)paramsArrayType;
  1166. paramsElementType = arrayType->mTypeGenericArguments[0];
  1167. while (argIdx < (int)mArguments.size())
  1168. {
  1169. argTypedValue = ResolveArgTypedValue(mArguments[argIdx], paramsElementType, genericArgumentsSubstitute);
  1170. if (!argTypedValue.HasType())
  1171. goto NoMatch;
  1172. if (!mModule->CanImplicitlyCast(argTypedValue, paramsElementType))
  1173. goto NoMatch;
  1174. argIdx++;
  1175. argMatchCount++;
  1176. }
  1177. }
  1178. else
  1179. goto NoMatch;
  1180. break;
  1181. }
  1182. if (methodInstance->IsImplicitCapture(paramIdx))
  1183. {
  1184. paramIdx++;
  1185. continue;
  1186. }
  1187. if (argIdx >= (int) mArguments.size())
  1188. {
  1189. // We have defaults the rest of the way, so that's cool
  1190. if (methodInstance->GetParamInitializer(paramIdx) != NULL)
  1191. break;
  1192. // We have unused params left over
  1193. goto NoMatch;
  1194. }
  1195. auto wantType = methodInstance->GetParamType(paramIdx);
  1196. if ((genericArgumentsSubstitute != NULL) && (wantType->IsUnspecializedType()))
  1197. {
  1198. auto resolvedType = mModule->ResolveGenericType(wantType, *genericArgumentsSubstitute);
  1199. if (resolvedType == NULL)
  1200. goto NoMatch;
  1201. wantType = resolvedType;
  1202. }
  1203. if (wantType->IsSelf())
  1204. wantType = typeInstance;
  1205. if ((mArguments[argIdx].mArgFlags & BfArgFlag_ParamsExpr) != 0)
  1206. {
  1207. // We had a 'params' expression but this method didn't have a params slot in this parameter
  1208. goto NoMatch;
  1209. }
  1210. BfTypedValue argTypedValue = ResolveArgTypedValue(mArguments[argIdx], wantType, genericArgumentsSubstitute);
  1211. if (!argTypedValue.IsUntypedValue())
  1212. {
  1213. if (!argTypedValue.HasType())
  1214. {
  1215. goto NoMatch;
  1216. }
  1217. else if (!mModule->CanImplicitlyCast(argTypedValue, wantType))
  1218. goto NoMatch;
  1219. }
  1220. paramIdx++;
  1221. argIdx++;
  1222. argMatchCount++;
  1223. if ((autoComplete != NULL) && (autoComplete->mIsCapturingMethodMatchInfo))
  1224. {
  1225. auto methodMatchInfo = autoComplete->mMethodMatchInfo;
  1226. if (!methodMatchInfo->mHadExactMatch)
  1227. {
  1228. bool isBetter = false;
  1229. bool isWorse = false;
  1230. int methodIdx = (int)methodMatchInfo->mInstanceList.size() - 1;
  1231. if ((methodMatchInfo->mBestIdx != -1) && (methodMatchInfo->mBestIdx < (int)methodMatchInfo->mInstanceList.size()))
  1232. {
  1233. auto prevMethodMatchEntry = &methodMatchInfo->mInstanceList[methodMatchInfo->mBestIdx];
  1234. if (checkMethod->mParams.size() < mArguments.size())
  1235. {
  1236. isWorse = true;
  1237. }
  1238. else if ((prevMethodMatchEntry->mMethodDef != NULL) && (prevMethodMatchEntry->mMethodDef->mParams.size() < (int) mArguments.size()))
  1239. {
  1240. isBetter = true;
  1241. }
  1242. }
  1243. }
  1244. }
  1245. }
  1246. //TODO: Does this ever get hit?
  1247. // Not enough arguments?
  1248. if (argIdx < (int)mArguments.size())
  1249. {
  1250. goto NoMatch;
  1251. }
  1252. if ((genericArgumentsSubstitute != NULL) && (genericArgumentsSubstitute->size() != 0))
  1253. {
  1254. for (int checkGenericIdx = uniqueGenericStartIdx; checkGenericIdx < (int)genericArgumentsSubstitute->size(); checkGenericIdx++)
  1255. {
  1256. auto& genericParams = methodInstance->mMethodInfoEx->mGenericParams;
  1257. auto genericArg = (*genericArgumentsSubstitute)[checkGenericIdx];
  1258. if (genericArg == NULL)
  1259. {
  1260. if (allowEmptyGenericSet.Contains(checkGenericIdx))
  1261. continue;
  1262. goto NoMatch;
  1263. }
  1264. // if (genericArg->IsPrimitiveType())
  1265. // {
  1266. // auto primType = (BfPrimitiveType*) genericArg;
  1267. // genericArg = mModule->GetPrimitiveStructType(primType->mTypeDef->mTypeCode);
  1268. // }
  1269. if (genericArg == NULL)
  1270. goto NoMatch;
  1271. //SetAndRestoreValue<bool> ignoreError(mModule->mIgnoreErrors, true);
  1272. if (!mModule->CheckGenericConstraints(BfGenericParamSource(methodInstance), genericArg, NULL, genericParams[checkGenericIdx], genericArgumentsSubstitute, NULL))
  1273. {
  1274. goto NoMatch;
  1275. }
  1276. }
  1277. }
  1278. // Method is applicable, check to see which method is better
  1279. if (mBestMethodDef != NULL)
  1280. {
  1281. bool isBetter = false;
  1282. bool isWorse = false;
  1283. BfMethodInstance* prevMethodInstance = mModule->GetRawMethodInstance(mBestMethodTypeInstance, mBestMethodDef);
  1284. bool allowSpecializeFail = mModule->mCurTypeInstance->IsUnspecializedType();
  1285. if (mModule->mCurMethodInstance != NULL)
  1286. allowSpecializeFail = mModule->mCurMethodInstance->mIsUnspecialized;
  1287. CompareMethods(prevMethodInstance, &mBestMethodGenericArguments, methodInstance, genericArgumentsSubstitute, &isBetter, &isWorse, allowSpecializeFail);
  1288. // If we had both a 'better' and 'worse', that's ambiguous because the methods are each better in different ways (not allowed)
  1289. // And if neither better nor worse then they are equally good, which is not allowed either
  1290. if (((!isBetter) && (!isWorse)) || ((isBetter) && (isWorse)))
  1291. {
  1292. if (!mHasVarArguments)
  1293. {
  1294. BfAmbiguousEntry ambiguousEntry;
  1295. ambiguousEntry.mMethodInstance = methodInstance;
  1296. if (genericArgumentsSubstitute != NULL)
  1297. ambiguousEntry.mBestMethodGenericArguments = *genericArgumentsSubstitute;
  1298. if (methodInstance->GetNumGenericParams() != 0)
  1299. {
  1300. BF_ASSERT(!ambiguousEntry.mBestMethodGenericArguments.empty());
  1301. }
  1302. mAmbiguousEntries.push_back(ambiguousEntry);
  1303. }
  1304. }
  1305. if (!isBetter)
  1306. goto Done;
  1307. }
  1308. if ((autoComplete != NULL) && (autoComplete->mIsCapturingMethodMatchInfo))
  1309. {
  1310. auto methodMatchInfo = autoComplete->mMethodMatchInfo;
  1311. // Try to persist with previous partial match, if we have one - this keeps us from locking onto
  1312. // an incorrect method just because it had the current number of params that we've typed so far
  1313. if (methodMatchInfo->mPrevBestIdx == -1)
  1314. {
  1315. methodMatchInfo->mHadExactMatch = true;
  1316. methodMatchInfo->mBestIdx = (int) methodMatchInfo->mInstanceList.size() - 1;
  1317. }
  1318. }
  1319. mAmbiguousEntries.Clear();
  1320. hadMatch = true;
  1321. mBestMethodDef = checkMethod;
  1322. for (auto& arg : mArguments)
  1323. arg.mBestBoundType = arg.mTypedValue.mType;
  1324. NoMatch:
  1325. if (!hadMatch)
  1326. {
  1327. if (mBestMethodDef != NULL)
  1328. return false;
  1329. /*if ((mHadExplicitGenericArguments) && (mBestMethodGenericArguments.size() != checkMethod->mGenericParams.size()))
  1330. return false;*/
  1331. if (mBackupMethodDef != NULL)
  1332. {
  1333. int prevParamDiff = (int)mBackupMethodDef->mParams.size() - (int)mArguments.size();
  1334. int paramDiff = (int)checkMethod->mParams.size() - (int)mArguments.size();
  1335. if ((prevParamDiff < 0) && (prevParamDiff > paramDiff))
  1336. return false;
  1337. if ((prevParamDiff >= 0) && ((paramDiff < 0) || (prevParamDiff < paramDiff)))
  1338. return false;
  1339. if (paramDiff == prevParamDiff)
  1340. {
  1341. if (argMatchCount < mBackupArgMatchCount)
  1342. return false;
  1343. else if (argMatchCount == mBackupArgMatchCount)
  1344. {
  1345. // We search from the most specific type, so don't prefer a less specific type
  1346. if (mBestMethodTypeInstance != typeInstance)
  1347. return false;
  1348. }
  1349. }
  1350. }
  1351. if ((autoComplete != NULL) && (autoComplete->mIsCapturingMethodMatchInfo))
  1352. {
  1353. auto methodMatchInfo = autoComplete->mMethodMatchInfo;
  1354. if ((methodMatchInfo->mPrevBestIdx == -1) && (!methodMatchInfo->mHadExactMatch))
  1355. {
  1356. methodMatchInfo->mBestIdx = (int)methodMatchInfo->mInstanceList.size() - 1;
  1357. }
  1358. }
  1359. mBackupMethodDef = checkMethod;
  1360. mBackupArgMatchCount = argMatchCount;
  1361. // Lie temporarily to store at least one candidate (but mBestMethodDef is still NULL)
  1362. hadMatch = true;
  1363. }
  1364. if (hadMatch)
  1365. {
  1366. mBestMethodTypeInstance = typeInstance;
  1367. if (genericArgumentsSubstitute != &mBestMethodGenericArguments)
  1368. {
  1369. if (genericArgumentsSubstitute != NULL)
  1370. mBestMethodGenericArguments = *genericArgumentsSubstitute;
  1371. else
  1372. mBestMethodGenericArguments.clear();
  1373. }
  1374. }
  1375. Done:
  1376. if ((autoComplete != NULL) && (autoComplete->mIsCapturingMethodMatchInfo) && (genericArgumentsSubstitute != NULL))
  1377. {
  1378. auto methodMatchInfo = autoComplete->mMethodMatchInfo;
  1379. if (!methodMatchInfo->mInstanceList.IsEmpty())
  1380. {
  1381. methodMatchInfo->mInstanceList[methodMatchInfo->mInstanceList.size() - 1].mGenericArguments = *genericArgumentsSubstitute;
  1382. }
  1383. }
  1384. return mBestMethodDef == checkMethod;
  1385. }
  1386. void BfMethodMatcher::FlushAmbiguityError()
  1387. {
  1388. if (!mAmbiguousEntries.empty())
  1389. {
  1390. BfError* error;
  1391. if (!mMethodName.empty())
  1392. error = mModule->Fail(StrFormat("Ambiguous method call for '%s'", mMethodName.c_str()), mTargetSrc);
  1393. else
  1394. error = mModule->Fail("Ambiguous method call", mTargetSrc);
  1395. if (error != NULL)
  1396. {
  1397. BfMethodInstance* bestMethodInstance = mModule->GetRawMethodInstance(mBestMethodTypeInstance, mBestMethodDef);
  1398. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("'%s' is a candidate", mModule->MethodToString(bestMethodInstance, BfMethodNameFlag_ResolveGenericParamNames,
  1399. mBestMethodGenericArguments.empty() ? NULL : &mBestMethodGenericArguments).c_str()),
  1400. bestMethodInstance->mMethodDef->GetRefNode());
  1401. for (auto& ambiguousEntry : mAmbiguousEntries)
  1402. {
  1403. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("'%s' is a candidate", mModule->MethodToString(ambiguousEntry.mMethodInstance, BfMethodNameFlag_ResolveGenericParamNames,
  1404. ambiguousEntry.mBestMethodGenericArguments.empty() ? NULL : &ambiguousEntry.mBestMethodGenericArguments).c_str()),
  1405. ambiguousEntry.mMethodInstance->mMethodDef->GetRefNode());
  1406. }
  1407. }
  1408. mAmbiguousEntries.Clear();
  1409. }
  1410. }
  1411. // This method checks all base classes before checking interfaces. Is that correct?
  1412. bool BfMethodMatcher::CheckType(BfTypeInstance* typeInstance, BfTypedValue target, bool isFailurePass)
  1413. {
  1414. auto curTypeInst = typeInstance;
  1415. auto curTypeDef = typeInstance->mTypeDef;
  1416. int checkInterfaceIdx = 0;
  1417. bool allowExplicitInterface = curTypeInst->IsInterface() && mBypassVirtual;
  1418. auto activeTypeDef = mModule->GetActiveTypeDef();
  1419. bool isDelegate = typeInstance->IsDelegate();
  1420. bool targetIsBase = target.IsBase();
  1421. bool checkExtensionBase = false;
  1422. if (targetIsBase)
  1423. {
  1424. if ((curTypeInst == mModule->mCurTypeInstance) && (curTypeInst->mTypeDef->mIsCombinedPartial))
  1425. {
  1426. checkExtensionBase = true;
  1427. }
  1428. else
  1429. {
  1430. curTypeInst = curTypeInst->mBaseType;
  1431. }
  1432. }
  1433. while (true)
  1434. {
  1435. curTypeDef->PopulateMemberSets();
  1436. BfMethodDef* nextMethodDef = NULL;
  1437. BfMemberSetEntry* entry;
  1438. if (curTypeDef->mMethodSet.TryGetWith(mMethodName, &entry))
  1439. nextMethodDef = (BfMethodDef*)entry->mMemberDef;
  1440. BfProtectionCheckFlags protectionCheckFlags = BfProtectionCheckFlag_None;
  1441. while (nextMethodDef != NULL)
  1442. {
  1443. auto checkMethod = nextMethodDef;
  1444. nextMethodDef = nextMethodDef->mNextWithSameName;
  1445. if ((checkExtensionBase) && (curTypeInst == mModule->mCurTypeInstance))
  1446. {
  1447. // Accept either a method in the same project but that's the root definition, OR a method that's in a dependent project
  1448. bool accept = false;
  1449. if (activeTypeDef->mProject == checkMethod->mDeclaringType->mProject)
  1450. accept = (activeTypeDef->IsExtension()) && (!checkMethod->mDeclaringType->IsExtension());
  1451. else
  1452. accept = activeTypeDef->mProject->ContainsReference(checkMethod->mDeclaringType->mProject);
  1453. if (!accept)
  1454. continue;
  1455. }
  1456. if ((!allowExplicitInterface) && (checkMethod->mExplicitInterface != NULL) && (mInterfaceMethodInstance == NULL))
  1457. {
  1458. continue;
  1459. }
  1460. if (checkMethod->mMethodType != mMethodType)
  1461. continue;
  1462. // if (checkMethod->mName != mMethodName)
  1463. // continue;
  1464. if (!isDelegate)
  1465. {
  1466. if ((!curTypeInst->IsTypeMemberIncluded(checkMethod->mDeclaringType, activeTypeDef, mModule)) ||
  1467. (!curTypeInst->IsTypeMemberAccessible(checkMethod->mDeclaringType, activeTypeDef)))
  1468. continue;
  1469. }
  1470. MatchFailKind matchFailKind = MatchFailKind_None;
  1471. if (!mModule->CheckProtection(protectionCheckFlags, curTypeInst, checkMethod->mProtection, typeInstance))
  1472. {
  1473. if ((mBypassVirtual) && (checkMethod->mProtection == BfProtection_Protected) && (mModule->TypeIsSubTypeOf(mModule->mCurTypeInstance, typeInstance)))
  1474. {
  1475. // Allow explicit 'base' call
  1476. }
  1477. else
  1478. {
  1479. if (!isFailurePass)
  1480. continue;
  1481. matchFailKind = MatchFailKind_Protection;
  1482. }
  1483. }
  1484. if (mCheckedKind != checkMethod->mCheckedKind)
  1485. {
  1486. bool passes = true;
  1487. if (mCheckedKind != BfCheckedKind_NotSet)
  1488. {
  1489. passes = false;
  1490. }
  1491. else
  1492. {
  1493. auto defaultCheckedKind = mModule->GetDefaultCheckedKind();
  1494. if (defaultCheckedKind != checkMethod->mCheckedKind)
  1495. passes = false;
  1496. }
  1497. if (!passes)
  1498. {
  1499. if (!isFailurePass)
  1500. continue;
  1501. matchFailKind = MatchFailKind_CheckedMismatch;
  1502. }
  1503. }
  1504. CheckMethod(curTypeInst, checkMethod, isFailurePass);
  1505. if ((isFailurePass) &&
  1506. ((mBestMethodDef == checkMethod) || (mBackupMethodDef == checkMethod)))
  1507. mMatchFailKind = matchFailKind;
  1508. }
  1509. if (mBestMethodDef != NULL)
  1510. {
  1511. FlushAmbiguityError();
  1512. return true;
  1513. }
  1514. auto baseType = curTypeInst->mBaseType;
  1515. if (baseType == NULL)
  1516. {
  1517. //TODO: Why were we doing the interface checking?
  1518. if ((curTypeInst != mModule->mContext->mBfObjectType) && (!curTypeInst->IsInterface()))
  1519. {
  1520. // This can happen for structs
  1521. baseType = mModule->mContext->mBfObjectType;
  1522. }
  1523. else if ((typeInstance->IsInterface()) && (checkInterfaceIdx < (int)typeInstance->mInterfaces.size()))
  1524. {
  1525. baseType = typeInstance->mInterfaces[checkInterfaceIdx].mInterfaceType;
  1526. checkInterfaceIdx++;
  1527. }
  1528. else
  1529. {
  1530. break;
  1531. }
  1532. }
  1533. curTypeDef = baseType->mTypeDef;
  1534. curTypeInst = baseType;
  1535. if ((isFailurePass) && (mBackupMethodDef != NULL))
  1536. break;
  1537. }
  1538. if (mBestMethodDef == NULL)
  1539. {
  1540. // FAILED, but select the first method which will fire an actual error on param type matching
  1541. mBestMethodDef = mBackupMethodDef;
  1542. }
  1543. if ((mBestMethodDef == NULL) && (!target) && (mAllowImplicitThis))
  1544. {
  1545. // No explicit target - maybe this was a static call in the outer type?
  1546. auto outerType = mModule->GetOuterType(typeInstance);
  1547. if (outerType != NULL)
  1548. CheckOuterTypeStaticMethods(outerType, isFailurePass);
  1549. }
  1550. FlushAmbiguityError();
  1551. return mBestMethodDef != NULL;
  1552. }
  1553. void BfMethodMatcher::TryDevirtualizeCall(BfTypedValue target, BfTypedValue* origTarget, BfTypedValue* staticResult)
  1554. {
  1555. if ((mBestMethodDef == NULL) || (target.mType == NULL))
  1556. return;
  1557. if ((mModule->mCompiler->IsAutocomplete()) || (mModule->mContext->mResolvingVarField))
  1558. return;
  1559. if (mModule->mBfIRBuilder->mIgnoreWrites)
  1560. return;
  1561. if (mBestMethodTypeInstance->IsInterface())
  1562. {
  1563. mModule->PopulateType(mBestMethodTypeInstance, BfPopulateType_DataAndMethods);
  1564. auto activeTypeDef = mModule->GetActiveTypeDef();
  1565. // Statically map this call
  1566. auto checkType = target.mType;
  1567. if (checkType->IsPointer())
  1568. checkType = ((BfPointerType*)checkType)->mElementType;
  1569. if (checkType->IsWrappableType())
  1570. checkType = mModule->GetWrappedStructType(checkType);
  1571. if ((checkType != NULL) && (checkType->IsTypeInstance()) && (!checkType->IsInterface()))
  1572. {
  1573. BfTypeInterfaceEntry* bestIFaceEntry = NULL;
  1574. auto checkTypeInst = checkType->ToTypeInstance();
  1575. if (mBestMethodTypeInstance->mTypeDef == mModule->mCompiler->mIHashableTypeDef)
  1576. {
  1577. if ((origTarget != NULL) && (origTarget->mType->IsPointer()) && (staticResult != NULL))
  1578. {
  1579. BfTypedValue ptrVal = mModule->LoadValue(*origTarget);
  1580. *staticResult = BfTypedValue(mModule->mBfIRBuilder->CreatePtrToInt(ptrVal.mValue, BfTypeCode_IntPtr), mModule->GetPrimitiveType(BfTypeCode_IntPtr));
  1581. return;
  1582. }
  1583. }
  1584. while (checkTypeInst != NULL)
  1585. {
  1586. mModule->PopulateType(checkTypeInst, BfPopulateType_DataAndMethods);
  1587. for (auto&& iface : checkTypeInst->mInterfaces)
  1588. {
  1589. //TODO: Why did we have this check? This caused Dictionary to not be able to devirtualize
  1590. // calls to TKey GetHashCode when TKey was from a user's project...
  1591. /*if (!checkTypeInst->IsTypeMemberAccessible(iface.mDeclaringType, activeTypeDef))
  1592. continue;*/
  1593. if (iface.mInterfaceType == mBestMethodTypeInstance)
  1594. {
  1595. if (bestIFaceEntry == NULL)
  1596. {
  1597. bestIFaceEntry = &iface;
  1598. continue;
  1599. }
  1600. bool isBetter;
  1601. bool isWorse;
  1602. mModule->CompareDeclTypes(iface.mDeclaringType, bestIFaceEntry->mDeclaringType, isBetter, isWorse);
  1603. if (isBetter == isWorse)
  1604. {
  1605. // Failed
  1606. }
  1607. else
  1608. {
  1609. if (isBetter)
  1610. bestIFaceEntry = &iface;
  1611. }
  1612. }
  1613. }
  1614. if (bestIFaceEntry != NULL)
  1615. break;
  1616. checkTypeInst = checkTypeInst->mBaseType;
  1617. if ((checkTypeInst == NULL) && (checkType->HasWrappedRepresentation()))
  1618. {
  1619. auto underlyingType = checkType->GetUnderlyingType();
  1620. if ((underlyingType != NULL) && (underlyingType->IsWrappableType()))
  1621. checkTypeInst = mModule->GetWrappedStructType(underlyingType);
  1622. }
  1623. }
  1624. if (bestIFaceEntry != NULL)
  1625. {
  1626. auto ifaceMethodEntry = checkTypeInst->mInterfaceMethodTable[bestIFaceEntry->mStartInterfaceTableIdx + mBestMethodDef->mIdx];
  1627. BfMethodInstance* bestMethodInstance = ifaceMethodEntry.mMethodRef;
  1628. if (bestMethodInstance != NULL)
  1629. {
  1630. bool isMissingArg = false;
  1631. for (auto genericArg : mBestMethodGenericArguments)
  1632. {
  1633. if (genericArg == NULL)
  1634. isMissingArg = true;
  1635. }
  1636. if (!isMissingArg)
  1637. {
  1638. // Assert error state?
  1639. mBestMethodTypeInstance = ifaceMethodEntry.mMethodRef.mTypeInstance;
  1640. mBestMethodDef = bestMethodInstance->mMethodDef;
  1641. mBestMethodInstance = mModule->GetMethodInstance(mBestMethodTypeInstance, bestMethodInstance->mMethodDef, mBestMethodGenericArguments,
  1642. bestMethodInstance->mIsForeignMethodDef ? BfGetMethodInstanceFlag_ForeignMethodDef : BfGetMethodInstanceFlag_None,
  1643. bestMethodInstance->GetForeignType());
  1644. }
  1645. }
  1646. else
  1647. {
  1648. // Failed
  1649. mFakeConcreteTarget = true;
  1650. }
  1651. }
  1652. }
  1653. }
  1654. if ((target.mType->IsValueType()) && (mBestMethodTypeInstance->IsObject()) && (mBestMethodDef->mIsVirtual))
  1655. {
  1656. auto structType = target.mType->ToTypeInstance();
  1657. auto virtualMethodInstance = mModule->GetMethodInstance(mBestMethodTypeInstance, mBestMethodDef, BfTypeVector());
  1658. BF_ASSERT(virtualMethodInstance.mMethodInstance->mVirtualTableIdx != -1);
  1659. BfTypeInstance* boxedType;
  1660. if (structType->HasOverrideMethods())
  1661. {
  1662. // We don't actually need this boxed type, so just resolve it unreified
  1663. auto useModule = mModule->mContext->mUnreifiedModule;
  1664. boxedType = useModule->CreateBoxedType(target.mType);
  1665. useModule->PopulateType(boxedType, BfPopulateType_DataAndMethods);
  1666. useModule->AddDependency(boxedType, mModule->mCurTypeInstance, BfDependencyMap::DependencyFlag_Calls);
  1667. }
  1668. else
  1669. {
  1670. boxedType = mModule->mContext->mBfObjectType;
  1671. }
  1672. auto methodRef = boxedType->mVirtualMethodTable[virtualMethodInstance.mMethodInstance->mVirtualTableIdx];
  1673. if (methodRef.mImplementingMethod.mTypeInstance->IsBoxed())
  1674. {
  1675. auto useModule = mModule->mContext->mUnreifiedModule;
  1676. auto boxedMethodInstance = useModule->ReferenceExternalMethodInstance(methodRef.mImplementingMethod);
  1677. BfBoxedType* vBoxedType = (BfBoxedType*)methodRef.mImplementingMethod.mTypeInstance;
  1678. mBestMethodTypeInstance = vBoxedType->mElementType;
  1679. mBestMethodInstance = mModule->GetMethodInstance(mBestMethodTypeInstance, boxedMethodInstance.mMethodInstance->mMethodDef, BfTypeVector());
  1680. mBestMethodDef = mBestMethodInstance.mMethodInstance->mMethodDef;
  1681. }
  1682. else
  1683. {
  1684. mBestMethodTypeInstance = methodRef.mImplementingMethod.mTypeInstance;
  1685. mBestMethodInstance = mModule->ReferenceExternalMethodInstance(methodRef.mImplementingMethod);
  1686. mBestMethodDef = mBestMethodInstance.mMethodInstance->mMethodDef;
  1687. }
  1688. mBypassVirtual = true;
  1689. }
  1690. }
  1691. void BfMethodMatcher::CheckOuterTypeStaticMethods(BfTypeInstance* typeInstance, bool isFailurePass)
  1692. {
  1693. bool allowPrivate = true;
  1694. bool allowProtected = true;
  1695. auto curTypeInst = typeInstance;
  1696. auto curTypeDef = typeInstance->mTypeDef;
  1697. while (true)
  1698. {
  1699. curTypeDef->PopulateMemberSets();
  1700. BfMethodDef* nextMethodDef = NULL;
  1701. BfMemberSetEntry* entry;
  1702. if (curTypeDef->mMethodSet.TryGetWith(mMethodName, &entry))
  1703. nextMethodDef = (BfMethodDef*)entry->mMemberDef;
  1704. while (nextMethodDef != NULL)
  1705. {
  1706. auto checkMethod = nextMethodDef;
  1707. nextMethodDef = nextMethodDef->mNextWithSameName;
  1708. // These can only be invoked when the target itself is the interface
  1709. if (checkMethod->mExplicitInterface != NULL)
  1710. continue;
  1711. if ((checkMethod->mMethodType != BfMethodType_Normal) || (!checkMethod->mIsStatic))
  1712. continue;
  1713. if (checkMethod->mName != mMethodName)
  1714. continue;
  1715. if ((!isFailurePass) && (!mModule->CheckProtection(checkMethod->mProtection, allowProtected, allowPrivate)))
  1716. continue;
  1717. CheckMethod(curTypeInst, checkMethod, isFailurePass);
  1718. }
  1719. if (mBestMethodDef != NULL)
  1720. return;
  1721. auto baseType = curTypeInst->mBaseType;
  1722. if (baseType == NULL)
  1723. break;
  1724. curTypeDef = baseType->mTypeDef;
  1725. curTypeInst = baseType;
  1726. allowPrivate = false;
  1727. if ((isFailurePass) && (mBackupMethodDef != NULL))
  1728. break;
  1729. }
  1730. if (mBestMethodDef == NULL)
  1731. {
  1732. // FAILED, but select the first method which will fire an actual error on param type matching
  1733. mBestMethodDef = mBackupMethodDef;
  1734. }
  1735. if (mBestMethodDef == NULL)
  1736. {
  1737. // No explicit target - maybe this was a static call in the outer type?
  1738. auto outerType = mModule->GetOuterType(typeInstance);
  1739. if (outerType != NULL)
  1740. CheckOuterTypeStaticMethods(outerType, isFailurePass);
  1741. }
  1742. }
  1743. //////////////////////////////////////////////////////////////////////////
  1744. void BfResolvedArgs::HandleFixits(BfModule* module)
  1745. {
  1746. auto compiler = module->mCompiler;
  1747. if ((!compiler->IsAutocomplete()) || (compiler->mResolvePassData->mResolveType != BfResolveType_GetFixits))
  1748. return;
  1749. SetAndRestoreValue<bool> ignoreErrors(module->mIgnoreErrors, true);
  1750. for (int argIdx = 0; argIdx < (int)mResolvedArgs.size(); argIdx++)
  1751. {
  1752. auto& resolvedArg = mResolvedArgs[argIdx];
  1753. auto expr = BfNodeDynCast<BfExpression>(resolvedArg.mExpression);
  1754. if (expr != NULL)
  1755. {
  1756. module->CreateValueFromExpression(expr, resolvedArg.mExpectedType);
  1757. }
  1758. }
  1759. }
  1760. //////////////////////////////////////////////////////////////////////////
  1761. BfExprEvaluator::BfExprEvaluator(BfModule* module)
  1762. {
  1763. mBfEvalExprFlags = BfEvalExprFlags_None;
  1764. mModule = module;
  1765. mPropDef = NULL;
  1766. mPropSrc = NULL;
  1767. mPropGetMethodFlags = BfGetMethodInstanceFlag_None;
  1768. mPropCheckedKind = BfCheckedKind_NotSet;
  1769. mUsedAsStatement = false;
  1770. mPropDefBypassVirtual = false;
  1771. mExpectingType = NULL;
  1772. mFunctionBindResult = NULL;
  1773. mExplicitCast = false;
  1774. mDeferCallRef = NULL;
  1775. mDeferScopeAlloc = NULL;
  1776. mPrefixedAttributeState = NULL;
  1777. mResolveGenericParam = true;
  1778. mNoBind = false;
  1779. mResultLocalVar = NULL;
  1780. mResultLocalVarField = 0;
  1781. mResultLocalVarFieldCount = 0;
  1782. mResultLocalVarRefNode = NULL;
  1783. mIsVolatileReference = false;
  1784. mIsHeapReference = false;
  1785. mResultIsTempComposite = false;
  1786. mAllowReadOnlyReference = false;
  1787. mReceivingValue = NULL;
  1788. }
  1789. BfExprEvaluator::~BfExprEvaluator()
  1790. {
  1791. }
  1792. BfAutoComplete* BfExprEvaluator::GetAutoComplete()
  1793. {
  1794. if (mModule->mCompiler->mResolvePassData == NULL)
  1795. return NULL;
  1796. if ((mBfEvalExprFlags & BfEvalExprFlags_NoAutoComplete) != 0)
  1797. return NULL;
  1798. // For local methods- only process autocomplete on capture phase
  1799. if ((mModule->mCurMethodState != NULL) && (mModule->mCurMethodState->mClosureState != NULL) && (!mModule->mCurMethodState->mClosureState->mCapturing))
  1800. return NULL;
  1801. // if ((mModule->mCurMethodInstance != NULL) && (mModule->mCurMethodInstance->mMethodDef->mIsLocalMethod))
  1802. // return NULL;
  1803. return mModule->mCompiler->mResolvePassData->mAutoComplete;
  1804. }
  1805. BfType* BfExprEvaluator::BindGenericType(BfAstNode* node, BfType* bindType)
  1806. {
  1807. if ((mModule->mCurMethodState == NULL) || (mModule->mCurMethodInstance == NULL) || (bindType == NULL))
  1808. return bindType;
  1809. BF_ASSERT(!mModule->mCurMethodInstance->mIsUnspecializedVariation);
  1810. auto parser = node->GetSourceData()->ToParserData();
  1811. if (parser == NULL)
  1812. return bindType;
  1813. int64 nodeId = ((int64)parser->mDataId << 32) + node->GetSrcStart();
  1814. if (mModule->mCurMethodInstance->mIsUnspecialized)
  1815. {
  1816. if (!bindType->IsGenericParam())
  1817. return bindType;
  1818. (*mModule->mCurMethodState->mGenericTypeBindings)[nodeId] = bindType;
  1819. return bindType;
  1820. }
  1821. else
  1822. {
  1823. if (mModule->mCurMethodState->mGenericTypeBindings == NULL)
  1824. return bindType;
  1825. /*auto itr = mModule->mCurMethodState->mGenericTypeBindings->find(nodeId);
  1826. if (itr != mModule->mCurMethodState->mGenericTypeBindings->end())
  1827. return itr->second;*/
  1828. BfType** typePtr = NULL;
  1829. if (mModule->mCurMethodState->mGenericTypeBindings->TryGetValue(nodeId, &typePtr))
  1830. return *typePtr;
  1831. return bindType;
  1832. }
  1833. }
  1834. BfType * BfExprEvaluator::ResolveTypeRef(BfTypeReference* typeRef, BfPopulateType populateType, BfResolveTypeRefFlags resolveFlags)
  1835. {
  1836. if (mExpectingType != NULL)
  1837. {
  1838. if (auto namedTypeRef = BfNodeDynCastExact<BfNamedTypeReference>(typeRef))
  1839. {
  1840. if (namedTypeRef->ToString() == "ExpectedType")
  1841. {
  1842. return mModule->ResolveTypeResult(typeRef, mExpectingType, populateType, resolveFlags);
  1843. }
  1844. }
  1845. }
  1846. return mModule->ResolveTypeRef(typeRef, populateType, resolveFlags);
  1847. }
  1848. void BfExprEvaluator::ResolveGenericType()
  1849. {
  1850. if (mResult)
  1851. {
  1852. if (mModule->IsUnboundGeneric(mResult.mType))
  1853. mResult.mType = mModule->GetPrimitiveType(BfTypeCode_Var);
  1854. //mResult.mType = mModule->ResolveGenericType(mResult.mType, true);
  1855. }
  1856. }
  1857. void BfExprEvaluator::Evaluate(BfAstNode* astNode, bool propogateNullConditional, bool ignoreNullConditional, bool allowSplat)
  1858. {
  1859. BP_ZONE("BfExprEvaluator::Evaluate");
  1860. // ParenthesizedExpression breaks null conditional chain
  1861. if (astNode->IsExact<BfParenthesizedExpression>())
  1862. propogateNullConditional = false;
  1863. BfPendingNullConditional* pendingNullCond = NULL;
  1864. if (mModule->mCurMethodState != NULL)
  1865. {
  1866. pendingNullCond = mModule->mCurMethodState->mPendingNullConditional;
  1867. if (!propogateNullConditional)
  1868. mModule->mCurMethodState->mPendingNullConditional = NULL;
  1869. }
  1870. astNode->Accept(this);
  1871. GetResult();
  1872. if ((mResultIsTempComposite) && (mResult.IsAddr()))
  1873. mResult.mKind = BfTypedValueKind_TempAddr;
  1874. if ((!allowSplat) && (mResult.IsSplat()))
  1875. mResult = mModule->AggregateSplat(mResult);
  1876. if ((mBfEvalExprFlags & BfEvalExprFlags_AllowIntUnknown) == 0)
  1877. mModule->FixIntUnknown(mResult);
  1878. if ((!propogateNullConditional) && (mModule->mCurMethodState != NULL))
  1879. {
  1880. if (mModule->mCurMethodState->mPendingNullConditional != NULL)
  1881. mResult = mModule->FlushNullConditional(mResult, ignoreNullConditional);
  1882. mModule->mCurMethodState->mPendingNullConditional = pendingNullCond;
  1883. }
  1884. }
  1885. void BfExprEvaluator::Visit(BfTypeReference* typeRef)
  1886. {
  1887. mResult.mType = ResolveTypeRef(typeRef, BfPopulateType_Declaration);
  1888. }
  1889. void BfExprEvaluator::Visit(BfAttributedExpression* attribExpr)
  1890. {
  1891. BfAttributeState attributeState;
  1892. attributeState.mTarget = (BfAttributeTargets)(BfAttributeTargets_Invocation | BfAttributeTargets_MemberAccess);
  1893. attributeState.mCustomAttributes = mModule->GetCustomAttributes(attribExpr->mAttributes, attributeState.mTarget);
  1894. SetAndRestoreValue<BfAttributeState*> prevAttributeState(mModule->mAttributeState, &attributeState);
  1895. VisitChild(attribExpr->mExpression);
  1896. if (!attributeState.mUsed)
  1897. {
  1898. mModule->Fail("Unused attributes", attribExpr->mAttributes);
  1899. }
  1900. }
  1901. void BfExprEvaluator::Visit(BfBlock* blockExpr)
  1902. {
  1903. if (mModule->mCurMethodState == NULL)
  1904. {
  1905. mModule->Fail("Illegal use of block expression", blockExpr);
  1906. return;
  1907. }
  1908. auto autoComplete = GetAutoComplete();
  1909. if ((autoComplete != NULL) && (autoComplete->mMethodMatchInfo != NULL) && (autoComplete->IsAutocompleteNode(blockExpr)))
  1910. {
  1911. // Don't show outer method match info when our cursor is inside a block (being passed as a parameter)
  1912. autoComplete->RemoveMethodMatchInfo();
  1913. }
  1914. if (blockExpr->mChildArr.IsEmpty())
  1915. {
  1916. mModule->Fail("An empty block cannot be used as an expression", blockExpr);
  1917. return;
  1918. }
  1919. bool lastWasResultExpr = false;
  1920. if (auto lastExpr = BfNodeDynCast<BfExpressionStatement>(blockExpr->mChildArr.GetLast()))
  1921. {
  1922. if (!lastExpr->IsMissingSemicolon())
  1923. mModule->Fail("Expression blocks must end in an expression which is missing its terminating semicolon", lastExpr->mTrailingSemicolon);
  1924. }
  1925. else if (auto lastExpr = BfNodeDynCast<BfExpression>(blockExpr->mChildArr.GetLast()))
  1926. {
  1927. // Expression
  1928. }
  1929. else
  1930. {
  1931. mModule->Fail("Expression blocks must end with an expression", blockExpr);
  1932. }
  1933. mModule->VisitEmbeddedStatement(blockExpr, this);
  1934. }
  1935. bool BfExprEvaluator::CheckVariableDeclaration(BfAstNode* checkNode, bool requireSimpleIfExpr, bool exprMustBeTrue, bool silentFail)
  1936. {
  1937. BfAstNode* checkChild = checkNode;
  1938. bool foundIf = false;
  1939. auto parentNodeEntry = mModule->mParentNodeEntry;
  1940. if (parentNodeEntry != NULL)
  1941. {
  1942. if (BfNodeIsA<BfInvocationExpression>(parentNodeEntry->mNode))
  1943. {
  1944. checkChild = parentNodeEntry->mNode;
  1945. parentNodeEntry = parentNodeEntry->mPrev;
  1946. }
  1947. }
  1948. while (parentNodeEntry != NULL)
  1949. {
  1950. BfAstNode* checkParent = parentNodeEntry->mNode;
  1951. if (auto binOpExpr = BfNodeDynCastExact<BfBinaryOperatorExpression>(checkParent))
  1952. {
  1953. if (binOpExpr->mOp == BfBinaryOp_ConditionalAnd)
  1954. {
  1955. // This is always okay
  1956. }
  1957. else if ((binOpExpr->mOp == BfBinaryOp_ConditionalOr) && (!exprMustBeTrue))
  1958. {
  1959. bool matches = false;
  1960. auto checkRight = binOpExpr->mRight;
  1961. while (checkRight != NULL)
  1962. {
  1963. if (checkRight == checkChild)
  1964. {
  1965. matches = true;
  1966. break;
  1967. }
  1968. if (auto parenExpr = BfNodeDynCast<BfParenthesizedExpression>(checkRight))
  1969. checkRight = parenExpr->mExpression;
  1970. else
  1971. {
  1972. break;
  1973. }
  1974. }
  1975. if (matches)
  1976. {
  1977. if (!silentFail)
  1978. mModule->Fail("Conditional short-circuiting may skip variable initialization", binOpExpr->mOpToken);
  1979. return false;
  1980. }
  1981. }
  1982. else
  1983. {
  1984. if (exprMustBeTrue)
  1985. {
  1986. if (!silentFail)
  1987. mModule->Fail("Operator cannot be used with variable initialization", binOpExpr->mOpToken);
  1988. return false;
  1989. }
  1990. }
  1991. }
  1992. else if (auto parenExpr = BfNodeDynCast<BfParenthesizedExpression>(checkParent))
  1993. {
  1994. // This is okay
  1995. }
  1996. else if (auto unaryOp = BfNodeDynCast<BfUnaryOperatorExpression>(checkParent))
  1997. {
  1998. if (exprMustBeTrue)
  1999. {
  2000. if (!silentFail)
  2001. mModule->Fail("Operator cannot be used with variable initialization", unaryOp->mOpToken);
  2002. return false;
  2003. }
  2004. }
  2005. else if (auto ifStmt = BfNodeDynCast<BfIfStatement>(checkParent))
  2006. {
  2007. // Done
  2008. foundIf = true;
  2009. break;
  2010. }
  2011. else
  2012. {
  2013. if (requireSimpleIfExpr)
  2014. {
  2015. if (!silentFail)
  2016. mModule->Fail("Variable declaration expression can only be contained in simple 'if' expressions", checkNode);
  2017. return false;
  2018. }
  2019. break;
  2020. }
  2021. checkChild = parentNodeEntry->mNode;
  2022. parentNodeEntry = parentNodeEntry->mPrev;
  2023. }
  2024. return foundIf;
  2025. }
  2026. bool BfExprEvaluator::HasVariableDeclaration(BfAstNode* checkNode)
  2027. {
  2028. BfVarDeclChecker checker;
  2029. checker.VisitChild(checkNode);
  2030. return checker.mHasVarDecl;
  2031. }
  2032. void BfExprEvaluator::Visit(BfVariableDeclaration* varDecl)
  2033. {
  2034. mModule->UpdateExprSrcPos(varDecl);
  2035. CheckVariableDeclaration(varDecl, true, false, false);
  2036. if (varDecl->mInitializer == NULL)
  2037. {
  2038. mModule->Fail("Variable declarations used as expressions must have an initializer", varDecl);
  2039. }
  2040. BfTupleExpression* tupleVariableDeclaration = BfNodeDynCast<BfTupleExpression>(varDecl->mNameNode);
  2041. if (tupleVariableDeclaration != NULL)
  2042. {
  2043. mModule->Fail("Tuple variable declarations cannot be used as expressions", varDecl);
  2044. mModule->HandleTupleVariableDeclaration(varDecl);
  2045. }
  2046. else
  2047. mModule->HandleVariableDeclaration(varDecl, this);
  2048. }
  2049. void BfExprEvaluator::Visit(BfCaseExpression* caseExpr)
  2050. {
  2051. if (caseExpr->mEqualsNode != NULL)
  2052. {
  2053. mModule->Warn(0, "Deprecated case syntax", caseExpr->mEqualsNode);
  2054. }
  2055. BfTypedValue caseValAddr;
  2056. if (caseExpr->mValueExpression != NULL)
  2057. caseValAddr = mModule->CreateValueFromExpression(caseExpr->mValueExpression);
  2058. if (caseValAddr.mType != NULL)
  2059. mModule->mBfIRBuilder->PopulateType(caseValAddr.mType);
  2060. if (mModule->mCurMethodState->mDeferredLocalAssignData != NULL)
  2061. mModule->mCurMethodState->mDeferredLocalAssignData->BreakExtendChain();
  2062. if (auto bindExpr = BfNodeDynCast<BfEnumCaseBindExpression>(caseExpr->mCaseExpression))
  2063. {
  2064. if (caseValAddr)
  2065. {
  2066. BfTypedValue enumTagVal;
  2067. if (caseValAddr.mType->IsPayloadEnum())
  2068. {
  2069. int dscrDataIdx;
  2070. auto dscrType = caseValAddr.mType->ToTypeInstance()->GetDiscriminatorType(&dscrDataIdx);
  2071. enumTagVal = BfTypedValue(mModule->ExtractValue(caseValAddr, dscrDataIdx), dscrType);
  2072. }
  2073. else
  2074. enumTagVal = mModule->GetDefaultTypedValue(mModule->GetPrimitiveType(BfTypeCode_Int32));
  2075. mResult = mModule->HandleCaseBind(caseValAddr, enumTagVal, bindExpr);
  2076. return;
  2077. }
  2078. }
  2079. if ((caseValAddr) && (caseValAddr.mType->IsPayloadEnum()))
  2080. {
  2081. bool hasVariable = false;
  2082. bool hasOut = false;
  2083. bool clearOutOnMismatch = false;
  2084. if (auto invocateExpr = BfNodeDynCast<BfInvocationExpression>(caseExpr->mCaseExpression))
  2085. {
  2086. for (auto arg : invocateExpr->mArguments)
  2087. {
  2088. if (auto varDecl = BfNodeDynCast<BfVariableDeclaration>(arg))
  2089. {
  2090. hasVariable = true;
  2091. }
  2092. else if (auto unaryOpExpr = BfNodeDynCast<BfUnaryOperatorExpression>(arg))
  2093. {
  2094. if (unaryOpExpr->mOpToken->mToken == BfToken_Out)
  2095. {
  2096. hasOut = true;
  2097. }
  2098. }
  2099. }
  2100. }
  2101. if (hasVariable)
  2102. {
  2103. CheckVariableDeclaration(caseExpr, false, true, false);
  2104. }
  2105. // We can avoid clearing on mismatch if we can be sure we ONLY enter the true block on a match.
  2106. // An example of requiring clearing is: if ((result case .Ok(out val)) || (force))
  2107. if (hasOut)
  2108. clearOutOnMismatch = !CheckVariableDeclaration(caseExpr, true, true, true);
  2109. int dscrDataIdx;
  2110. auto dscrType = caseValAddr.mType->ToTypeInstance()->GetDiscriminatorType(&dscrDataIdx);
  2111. auto enumTagVal = mModule->LoadValue(mModule->ExtractValue(caseValAddr, NULL, 2));
  2112. int uncondTagId = -1;
  2113. bool hadConditional = false;
  2114. mResult = mModule->TryCaseEnumMatch(caseValAddr, enumTagVal, caseExpr->mCaseExpression, NULL, NULL, NULL, uncondTagId, hadConditional, clearOutOnMismatch);
  2115. if (mResult)
  2116. return;
  2117. }
  2118. if ((caseValAddr) && (caseValAddr.mType->IsVar()))
  2119. {
  2120. auto invocationExpr = BfNodeDynCast<BfInvocationExpression>(caseExpr->mCaseExpression);
  2121. if (invocationExpr != NULL)
  2122. {
  2123. for (auto expr : invocationExpr->mArguments)
  2124. {
  2125. if (expr == NULL)
  2126. continue;
  2127. if (auto varDecl = BfNodeDynCast<BfVariableDeclaration>(expr))
  2128. {
  2129. auto localVar = mModule->HandleVariableDeclaration(varDecl, BfTypedValue());
  2130. if (localVar != NULL)
  2131. localVar->mReadFromId = 0;
  2132. }
  2133. }
  2134. }
  2135. auto boolType = mModule->GetPrimitiveType(BfTypeCode_Boolean);
  2136. mResult = mModule->GetDefaultTypedValue(boolType);
  2137. return;
  2138. }
  2139. if ((caseValAddr.mType != NULL) && (caseValAddr.mType->IsPointer()))
  2140. {
  2141. caseValAddr = mModule->LoadValue(caseValAddr);
  2142. caseValAddr = BfTypedValue(caseValAddr.mValue, caseValAddr.mType->GetUnderlyingType(), true);
  2143. }
  2144. auto boolType = mModule->GetPrimitiveType(BfTypeCode_Boolean);
  2145. BfTypedValue caseMatch;
  2146. if (caseExpr->mCaseExpression != NULL)
  2147. caseMatch = mModule->CreateValueFromExpression(caseExpr->mCaseExpression, caseValAddr.mType, BfEvalExprFlags_AllowEnumId);
  2148. if ((!caseMatch) || (!caseValAddr))
  2149. {
  2150. mResult = mModule->GetDefaultTypedValue(boolType);
  2151. return;
  2152. }
  2153. if (caseValAddr.mType == caseMatch.mType)
  2154. {
  2155. if (((caseValAddr.mType->IsEnum()) && (caseValAddr.mType->IsStruct())) &&
  2156. ((caseMatch) && (caseMatch.mType->IsPayloadEnum()) && (caseMatch.mValue.IsConst())))
  2157. {
  2158. BfTypedValue enumTagVal = mModule->LoadValue(mModule->ExtractValue(caseValAddr, NULL, 2));
  2159. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateCmpEQ(enumTagVal.mValue, caseMatch.mValue), boolType);
  2160. return;
  2161. }
  2162. }
  2163. else
  2164. {
  2165. // We need to get rid of the int-const for the 'scalar match'. We get a full payload enum value so we can
  2166. // possibly use it in a user-defined comparison operator
  2167. if ((caseMatch.mType->IsStruct()) && (caseMatch.mValue.IsConst()))
  2168. {
  2169. // Is it possible this could throw an error twice? Hope not.
  2170. caseMatch = mModule->CreateValueFromExpression(caseExpr->mCaseExpression, NULL);
  2171. }
  2172. }
  2173. PerformBinaryOperation(caseExpr->mCaseExpression, caseExpr->mValueExpression, BfBinaryOp_Equality, caseExpr->mEqualsNode, BfBinOpFlag_None, caseValAddr, caseMatch);
  2174. }
  2175. void BfExprEvaluator::Visit(BfTypedValueExpression* typedValueExpr)
  2176. {
  2177. mResult = typedValueExpr->mTypedValue;
  2178. }
  2179. static bool IsCharType(BfTypeCode typeCode)
  2180. {
  2181. switch (typeCode)
  2182. {
  2183. case BfTypeCode_Char8:
  2184. case BfTypeCode_Char16:
  2185. case BfTypeCode_Char32:
  2186. return true;
  2187. default:
  2188. return false;
  2189. }
  2190. }
  2191. void BfExprEvaluator::GetLiteral(BfAstNode* refNode, const BfVariant& variant)
  2192. {
  2193. switch (variant.mTypeCode)
  2194. {
  2195. case BfTypeCode_NullPtr:
  2196. {
  2197. auto nullType = mModule->ResolveTypeDef(mModule->mSystem->mTypeNullPtr);
  2198. /*mResult = BfTypedValue(ConstantPointerNull::get((PointerType*) nullType->mIRType), nullType);*/
  2199. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConstNull(), nullType);
  2200. }
  2201. break;
  2202. case BfTypeCode_CharPtr:
  2203. {
  2204. if ((mExpectingType != NULL) && (mExpectingType->IsSizedArray()))
  2205. {
  2206. auto sizedArray = (BfSizedArrayType*)mExpectingType;
  2207. if (sizedArray->mElementType == mModule->GetPrimitiveType(BfTypeCode_Char8))
  2208. {
  2209. if (variant.mString->GetLength() > sizedArray->mElementCount)
  2210. {
  2211. mModule->Fail(StrFormat("String literal is too long to fit into '%s'", mModule->TypeToString(sizedArray).c_str()), refNode);
  2212. }
  2213. Array<BfIRValue> charValues;
  2214. for (int i = 0; i < (int)BF_MIN(variant.mString->GetLength(), sizedArray->mElementCount); i++)
  2215. {
  2216. char c = (*variant.mString)[i];
  2217. charValues.Add(mModule->mBfIRBuilder->CreateConst(BfTypeCode_Char8, (int)(uint8)c));
  2218. }
  2219. if (sizedArray->mElementCount > charValues.size())
  2220. charValues.Add(mModule->mBfIRBuilder->CreateConst(BfTypeCode_Char8, 0));
  2221. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConstArray(mModule->mBfIRBuilder->MapType(sizedArray), charValues), sizedArray);
  2222. return;
  2223. }
  2224. }
  2225. if ((mExpectingType == NULL) || (!mExpectingType->IsPointer()))
  2226. {
  2227. mResult = BfTypedValue(mModule->GetStringObjectValue(*variant.mString),
  2228. mModule->ResolveTypeDef(mModule->mCompiler->mStringTypeDef));
  2229. }
  2230. else
  2231. {
  2232. auto charType = mModule->GetPrimitiveType(BfTypeCode_Char8);
  2233. auto charPtrType = mModule->CreatePointerType(charType);
  2234. mResult = BfTypedValue(mModule->GetStringCharPtr(*variant.mString),
  2235. charPtrType);
  2236. }
  2237. }
  2238. break;
  2239. case BfTypeCode_Boolean:
  2240. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConst(variant.mTypeCode, variant.mUInt64), mModule->GetPrimitiveType(variant.mTypeCode));
  2241. break;
  2242. case BfTypeCode_Char8:
  2243. case BfTypeCode_Char16:
  2244. case BfTypeCode_Char32:
  2245. case BfTypeCode_Int8:
  2246. case BfTypeCode_UInt8:
  2247. case BfTypeCode_Int16:
  2248. case BfTypeCode_UInt16:
  2249. case BfTypeCode_Int32:
  2250. case BfTypeCode_UInt32:
  2251. case BfTypeCode_Int64:
  2252. case BfTypeCode_UInt64:
  2253. case BfTypeCode_IntPtr:
  2254. case BfTypeCode_UIntPtr:
  2255. case BfTypeCode_IntUnknown:
  2256. case BfTypeCode_UIntUnknown:
  2257. if ((mExpectingType != NULL) && (mExpectingType->IsIntegral()) && (mExpectingType->IsChar() == IsCharType(variant.mTypeCode)))
  2258. {
  2259. auto primType = (BfPrimitiveType*)mExpectingType;
  2260. if (mModule->mSystem->DoesLiteralFit(primType->mTypeDef->mTypeCode, variant.mInt64))
  2261. {
  2262. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConst(primType->mTypeDef->mTypeCode, variant.mUInt64), mExpectingType);
  2263. break;
  2264. }
  2265. }
  2266. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConst(variant.mTypeCode, variant.mUInt64), mModule->GetPrimitiveType(variant.mTypeCode));
  2267. break;
  2268. case BfTypeCode_Single:
  2269. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConst(variant.mTypeCode, variant.mSingle), mModule->GetPrimitiveType(variant.mTypeCode));
  2270. break;
  2271. case BfTypeCode_Double:
  2272. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConst(variant.mTypeCode, variant.mDouble), mModule->GetPrimitiveType(variant.mTypeCode));
  2273. break;
  2274. default:
  2275. mModule->Fail("Invalid literal", refNode);
  2276. break;
  2277. }
  2278. }
  2279. void BfExprEvaluator::Visit(BfLiteralExpression* literalExpr)
  2280. {
  2281. switch (literalExpr->mValue.mWarnType)
  2282. {
  2283. case BfWarning_BF4201_Only7Hex:
  2284. mModule->Warn(BfWarning_BF4201_Only7Hex, "Only 7 hex digits specified. Add a leading zero to clarify intention.", literalExpr);
  2285. break;
  2286. case BfWarning_BF4202_TooManyHexForInt:
  2287. mModule->Warn(BfWarning_BF4202_TooManyHexForInt, "Too many hex digits for an int, but too few for a long. Use 'L' suffix if a long was intended.", literalExpr);
  2288. break;
  2289. }
  2290. GetLiteral(literalExpr, literalExpr->mValue);
  2291. }
  2292. BfTypedValue BfExprEvaluator::LoadLocal(BfLocalVariable* varDecl, bool allowRef)
  2293. {
  2294. if (!mModule->mIsInsideAutoComplete)
  2295. varDecl->mReadFromId = mModule->mCurMethodState->GetRootMethodState()->mCurAccessId++;
  2296. // The Beef backend prefers readonly addrs since that reduces register pressure, whereas
  2297. // LLVM prefers values to avoid memory loads. This only applies to primitive types...
  2298. bool preferValue = (varDecl->mResolvedType->IsPrimitiveType()) && (!mModule->IsTargetingBeefBackend());
  2299. BfTypedValue localResult;
  2300. if (varDecl->mIsThis)
  2301. {
  2302. return mModule->GetThis();
  2303. }
  2304. else if (varDecl->mConstValue)
  2305. {
  2306. localResult = BfTypedValue(varDecl->mConstValue, varDecl->mResolvedType, false);
  2307. }
  2308. else if (varDecl->mIsSplat)
  2309. {
  2310. if ((!preferValue) && (varDecl->mAddr))
  2311. localResult = BfTypedValue(varDecl->mAddr, varDecl->mResolvedType, BfTypedValueKind_SplatHead);
  2312. else if (!varDecl->mResolvedType->IsValuelessType())
  2313. localResult = BfTypedValue(varDecl->mValue, varDecl->mResolvedType, BfTypedValueKind_SplatHead);
  2314. else
  2315. localResult = BfTypedValue(varDecl->mValue, varDecl->mResolvedType);
  2316. //BF_ASSERT(varDecl->mValue.IsArg());
  2317. }
  2318. else if ((varDecl->mValue) && ((varDecl->mIsReadOnly && preferValue) || (!varDecl->mAddr)))
  2319. {
  2320. if ((varDecl->mResolvedType->IsRef()) && (!allowRef))
  2321. {
  2322. BfRefType* refType = (BfRefType*)varDecl->mResolvedType;
  2323. BfType* innerType = refType->mElementType;
  2324. if (innerType->IsGenericParam())
  2325. {
  2326. if (refType->mRefKind == BfRefType::RefKind_Mut)
  2327. {
  2328. localResult = BfTypedValue(varDecl->mValue, innerType, BfTypedValueKind_MutableValue);
  2329. return localResult;
  2330. }
  2331. else
  2332. {
  2333. localResult = BfTypedValue(varDecl->mValue, innerType, BfTypedValueKind_Addr);
  2334. return localResult;
  2335. }
  2336. }
  2337. localResult = BfTypedValue(varDecl->mValue, innerType, BfTypedValueKind_Addr);
  2338. }
  2339. else
  2340. {
  2341. BfTypedValueKind kind;
  2342. if ((varDecl->mResolvedType->IsComposite()) && (varDecl->IsParam()) && (mModule->mCurMethodState->mMixinState == NULL))
  2343. kind = varDecl->mIsReadOnly ? BfTypedValueKind_ReadOnlyAddr : BfTypedValueKind_Addr;
  2344. else
  2345. kind = BfTypedValueKind_Value;
  2346. localResult = BfTypedValue(varDecl->mValue, varDecl->mResolvedType, kind);
  2347. }
  2348. }
  2349. else if (varDecl->mAddr)
  2350. {
  2351. if ((varDecl->mResolvedType->IsRef()) && (!allowRef))
  2352. {
  2353. BfRefType* refType = (BfRefType*)varDecl->mResolvedType;
  2354. BfType* innerType = refType->mElementType;
  2355. if (innerType->IsValuelessType())
  2356. {
  2357. if (refType->mRefKind == BfRefType::RefKind_Mut)
  2358. return BfTypedValue(mModule->mBfIRBuilder->GetFakeVal(), innerType, BfTypedValueKind_MutableValue);
  2359. return BfTypedValue(mModule->mBfIRBuilder->GetFakeVal(), innerType, varDecl->mIsReadOnly ? BfTypedValueKind_ReadOnlyAddr : BfTypedValueKind_Addr);
  2360. }
  2361. if (refType->mRefKind == BfRefType::RefKind_Mut)
  2362. {
  2363. if (innerType->IsGenericParam())
  2364. {
  2365. localResult = BfTypedValue(mModule->mBfIRBuilder->CreateAlignedLoad(varDecl->mAddr, varDecl->mResolvedType->mAlign), innerType, BfTypedValueKind_MutableValue);
  2366. return localResult;
  2367. }
  2368. }
  2369. localResult = BfTypedValue(mModule->mBfIRBuilder->CreateAlignedLoad(varDecl->mAddr, varDecl->mResolvedType->mAlign), innerType, varDecl->mIsReadOnly ? BfTypedValueKind_ReadOnlyAddr : BfTypedValueKind_Addr);
  2370. }
  2371. else if (varDecl->mHasLocalStructBacking)
  2372. {
  2373. // varDecl->mAddr is a "struct**"
  2374. localResult = BfTypedValue(mModule->mBfIRBuilder->CreateAlignedLoad(varDecl->mAddr, varDecl->mResolvedType->mAlign), varDecl->mResolvedType, true);
  2375. }
  2376. else
  2377. localResult = BfTypedValue(varDecl->mAddr, varDecl->mResolvedType, varDecl->mIsReadOnly ? BfTypedValueKind_ReadOnlyAddr : BfTypedValueKind_Addr);
  2378. }
  2379. else if (varDecl->mResolvedType->IsValuelessType())
  2380. {
  2381. if ((varDecl->mResolvedType->IsRef()) && (!allowRef))
  2382. {
  2383. BfRefType* refType = (BfRefType*)varDecl->mResolvedType;
  2384. BfType* innerType = refType->mElementType;
  2385. localResult = BfTypedValue(mModule->mBfIRBuilder->GetFakeVal(), innerType, true);
  2386. return localResult;
  2387. }
  2388. localResult = BfTypedValue(mModule->mBfIRBuilder->GetFakeVal(), varDecl->mResolvedType, true);
  2389. }
  2390. else if (varDecl->mCompositeCount >= 0)
  2391. {
  2392. localResult = BfTypedValue(BfIRValue(), mModule->GetPrimitiveType(BfTypeCode_None));
  2393. }
  2394. else
  2395. {
  2396. BF_ASSERT((mModule->mCurMethodState->mClosureState != NULL) || (mModule->mBfIRBuilder->mIgnoreWrites));
  2397. // Just temporary
  2398. auto varType = varDecl->mResolvedType;
  2399. auto allocType = varType;
  2400. if (varType->IsRef())
  2401. {
  2402. BfRefType* refType = (BfRefType*)varType;
  2403. allocType = refType->mElementType;
  2404. }
  2405. auto declType = varDecl->mResolvedType;
  2406. if (declType->IsRef())
  2407. {
  2408. BfRefType* refType = (BfRefType*)declType;
  2409. declType = refType->mElementType;
  2410. }
  2411. mModule->PopulateType(allocType);
  2412. varDecl->mAddr = mModule->mBfIRBuilder->CreateAlloca(mModule->mBfIRBuilder->MapType(allocType));
  2413. localResult = BfTypedValue(varDecl->mAddr, declType, true);
  2414. return localResult;
  2415. }
  2416. if ((varDecl->mIsThis) && (localResult.mKind == BfTypedValueKind_Value))
  2417. localResult.mKind = BfTypedValueKind_ThisValue;
  2418. return localResult;
  2419. }
  2420. BfTypedValue BfExprEvaluator::LookupIdentifier(BfAstNode* refNode, const StringImpl& findName, bool ignoreInitialError, bool* hadError)
  2421. {
  2422. auto identifierNode = BfNodeDynCast<BfIdentifierNode>(refNode);
  2423. if (mModule->mCurMethodState != NULL)
  2424. {
  2425. auto rootMethodState = mModule->mCurMethodState->GetRootMethodState();
  2426. auto checkMethodState = mModule->mCurMethodState;
  2427. bool isMixinOuterVariablePass = false;
  2428. while (checkMethodState != NULL)
  2429. {
  2430. BP_ZONE("LookupIdentifier:LocalVar");
  2431. BfTypeInstance* closureTypeInst = NULL;
  2432. if ((checkMethodState->mClosureState != NULL) && (checkMethodState->mClosureState->mClosureType != NULL) && (!checkMethodState->mClosureState->mCapturing))
  2433. {
  2434. closureTypeInst = mModule->mCurMethodState->mClosureState->mClosureType;
  2435. }
  2436. int varSkipCount = 0;
  2437. StringT<128> wantName = findName;
  2438. while (wantName.StartsWith("@"))
  2439. {
  2440. varSkipCount++;
  2441. wantName.Remove(0);
  2442. }
  2443. if (wantName.IsEmpty())
  2444. {
  2445. mModule->Fail("Shadowed variable name expected after '@'", refNode);
  2446. }
  2447. BfLocalVarEntry* entry;
  2448. if (checkMethodState->mLocalVarSet.TryGetWith<StringImpl&>(wantName, &entry))
  2449. {
  2450. auto varDecl = entry->mLocalVar;
  2451. while ((varSkipCount > 0) && (varDecl != NULL))
  2452. {
  2453. varDecl = varDecl->mShadowedLocal;
  2454. varSkipCount--;
  2455. }
  2456. if (varDecl->mNotCaptured)
  2457. {
  2458. mModule->Fail("Local variable is not captured", refNode);
  2459. }
  2460. if ((varSkipCount == 0) && (varDecl != NULL))
  2461. {
  2462. if ((closureTypeInst != NULL) && (wantName == "this"))
  2463. break;
  2464. if ((varDecl->mCompositeCount >= 0) && ((mBfEvalExprFlags & BfEvalExprFlags_AllowParamsExpr) == 0))
  2465. {
  2466. mModule->Fail("Invalid use of 'params' parameter", refNode);
  2467. }
  2468. if (varDecl->mResolvedType->IsVoid())
  2469. {
  2470. if ((varDecl->mIsReadOnly) && (varDecl->mParamIdx == -2) && (varDecl->mParamFailed))
  2471. {
  2472. BF_ASSERT(mModule->mCurMethodInstance->mMethodDef->mMethodType == BfMethodType_CtorCalcAppend);
  2473. 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);
  2474. }
  2475. }
  2476. BfTypedValue localResult = LoadLocal(varDecl);
  2477. auto autoComplete = GetAutoComplete();
  2478. if (identifierNode != NULL)
  2479. {
  2480. if (autoComplete != NULL)
  2481. autoComplete->CheckLocalRef(identifierNode, varDecl);
  2482. if (((mModule->mCurMethodState->mClosureState == NULL) || (mModule->mCurMethodState->mClosureState->mCapturing)) &&
  2483. (mModule->mCompiler->mResolvePassData != NULL) && (mModule->mCurMethodInstance != NULL))
  2484. mModule->mCompiler->mResolvePassData->HandleLocalReference(identifierNode, varDecl->mNameNode, mModule->mCurTypeInstance->mTypeDef, rootMethodState->mMethodInstance->mMethodDef, varDecl->mLocalVarId);
  2485. }
  2486. if (!isMixinOuterVariablePass)
  2487. {
  2488. mResultLocalVar = varDecl;
  2489. mResultLocalVarRefNode = identifierNode;
  2490. }
  2491. return localResult;
  2492. }
  2493. }
  2494. // Check for the captured locals. It's important we do it here so we get local-first precedence still
  2495. if (closureTypeInst != NULL)
  2496. {
  2497. closureTypeInst->mTypeDef->PopulateMemberSets();
  2498. BfMemberSetEntry* memberSetEntry = NULL;
  2499. if (closureTypeInst->mTypeDef->mFieldSet.TryGetWith(findName, &memberSetEntry))
  2500. {
  2501. auto fieldDef = (BfFieldDef*)memberSetEntry->mMemberDef;
  2502. auto& field = closureTypeInst->mFieldInstances[fieldDef->mIdx];
  2503. if (!field.mResolvedType->IsValuelessType())
  2504. {
  2505. if (mModule->mCurMethodState->mClosureState->mCapturing)
  2506. {
  2507. mModule->mCurMethodState->mClosureState->mReferencedOuterClosureMembers.Add(&field);
  2508. return mModule->GetDefaultTypedValue(field.mResolvedType);
  2509. }
  2510. auto localVar = mModule->mCurMethodState->mLocals[0];
  2511. auto thisValue = localVar->mValue;
  2512. mModule->mBfIRBuilder->PopulateType(localVar->mResolvedType);
  2513. BfTypedValue result = BfTypedValue(mModule->mBfIRBuilder->CreateInBoundsGEP(thisValue, 0, field.mDataIdx), field.mResolvedType, true);
  2514. if (field.mResolvedType->IsRef())
  2515. {
  2516. auto refType = (BfRefType*)field.mResolvedType;
  2517. auto underlyingType = refType->GetUnderlyingType();
  2518. result = BfTypedValue(mModule->mBfIRBuilder->CreateLoad(result.mValue), underlyingType, true);
  2519. }
  2520. else if (fieldDef->mIsReadOnly)
  2521. result = mModule->LoadValue(result);
  2522. mResultLocalVar = localVar;
  2523. mResultLocalVarField = -(field.mMergedDataIdx + 1);
  2524. return result;
  2525. }
  2526. }
  2527. }
  2528. if ((checkMethodState->mClosureState != NULL) && (checkMethodState->mClosureState->mCapturing) /*&& (checkMethodState->mClosureState->mIsLocalMethod)*/)
  2529. {
  2530. checkMethodState = checkMethodState->mPrevMethodState;
  2531. continue;
  2532. }
  2533. // Allow local mixin to see outside variables during its processing -- since we don't actually "capture" those into params
  2534. bool isLocalMixinProcessing = false;
  2535. if ((checkMethodState->mClosureState != NULL) && (!checkMethodState->mClosureState->mCapturing) && (closureTypeInst == NULL) &&
  2536. (mModule->mCurMethodInstance->mMethodDef->mMethodType == BfMethodType_Mixin))
  2537. isLocalMixinProcessing = true;
  2538. if (!isLocalMixinProcessing)
  2539. break;
  2540. isMixinOuterVariablePass = true;
  2541. checkMethodState = checkMethodState->mPrevMethodState;
  2542. }
  2543. }
  2544. BfTypedValue thisValue = mModule->GetThis();
  2545. bool forcedIFaceLookup = false;
  2546. if ((mModule->mCurMethodInstance != NULL) && (mModule->mCurMethodInstance->mIsForeignMethodDef))
  2547. {
  2548. thisValue.mType = mModule->mCurMethodInstance->GetForeignType();
  2549. forcedIFaceLookup = true;
  2550. }
  2551. if (thisValue)
  2552. {
  2553. if (findName == "this")
  2554. return thisValue;
  2555. if (findName == "base")
  2556. {
  2557. auto baseValue = thisValue;
  2558. if (baseValue.IsThis())
  2559. baseValue.ToBase();
  2560. if (mModule->GetActiveTypeDef()->mTypeCode != BfTypeCode_Extension)
  2561. {
  2562. MakeBaseConcrete(baseValue);
  2563. }
  2564. return baseValue;
  2565. }
  2566. if (!mModule->mCurMethodState->HasNonStaticMixin())
  2567. {
  2568. mResultLocalVar = mModule->GetThisVariable();
  2569. mResultLocalVarRefNode = identifierNode;
  2570. }
  2571. }
  2572. if (!thisValue)
  2573. thisValue = BfTypedValue(mModule->mCurTypeInstance);
  2574. BfTypedValue result = LookupField(identifierNode, thisValue, findName, BfLookupFieldFlag_IsImplicitThis);
  2575. if (mPropDef != NULL)
  2576. {
  2577. if (forcedIFaceLookup)
  2578. {
  2579. }
  2580. }
  2581. if ((!result) && (mPropDef == NULL))
  2582. {
  2583. if (mModule->mContext->mCurTypeState != NULL)
  2584. {
  2585. // This is not necessarily true since we changed ConstResolver
  2586. //BF_ASSERT(mModule->mCurTypeInstance == mModule->mContext->mCurTypeState->mTypeInstance);
  2587. BfGlobalLookup globalLookup;
  2588. globalLookup.mKind = BfGlobalLookup::Kind_Field;
  2589. globalLookup.mName = findName;
  2590. mModule->PopulateGlobalContainersList(globalLookup);
  2591. for (auto& globalContainer : mModule->mContext->mCurTypeState->mGlobalContainers)
  2592. {
  2593. if (globalContainer.mTypeInst == NULL)
  2594. continue;
  2595. thisValue = BfTypedValue(globalContainer.mTypeInst);
  2596. result = LookupField(identifierNode, thisValue, findName);
  2597. if ((result) || (mPropDef != NULL))
  2598. return result;
  2599. }
  2600. }
  2601. }
  2602. if ((!result) && (identifierNode != NULL))
  2603. result = mModule->TryLookupGenericConstVaue(identifierNode, mExpectingType);
  2604. return result;
  2605. }
  2606. BfTypedValue BfExprEvaluator::LookupIdentifier(BfIdentifierNode* identifierNode, bool ignoreInitialError, bool* hadError)
  2607. {
  2608. auto qualifiedNameNode = BfNodeDynCast<BfQualifiedNameNode>(identifierNode);
  2609. if (qualifiedNameNode != NULL)
  2610. {
  2611. LookupQualifiedName(qualifiedNameNode, ignoreInitialError, hadError);
  2612. auto qualifiedResult = mResult;
  2613. mResult = BfTypedValue();
  2614. return qualifiedResult;
  2615. }
  2616. StringT<128> identifierStr;
  2617. identifierNode->ToString(identifierStr);
  2618. return LookupIdentifier(identifierNode, identifierStr, ignoreInitialError, hadError);
  2619. }
  2620. void BfExprEvaluator::Visit(BfIdentifierNode* identifierNode)
  2621. {
  2622. if (GetAutoComplete() != NULL)
  2623. GetAutoComplete()->CheckIdentifier(identifierNode, true);
  2624. mResult = LookupIdentifier(identifierNode);
  2625. if ((!mResult) && (mPropDef == NULL))
  2626. mModule->Fail("Identifier not found", identifierNode);
  2627. }
  2628. void BfExprEvaluator::Visit(BfAttributedIdentifierNode* attrIdentifierNode)
  2629. {
  2630. if ((mModule->mAttributeState != NULL))
  2631. {
  2632. mModule->mAttributeState->mCustomAttributes = mModule->GetCustomAttributes(attrIdentifierNode->mAttributes, mModule->mAttributeState->mTarget);
  2633. VisitChild(attrIdentifierNode->mIdentifier);
  2634. }
  2635. else
  2636. {
  2637. BfAttributeState attributeState;
  2638. attributeState.mTarget = (BfAttributeTargets)(BfAttributeTargets_MemberAccess);
  2639. SetAndRestoreValue<BfAttributeState*> prevAttributeState(mModule->mAttributeState, &attributeState);
  2640. mModule->mAttributeState->mCustomAttributes = mModule->GetCustomAttributes(attrIdentifierNode->mAttributes, mModule->mAttributeState->mTarget);
  2641. VisitChild(attrIdentifierNode->mIdentifier);
  2642. }
  2643. }
  2644. static int gPropIdx = 0;
  2645. void BfExprEvaluator::FixitAddMember(BfTypeInstance* typeInst, BfType* fieldType, const StringImpl& fieldName, bool isStatic)
  2646. {
  2647. if (fieldType == NULL)
  2648. {
  2649. fieldType = mExpectingType;
  2650. }
  2651. if (fieldType != NULL)
  2652. {
  2653. if (fieldType->IsRef())
  2654. fieldType = fieldType->GetUnderlyingType();
  2655. }
  2656. mModule->mCompiler->mResolvePassData->mAutoComplete->FixitAddMember(typeInst, fieldType, fieldName, isStatic, mModule->mCurTypeInstance);
  2657. }
  2658. BfTypedValue BfExprEvaluator::LookupField(BfAstNode* targetSrc, BfTypedValue target, const StringImpl& fieldName, BfLookupFieldFlags flags)
  2659. {
  2660. BfTypeInstance* startCheckType = mModule->mCurTypeInstance;
  2661. mPropDef = NULL;
  2662. mPropDefBypassVirtual = false;
  2663. if ((target.mType != NULL) && (mModule->mCurMethodState != NULL))
  2664. {
  2665. mModule->PopulateType(target.mType, BfPopulateType_BaseType);
  2666. }
  2667. if (target)
  2668. {
  2669. if ((!target.mType->IsValueType()) && (target.IsAddr()))
  2670. target = mModule->LoadValue(target);
  2671. if (target.mType->IsPrimitiveType())
  2672. {
  2673. auto primType = (BfPrimitiveType*)target.mType;
  2674. startCheckType = mModule->GetPrimitiveStructType(primType->mTypeDef->mTypeCode);
  2675. }
  2676. else
  2677. {
  2678. startCheckType = target.mType->ToTypeInstance();
  2679. if ((startCheckType == NULL) && (target.mType->IsPointer()))
  2680. startCheckType = ((BfPointerType*) target.mType)->mElementType->ToTypeInstance();
  2681. }
  2682. //BF_ASSERT(startCheckType != NULL);
  2683. }
  2684. else if (target.mType != NULL)
  2685. {
  2686. startCheckType = target.mType->ToTypeInstance();
  2687. }
  2688. auto activeTypeDef = mModule->GetActiveTypeDef();
  2689. for (int pass = 0; pass < 2; pass++)
  2690. {
  2691. auto curCheckType = startCheckType;
  2692. bool isFailurePass = pass == 1;
  2693. bool isBaseLookup = false;
  2694. while (curCheckType != NULL)
  2695. {
  2696. curCheckType->mTypeDef->PopulateMemberSets();
  2697. BfFieldDef* nextField = NULL;
  2698. BfMemberSetEntry* entry;
  2699. if (curCheckType->mTypeDef->mFieldSet.TryGetWith(fieldName, &entry))
  2700. nextField = (BfFieldDef*)entry->mMemberDef;
  2701. BfProtectionCheckFlags protectionCheckFlags = BfProtectionCheckFlag_None;
  2702. BfFieldDef* matchedField = NULL;
  2703. while (nextField != NULL)
  2704. {
  2705. auto field = nextField;
  2706. nextField = nextField->mNextWithSameName;
  2707. if ((!isFailurePass) && (!mModule->CheckProtection(protectionCheckFlags, curCheckType, field->mProtection, startCheckType)))
  2708. {
  2709. continue;
  2710. }
  2711. //OLD:
  2712. bool isResolvingFields = curCheckType->mResolvingConstField || curCheckType->mResolvingVarField;
  2713. // mCurMethodState is NULL when we're pre-evaluating var field expressions
  2714. // to determine their type in PopulateFields
  2715. /*if (!isResolvingFields)
  2716. {
  2717. mModule->PopulateType(curCheckType, BfPopulateType_Data);
  2718. }*/
  2719. if (curCheckType->mFieldInstances.IsEmpty())
  2720. {
  2721. mModule->PopulateType(curCheckType, BfPopulateType_Data);
  2722. }
  2723. BF_ASSERT(field->mIdx < (int)curCheckType->mFieldInstances.size());
  2724. auto fieldInstance = &curCheckType->mFieldInstances[field->mIdx];
  2725. if (!fieldInstance->mFieldIncluded)
  2726. continue;
  2727. if (curCheckType->IsUnspecializedType())
  2728. {
  2729. // The check for non-unspecialized types is already handled in mFieldIncluded
  2730. if (!curCheckType->IsTypeMemberIncluded(field->mDeclaringType, activeTypeDef, mModule))
  2731. continue;
  2732. }
  2733. if (!curCheckType->IsTypeMemberAccessible(field->mDeclaringType, activeTypeDef))
  2734. continue;
  2735. if (matchedField != NULL)
  2736. {
  2737. auto error = mModule->Fail(StrFormat("Ambiguous reference to field '%s.%s'", mModule->TypeToString(curCheckType).c_str(), fieldName.c_str()), targetSrc);
  2738. if (error != NULL)
  2739. {
  2740. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("See field declaration in project '%s'", matchedField->mDeclaringType->mProject->mName.c_str()), matchedField->mFieldDeclaration);
  2741. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("See field declaration in project '%s'", field->mDeclaringType->mProject->mName.c_str()), field->mFieldDeclaration);
  2742. break;
  2743. }
  2744. }
  2745. matchedField = field;
  2746. }
  2747. if (matchedField != NULL)
  2748. {
  2749. auto field = matchedField;
  2750. auto fieldInstance = &curCheckType->mFieldInstances[field->mIdx];
  2751. bool isResolvingFields = curCheckType->mResolvingConstField || curCheckType->mResolvingVarField;
  2752. if (field->mIsVolatile)
  2753. mIsVolatileReference = true;
  2754. if (isFailurePass)
  2755. {
  2756. mModule->Fail(StrFormat("'%s.%s' is inaccessible due to its protection level", mModule->TypeToString(curCheckType).c_str(), field->mName.c_str()), targetSrc);
  2757. }
  2758. auto resolvePassData = mModule->mCompiler->mResolvePassData;
  2759. if ((resolvePassData != NULL) && (resolvePassData->mGetSymbolReferenceKind == BfGetSymbolReferenceKind_Field))
  2760. {
  2761. resolvePassData->HandleFieldReference(targetSrc, curCheckType->mTypeDef, field);
  2762. }
  2763. if ((!curCheckType->mTypeFailed) && (!isResolvingFields) && (curCheckType->IsIncomplete()))
  2764. {
  2765. if ((fieldInstance->mResolvedType == NULL) ||
  2766. (!field->mIsStatic))
  2767. mModule->PopulateType(curCheckType, BfPopulateType_Data);
  2768. }
  2769. if (fieldInstance->mResolvedType == NULL)
  2770. {
  2771. BF_ASSERT((curCheckType->mTypeFailed) || (isResolvingFields));
  2772. return BfTypedValue();
  2773. }
  2774. if (fieldInstance->mFieldIdx == -1)
  2775. {
  2776. mModule->AssertErrorState();
  2777. return BfTypedValue();
  2778. }
  2779. // Are we accessing a 'var' field that has not yet been resolved?
  2780. if (fieldInstance->mResolvedType->IsVar())
  2781. {
  2782. // This can happen if we have one var field referencing another var field
  2783. fieldInstance->mResolvedType = mModule->ResolveVarFieldType(curCheckType, fieldInstance, field);
  2784. if (fieldInstance->mResolvedType == NULL)
  2785. return BfTypedValue();
  2786. if ((fieldInstance->mResolvedType->IsVar()) && (mModule->mCompiler->mIsResolveOnly))
  2787. mModule->Fail("Field type reference failed to resolve", targetSrc);
  2788. }
  2789. auto resolvedFieldType = fieldInstance->mResolvedType;
  2790. if (fieldInstance->mIsEnumPayloadCase)
  2791. {
  2792. resolvedFieldType = curCheckType;
  2793. }
  2794. mModule->PopulateType(resolvedFieldType, BfPopulateType_Data);
  2795. mModule->AddDependency(curCheckType, mModule->mCurTypeInstance, BfDependencyMap::DependencyFlag_ReadFields);
  2796. auto autoComplete = GetAutoComplete();
  2797. if (autoComplete != NULL)
  2798. autoComplete->CheckFieldRef(BfNodeDynCast<BfIdentifierNode>(targetSrc), fieldInstance);
  2799. if (field->mIsStatic)
  2800. {
  2801. if ((target) && ((flags & BfLookupFieldFlag_IsImplicitThis) == 0) && (!curCheckType->mTypeDef->IsGlobalsContainer()))
  2802. {
  2803. //CS0176: Member 'Program.sVal' cannot be accessed with an instance reference; qualify it with a type name instead
  2804. mModule->Fail(StrFormat("Member '%s.%s' cannot be accessed with an instance reference; qualify it with a type name instead",
  2805. mModule->TypeToString(curCheckType).c_str(), field->mName.c_str()), targetSrc);
  2806. }
  2807. // Target must be an implicit 'this', or an error (accessing a static with a non-static target).
  2808. // Not actually needed in either case since this is a static lookup.
  2809. mResultLocalVar = NULL;
  2810. }
  2811. bool isConst = false;
  2812. if (field->mIsConst)
  2813. {
  2814. isConst = true;
  2815. auto fieldDef = fieldInstance->GetFieldDef();
  2816. if ((resolvedFieldType->IsPointer()) && (fieldDef->mIsExtern))
  2817. isConst = false;
  2818. }
  2819. if (resolvedFieldType->IsValuelessType())
  2820. {
  2821. return BfTypedValue(BfIRValue::sValueless, resolvedFieldType, true);
  2822. }
  2823. if (isConst)
  2824. {
  2825. if (fieldInstance->mIsEnumPayloadCase)
  2826. {
  2827. auto dscrType = curCheckType->GetDiscriminatorType();
  2828. mModule->mBfIRBuilder->PopulateType(curCheckType);
  2829. int tagIdx = -fieldInstance->mDataIdx - 1;
  2830. if ((mBfEvalExprFlags & BfEvalExprFlags_AllowEnumId) != 0)
  2831. {
  2832. return BfTypedValue(mModule->mBfIRBuilder->CreateConst(dscrType->mTypeDef->mTypeCode, tagIdx), fieldInstance->mOwner);
  2833. }
  2834. mModule->PopulateType(fieldInstance->mOwner, BfPopulateType_Data);
  2835. // auto agg = mModule->mBfIRBuilder->CreateUndefValue(mModule->mBfIRBuilder->MapType(fieldInstance->mOwner));
  2836. // agg = mModule->mBfIRBuilder->CreateInsertValue(agg, mModule->mBfIRBuilder->CreateConst(dscrType->mTypeDef->mTypeCode, tagIdx), 2);
  2837. //
  2838. // if (fieldInstance->mResolvedType->mSize != 0)
  2839. // {
  2840. // mModule->FailAfter("Enum case parameters expected", targetSrc);
  2841. // }
  2842. //
  2843. // return BfTypedValue(agg, fieldInstance->mOwner);
  2844. auto agg = mModule->CreateAlloca(fieldInstance->mOwner);
  2845. auto gep = mModule->mBfIRBuilder->CreateInBoundsGEP(agg, 0, 2);
  2846. mModule->mBfIRBuilder->CreateStore(mModule->mBfIRBuilder->CreateConst(dscrType->mTypeDef->mTypeCode, tagIdx), gep);
  2847. if (fieldInstance->mResolvedType->mSize != 0)
  2848. {
  2849. mModule->FailAfter("Enum case parameters expected", targetSrc);
  2850. }
  2851. return BfTypedValue(agg, fieldInstance->mOwner, true);
  2852. }
  2853. if (fieldInstance->mConstIdx == -1)
  2854. {
  2855. curCheckType->mModule->ResolveConstField(curCheckType, fieldInstance, field);
  2856. if (fieldInstance->mConstIdx == -1)
  2857. return BfTypedValue(mModule->GetDefaultValue(resolvedFieldType), resolvedFieldType);
  2858. }
  2859. BF_ASSERT(fieldInstance->mConstIdx != -1);
  2860. auto foreignConst = curCheckType->mConstHolder->GetConstantById(fieldInstance->mConstIdx);
  2861. auto retVal = mModule->ConstantToCurrent(foreignConst, curCheckType->mConstHolder, resolvedFieldType);
  2862. return BfTypedValue(retVal, resolvedFieldType);
  2863. }
  2864. else if (field->mIsStatic)
  2865. {
  2866. mModule->CheckStaticAccess(curCheckType);
  2867. auto retVal = mModule->ReferenceStaticField(fieldInstance);
  2868. if (field->mIsReadOnly)
  2869. retVal = mModule->LoadValue(retVal, NULL, mIsVolatileReference);
  2870. else
  2871. mIsHeapReference = true;
  2872. return retVal;
  2873. }
  2874. else if (!target)
  2875. {
  2876. if ((flags & BfLookupFieldFlag_CheckingOuter) != 0)
  2877. 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()),
  2878. targetSrc);
  2879. else if ((mModule->mCurMethodInstance != NULL) && (mModule->mCurMethodInstance->mMethodDef->mMethodType == BfMethodType_CtorCalcAppend))
  2880. mModule->Fail(StrFormat("Cannot reference field '%s' before append allocations", field->mName.c_str()), targetSrc);
  2881. else
  2882. mModule->Fail(StrFormat("Cannot reference non-static field '%s' from a static method", field->mName.c_str()), targetSrc);
  2883. return mModule->GetDefaultTypedValue(resolvedFieldType, false, BfDefaultValueKind_Addr);
  2884. }
  2885. if ((mResultLocalVar != NULL) && (fieldInstance->mMergedDataIdx != -1))
  2886. {
  2887. int minMergedDataIdx = fieldInstance->mMergedDataIdx;
  2888. int maxMergedDataIdx = minMergedDataIdx + 1;
  2889. if (resolvedFieldType->IsStruct())
  2890. maxMergedDataIdx = minMergedDataIdx + resolvedFieldType->ToTypeInstance()->mMergedFieldDataCount;
  2891. if (curCheckType->mIsUnion)
  2892. {
  2893. for (auto& checkFieldInstance : curCheckType->mFieldInstances)
  2894. {
  2895. if (&checkFieldInstance == fieldInstance)
  2896. continue;
  2897. if (checkFieldInstance.mDataIdx == fieldInstance->mDataIdx)
  2898. {
  2899. int checkMinMergedDataIdx = checkFieldInstance.mMergedDataIdx;
  2900. int checkMaxMergedDataIdx = checkMinMergedDataIdx + 1;
  2901. if (checkFieldInstance.GetResolvedType()->IsStruct())
  2902. checkMaxMergedDataIdx = checkMinMergedDataIdx + checkFieldInstance.mResolvedType->ToTypeInstance()->mMergedFieldDataCount;
  2903. minMergedDataIdx = BF_MIN(minMergedDataIdx, checkMinMergedDataIdx);
  2904. maxMergedDataIdx = BF_MAX(maxMergedDataIdx, checkMaxMergedDataIdx);
  2905. }
  2906. }
  2907. }
  2908. int fieldIdx = -1;
  2909. if (fieldIdx == -1)
  2910. {
  2911. mResultLocalVarField = minMergedDataIdx + 1;
  2912. }
  2913. else
  2914. {
  2915. fieldIdx += minMergedDataIdx;
  2916. mResultLocalVarField = fieldIdx + 1;
  2917. }
  2918. mResultLocalVarFieldCount = maxMergedDataIdx - minMergedDataIdx;
  2919. mResultLocalVarRefNode = targetSrc;
  2920. /*int fieldIdx = (mResultLocalVarIdx >> 16) - 1;
  2921. if (fieldIdx == -1)
  2922. {
  2923. mResultLocalVarField = fieldInstance->mMergedDataIdx + 1;
  2924. }
  2925. else
  2926. {
  2927. fieldIdx += fieldInstance->mMergedDataIdx;
  2928. mResultLocalVarField = fieldIdx + 1;
  2929. }
  2930. mResultLocalVarFieldCount = 1;
  2931. if (fieldInstance->mType->IsStruct())
  2932. {
  2933. auto fieldTypeInstance = fieldInstance->mType->ToTypeInstance();
  2934. mResultLocalVarFieldCount = fieldTypeInstance->mMergedFieldDataCount;
  2935. }
  2936. mResultLocalVarRefNode = targetSrc;*/
  2937. }
  2938. if ((curCheckType->IsIncomplete()) && (!curCheckType->mNeedsMethodProcessing))
  2939. {
  2940. BF_ASSERT(curCheckType->mTypeFailed || (mModule->mCurMethodState == NULL) || (mModule->mCurMethodState->mTempKind != BfMethodState::TempKind_None) || (mModule->mCompiler->IsAutocomplete()));
  2941. return mModule->GetDefaultTypedValue(resolvedFieldType);
  2942. }
  2943. bool isTemporary = target.IsTempAddr();
  2944. bool wantsLoadValue = false;
  2945. if ((field->mIsReadOnly) && ((mModule->mCurMethodInstance->mMethodDef->mMethodType != BfMethodType_Ctor) || (!target.IsThis())))
  2946. wantsLoadValue = true;
  2947. bool isComposite = target.mType->IsComposite();
  2948. if ((isComposite) && (!target.mType->IsTypedPrimitive()) && (!target.IsAddr()))
  2949. isTemporary = true;
  2950. if ((isComposite) && (!target.IsAddr()))
  2951. wantsLoadValue = true;
  2952. if ((target.mType->IsWrappableType()) && (!target.mType->IsPointer()))
  2953. {
  2954. BfTypeInstance* primStructType = mModule->GetWrappedStructType(target.mType);
  2955. BfIRValue allocaInst = mModule->CreateAlloca(primStructType, true, "tmpStruct");
  2956. BfIRValue elementAddr = mModule->mBfIRBuilder->CreateInBoundsGEP(allocaInst, 0, 1);
  2957. mModule->mBfIRBuilder->CreateStore(target.mValue, elementAddr);
  2958. target = BfTypedValue(allocaInst, primStructType, true);
  2959. }
  2960. BfTypedValue targetValue;
  2961. if ((isBaseLookup) && (!target.IsSplat()))
  2962. {
  2963. if ((!isComposite) || (target.IsAddr()))
  2964. targetValue = BfTypedValue(mModule->mBfIRBuilder->CreateBitCast(target.mValue, mModule->mBfIRBuilder->MapTypeInstPtr(curCheckType)), curCheckType);
  2965. else
  2966. {
  2967. BfIRValue curVal = target.mValue;
  2968. auto baseCheckType = target.mType->ToTypeInstance();
  2969. while (baseCheckType != curCheckType)
  2970. {
  2971. curVal = mModule->mBfIRBuilder->CreateExtractValue(curVal, 0);
  2972. baseCheckType = baseCheckType->mBaseType;
  2973. }
  2974. targetValue = BfTypedValue(curVal, curCheckType);
  2975. }
  2976. }
  2977. else
  2978. targetValue = target;
  2979. bool doAccessCheck = true;
  2980. if ((mModule->mAttributeState != NULL) && (mModule->mAttributeState->mCustomAttributes != NULL) && (mModule->mAttributeState->mCustomAttributes->Contains(mModule->mCompiler->mSkipAccessCheckAttributeTypeDef)))
  2981. doAccessCheck = false;
  2982. if (target.IsThis())
  2983. {
  2984. if (!mModule->mCurMethodState->mMayNeedThisAccessCheck)
  2985. doAccessCheck = false;
  2986. }
  2987. if (doAccessCheck)
  2988. mModule->EmitObjectAccessCheck(target);
  2989. if (fieldInstance->mDataIdx < 0)
  2990. {
  2991. BF_ASSERT(curCheckType->mTypeFailed);
  2992. return mModule->GetDefaultTypedValue(resolvedFieldType);
  2993. }
  2994. BfTypedValue retVal;
  2995. if (target.IsSplat())
  2996. {
  2997. retVal = mModule->ExtractValue(targetValue, fieldInstance, fieldInstance->mDataIdx);
  2998. }
  2999. else if ((target.mType->IsStruct()) && (!target.IsAddr()))
  3000. {
  3001. retVal = BfTypedValue(mModule->mBfIRBuilder->CreateExtractValue(targetValue.mValue, fieldInstance->mDataIdx/*, field->mName*/),
  3002. resolvedFieldType);
  3003. }
  3004. else
  3005. {
  3006. mModule->mBfIRBuilder->PopulateType(curCheckType);
  3007. if ((targetValue.IsAddr()) && (!curCheckType->IsValueType()))
  3008. targetValue = mModule->LoadValue(targetValue);
  3009. retVal = BfTypedValue(mModule->mBfIRBuilder->CreateInBoundsGEP(targetValue.mValue, 0, fieldInstance->mDataIdx/*, field->mName*/),
  3010. resolvedFieldType, target.IsReadOnly() ? BfTypedValueKind_ReadOnlyAddr : BfTypedValueKind_Addr);
  3011. }
  3012. if (!retVal.IsSplat())
  3013. {
  3014. if (curCheckType->mIsUnion)
  3015. {
  3016. BfIRType llvmPtrType = mModule->mBfIRBuilder->GetPointerTo(mModule->mBfIRBuilder->MapType(resolvedFieldType));
  3017. retVal.mValue = mModule->mBfIRBuilder->CreateBitCast(retVal.mValue, llvmPtrType);
  3018. }
  3019. }
  3020. if (wantsLoadValue)
  3021. retVal = mModule->LoadValue(retVal, NULL, mIsVolatileReference);
  3022. else
  3023. mIsHeapReference = true;
  3024. if (isTemporary)
  3025. {
  3026. if (retVal.IsAddr())
  3027. retVal.mKind = BfTypedValueKind_TempAddr;
  3028. }
  3029. return retVal;
  3030. }
  3031. BfPropertyDef* nextProp = NULL;
  3032. if (curCheckType->mTypeDef->mPropertySet.TryGetWith(fieldName, &entry))
  3033. nextProp = (BfPropertyDef*)entry->mMemberDef;
  3034. if (nextProp != NULL)
  3035. {
  3036. BfCheckedKind checkedKind = BfCheckedKind_NotSet;
  3037. bool isInlined = false;
  3038. if ((mModule->mAttributeState != NULL) && (mModule->mAttributeState->mCustomAttributes != NULL))
  3039. {
  3040. if (mModule->mAttributeState->mCustomAttributes->Contains(mModule->mCompiler->mInlineAttributeTypeDef))
  3041. {
  3042. isInlined = true;
  3043. mModule->mAttributeState->mUsed = true;
  3044. }
  3045. if (mModule->mAttributeState->mCustomAttributes->Contains(mModule->mCompiler->mCheckedAttributeTypeDef))
  3046. {
  3047. checkedKind = BfCheckedKind_Checked;
  3048. mModule->mAttributeState->mUsed = true;
  3049. }
  3050. if (mModule->mAttributeState->mCustomAttributes->Contains(mModule->mCompiler->mUncheckedAttributeTypeDef))
  3051. {
  3052. checkedKind = BfCheckedKind_Unchecked;
  3053. mModule->mAttributeState->mUsed = true;
  3054. }
  3055. }
  3056. BfPropertyDef* matchedProp = NULL;
  3057. while (nextProp != NULL)
  3058. {
  3059. auto prop = nextProp;
  3060. nextProp = nextProp->mNextWithSameName;
  3061. if ((!isFailurePass) && (!mModule->CheckProtection(protectionCheckFlags, curCheckType, prop->mProtection, startCheckType)))
  3062. {
  3063. continue;
  3064. }
  3065. if (!prop->mMethods.IsEmpty())
  3066. {
  3067. BfMethodDef* checkMethod = prop->mMethods[0];;
  3068. // Properties with explicit interfaces or marked as overrides can only be called indirectly
  3069. if ((checkMethod->mExplicitInterface != NULL) || (checkMethod->mIsOverride))
  3070. continue;
  3071. }
  3072. if ((!target.IsStatic()) || (prop->mIsStatic))
  3073. {
  3074. if ((!curCheckType->IsTypeMemberIncluded(prop->mDeclaringType, activeTypeDef, mModule)) ||
  3075. (!curCheckType->IsTypeMemberAccessible(prop->mDeclaringType, activeTypeDef)))
  3076. continue;
  3077. if (matchedProp != NULL)
  3078. {
  3079. auto error = mModule->Fail(StrFormat("Ambiguous reference to property '%s.%s'", mModule->TypeToString(curCheckType).c_str(), fieldName.c_str()), targetSrc);
  3080. if (error != NULL)
  3081. {
  3082. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("See property declaration in project '%s'", matchedProp->mDeclaringType->mProject->mName.c_str()), matchedProp->mFieldDeclaration);
  3083. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("See property declaration in project '%s'", prop->mDeclaringType->mProject->mName.c_str()), prop->mFieldDeclaration);
  3084. break;
  3085. }
  3086. }
  3087. matchedProp = prop;
  3088. }
  3089. }
  3090. if (matchedProp != NULL)
  3091. {
  3092. auto prop = matchedProp;
  3093. gPropIdx++;
  3094. mModule->SetElementType(targetSrc, BfSourceElementType_Method);
  3095. mPropSrc = targetSrc;
  3096. mPropDef = prop;
  3097. mPropCheckedKind = checkedKind;
  3098. if (isInlined)
  3099. mPropGetMethodFlags = (BfGetMethodInstanceFlags)(mPropGetMethodFlags | BfGetMethodInstanceFlag_ForceInline);
  3100. if (mPropDef->mIsStatic)
  3101. {
  3102. if ((target) && ((flags & BfLookupFieldFlag_IsImplicitThis) == 0) && (!curCheckType->mTypeDef->IsGlobalsContainer()))
  3103. {
  3104. //CS0176: Member 'Program.sVal' cannot be accessed with an instance reference; qualify it with a type name instead
  3105. mModule->Fail(StrFormat("Property '%s.%s' cannot be accessed with an instance reference; qualify it with a type name instead",
  3106. mModule->TypeToString(curCheckType).c_str(), mPropDef->mName.c_str()), targetSrc);
  3107. }
  3108. }
  3109. if (prop->mIsStatic)
  3110. mPropTarget = BfTypedValue(curCheckType);
  3111. else if (isBaseLookup)
  3112. {
  3113. mPropTarget = mModule->Cast(targetSrc, target, curCheckType);
  3114. BF_ASSERT(mPropTarget);
  3115. }
  3116. else
  3117. mPropTarget = target;
  3118. mOrigPropTarget = mPropTarget;
  3119. auto autoComplete = GetAutoComplete();
  3120. auto resolvePassData = mModule->mCompiler->mResolvePassData;
  3121. if (((autoComplete != NULL) && (autoComplete->mIsGetDefinition)) ||
  3122. ((resolvePassData != NULL) && (resolvePassData->mGetSymbolReferenceKind == BfGetSymbolReferenceKind_Property)))
  3123. {
  3124. BfPropertyDef* basePropDef = mPropDef;
  3125. BfTypeInstance* baseTypeInst = curCheckType;
  3126. mModule->GetBasePropertyDef(basePropDef, baseTypeInst);
  3127. resolvePassData->HandlePropertyReference(targetSrc, baseTypeInst->mTypeDef, basePropDef);
  3128. if ((autoComplete != NULL) && (autoComplete->IsAutocompleteNode(targetSrc)))
  3129. {
  3130. autoComplete->mDefProp = basePropDef;
  3131. autoComplete->mDefType = baseTypeInst->mTypeDef;
  3132. }
  3133. }
  3134. SetAndRestoreValue<BfTypedValue> prevResult(mResult, target);
  3135. CheckResultForReading(mResult);
  3136. return BfTypedValue();
  3137. }
  3138. }
  3139. isBaseLookup = true;
  3140. curCheckType = curCheckType->mBaseType;
  3141. }
  3142. }
  3143. auto outerTypeDef = mModule->GetOuterType(startCheckType);
  3144. if (outerTypeDef != NULL)
  3145. {
  3146. // Check statics in outer type
  3147. return LookupField(targetSrc, BfTypedValue(outerTypeDef), fieldName, BfLookupFieldFlag_CheckingOuter);
  3148. }
  3149. return BfTypedValue();
  3150. }
  3151. void BfExprEvaluator::ResolveArgValues(BfResolvedArgs& resolvedArgs, BfResolveArgFlags flags)
  3152. {
  3153. static int idx = 0;
  3154. idx++;
  3155. int curIdx = idx;
  3156. if (resolvedArgs.mArguments == NULL)
  3157. return;
  3158. int argCount = (int)resolvedArgs.mArguments->size();
  3159. if ((resolvedArgs.mCommas != NULL) && (resolvedArgs.mCommas->size() != 0) && (resolvedArgs.mCommas->size() >= resolvedArgs.mArguments->size()))
  3160. {
  3161. //mModule->FailAfter("Expression expected", resolvedArgs.mCommas->back());
  3162. argCount++;
  3163. }
  3164. BfAutoComplete* autoComplete = GetAutoComplete();
  3165. bool hadIgnoredFixits = false;
  3166. if (autoComplete != NULL)
  3167. {
  3168. hadIgnoredFixits = autoComplete->mIgnoreFixits;
  3169. if (flags & BfResolveArgFlag_DeferFixits)
  3170. autoComplete->mIgnoreFixits = true;
  3171. }
  3172. for (int argIdx = 0; argIdx < argCount ; argIdx++)
  3173. {
  3174. //printf("Args: %p %p %d\n", resolvedArgs.mArguments, resolvedArgs.mArguments->mVals, resolvedArgs.mArguments->mSize);
  3175. BfExpression* argExpr = NULL;
  3176. if (argIdx < resolvedArgs.mArguments->size())
  3177. argExpr = (*resolvedArgs.mArguments)[argIdx];
  3178. if (argExpr == NULL)
  3179. {
  3180. if (argIdx == 0)
  3181. {
  3182. if (resolvedArgs.mOpenToken != NULL)
  3183. mModule->FailAfter("Expression expected", resolvedArgs.mOpenToken);
  3184. }
  3185. else if (resolvedArgs.mCommas != NULL)
  3186. mModule->FailAfter("Expression expected", (*resolvedArgs.mCommas)[argIdx - 1]);
  3187. }
  3188. if (auto typedValueExpr = BfNodeDynCast<BfTypedValueExpression>(argExpr))
  3189. {
  3190. BfResolvedArg resolvedArg;
  3191. resolvedArg.mTypedValue = typedValueExpr->mTypedValue;
  3192. resolvedArg.mExpression = typedValueExpr->mRefNode;
  3193. resolvedArgs.mResolvedArgs.push_back(resolvedArg);
  3194. continue;
  3195. }
  3196. BfResolvedArg resolvedArg;
  3197. BfExprEvaluator exprEvaluator(mModule);
  3198. exprEvaluator.mResolveGenericParam = (flags & BfResolveArgFlag_AllowUnresolvedTypes) == 0;
  3199. exprEvaluator.mBfEvalExprFlags = (BfEvalExprFlags)(exprEvaluator.mBfEvalExprFlags | BfEvalExprFlags_AllowRefExpr | BfEvalExprFlags_AllowOutExpr);
  3200. bool handled = false;
  3201. bool evaluated = false;
  3202. bool deferParamEval = false;
  3203. if ((flags & BfResolveArgFlag_DeferParamEval) != 0)
  3204. {
  3205. if (argExpr != NULL)
  3206. {
  3207. BfDeferEvalChecker deferEvalChecker;
  3208. argExpr->Accept(&deferEvalChecker);
  3209. deferParamEval = deferEvalChecker.mNeedsDeferEval;
  3210. }
  3211. }
  3212. if (deferParamEval)
  3213. {
  3214. resolvedArg.mArgFlags = (BfArgFlags)(resolvedArg.mArgFlags | BfArgFlag_DeferredEval);
  3215. handled = true;
  3216. }
  3217. else if (auto delegateBindExpression = BfNodeDynCast<BfDelegateBindExpression>(argExpr))
  3218. {
  3219. resolvedArg.mArgFlags = (BfArgFlags)(resolvedArg.mArgFlags | BfArgFlag_DelegateBindAttempt);
  3220. handled = true;
  3221. }
  3222. else if (auto lambdaBindExpression = BfNodeDynCast<BfLambdaBindExpression>(argExpr))
  3223. {
  3224. resolvedArg.mArgFlags = (BfArgFlags)(resolvedArg.mArgFlags | BfArgFlag_LambdaBindAttempt);
  3225. handled = true;
  3226. }
  3227. else if (auto memberRef = BfNodeDynCast<BfMemberReferenceExpression>(argExpr))
  3228. {
  3229. if (memberRef->mTarget == NULL)
  3230. {
  3231. resolvedArg.mArgFlags = (BfArgFlags)(resolvedArg.mArgFlags | BfArgFlag_UnqualifiedDotAttempt);
  3232. handled = true;
  3233. }
  3234. }
  3235. else if (auto invokeExpr = BfNodeDynCast<BfInvocationExpression>(argExpr))
  3236. {
  3237. if (auto memberRef = BfNodeDynCast<BfMemberReferenceExpression>(invokeExpr->mTarget))
  3238. {
  3239. if (memberRef->mTarget == NULL)
  3240. {
  3241. resolvedArg.mArgFlags = (BfArgFlags)(resolvedArg.mArgFlags | BfArgFlag_UnqualifiedDotAttempt);
  3242. handled = true;
  3243. }
  3244. }
  3245. }
  3246. else if (auto defaultExpr = BfNodeDynCast<BfDefaultExpression>(argExpr))
  3247. {
  3248. if (defaultExpr->mTypeRef == NULL)
  3249. {
  3250. resolvedArg.mArgFlags = (BfArgFlags)(resolvedArg.mArgFlags | BfArgFlag_UntypedDefault);
  3251. handled = true;
  3252. }
  3253. }
  3254. else if (auto varDeclExpr = BfNodeDynCast<BfVariableDeclaration>(argExpr))
  3255. {
  3256. resolvedArg.mArgFlags = (BfArgFlags)(resolvedArg.mArgFlags | BfArgFlag_VariableDeclaration);
  3257. handled = true;
  3258. }
  3259. else if (auto unaryExpr = BfNodeDynCast<BfUnaryOperatorExpression>(argExpr))
  3260. {
  3261. if (unaryExpr->mOp == BfUnaryOp_Params)
  3262. {
  3263. resolvedArg.mArgFlags = (BfArgFlags)(resolvedArg.mArgFlags | BfArgFlag_ParamsExpr);
  3264. }
  3265. }
  3266. /*else if (auto castExpr = BfNodeDynCast<BfCastExpression>(argExpr))
  3267. {
  3268. if (auto namedTypeRef = BfNodeDynCastExact<BfNamedTypeReference>(castExpr->mTypeRef))
  3269. {
  3270. if (namedTypeRef->ToString() == "ExpectedType")
  3271. {
  3272. resolvedArg.mArgFlags = (BfArgFlags)(resolvedArg.mArgFlags | BfArgFlag_ExpectedTypeCast);
  3273. handled = true;
  3274. }
  3275. }
  3276. }*/
  3277. if ((argExpr != NULL) && (!handled))
  3278. {
  3279. bool deferParamValues = (flags & BfResolveArgFlag_DeferParamValues) != 0;
  3280. SetAndRestoreValue<bool> ignoreWrites(mModule->mBfIRBuilder->mIgnoreWrites, mModule->mBfIRBuilder->mIgnoreWrites || deferParamValues);
  3281. auto prevInsertBlock = mModule->mBfIRBuilder->GetInsertBlock();
  3282. if (deferParamValues)
  3283. resolvedArg.mArgFlags = (BfArgFlags)(resolvedArg.mArgFlags | BfArgFlag_DeferredValue);
  3284. if (!evaluated)
  3285. {
  3286. exprEvaluator.mBfEvalExprFlags = (BfEvalExprFlags)(exprEvaluator.mBfEvalExprFlags | BfEvalExprFlags_AllowParamsExpr);
  3287. exprEvaluator.Evaluate(argExpr, false, false, true);
  3288. }
  3289. if ((mModule->mCurMethodState != NULL) && (exprEvaluator.mResultLocalVar != NULL) && (exprEvaluator.mResultLocalVarRefNode != NULL))
  3290. {
  3291. auto localVar = exprEvaluator.mResultLocalVar;
  3292. int fieldIdx = mResultLocalVarField - 1;
  3293. auto methodState = mModule->mCurMethodState->GetMethodStateForLocal(localVar);
  3294. if (localVar->mCompositeCount >= 0)
  3295. {
  3296. if ((resolvedArg.mArgFlags & BfArgFlag_ParamsExpr) == 0)
  3297. mModule->Warn(0, "'params' token expected", argExpr);
  3298. for (int compositeIdx = 0; compositeIdx < localVar->mCompositeCount; compositeIdx++)
  3299. {
  3300. BfResolvedArg compositeResolvedArg;
  3301. auto compositeLocalVar = methodState->mLocals[localVar->mLocalVarIdx + compositeIdx + 1];
  3302. auto argValue = exprEvaluator.LoadLocal(compositeLocalVar);
  3303. if (argValue)
  3304. {
  3305. if (argValue.mType->IsRef())
  3306. argValue.mKind = BfTypedValueKind_Value;
  3307. else if (!argValue.mType->IsStruct())
  3308. argValue = mModule->LoadValue(argValue, NULL, exprEvaluator.mIsVolatileReference);
  3309. }
  3310. resolvedArg.mTypedValue = argValue;
  3311. resolvedArg.mExpression = argExpr;
  3312. resolvedArg.mArgFlags = (BfArgFlags)(resolvedArg.mArgFlags | BfArgFlag_FromParamComposite);
  3313. resolvedArgs.mResolvedArgs.push_back(resolvedArg);
  3314. }
  3315. continue;
  3316. }
  3317. }
  3318. exprEvaluator.CheckResultForReading(exprEvaluator.mResult);
  3319. auto argValue = exprEvaluator.mResult;
  3320. if (argValue)
  3321. {
  3322. //resolvedArg.mResolvedType = mModule->ResolveGenericType(argValue.mType);
  3323. resolvedArg.mResolvedType = argValue.mType;
  3324. if (resolvedArg.mResolvedType->IsRef())
  3325. argValue.mKind = BfTypedValueKind_Value;
  3326. else if ((!resolvedArg.mResolvedType->IsStruct()) && (!resolvedArg.mResolvedType->IsSizedArray()) && (!resolvedArg.mResolvedType->IsValuelessType()))
  3327. argValue = mModule->LoadValue(argValue, NULL, exprEvaluator.mIsVolatileReference);
  3328. }
  3329. resolvedArg.mTypedValue = argValue;
  3330. if (deferParamValues)
  3331. mModule->mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  3332. }
  3333. resolvedArg.mExpression = argExpr;
  3334. resolvedArgs.mResolvedArgs.push_back(resolvedArg);
  3335. }
  3336. if (autoComplete != NULL)
  3337. autoComplete->mIgnoreFixits = hadIgnoredFixits;
  3338. }
  3339. void BfExprEvaluator::PerformCallChecks(BfMethodInstance* methodInstance, BfAstNode* targetSrc)
  3340. {
  3341. BfCustomAttributes* customAttributes = methodInstance->GetCustomAttributes();
  3342. if (customAttributes != NULL)
  3343. {
  3344. auto _AddMethodDeclarationMoreInfo = [&]()
  3345. {
  3346. if (methodInstance->mMethodDef->mMethodDeclaration != NULL)
  3347. mModule->mCompiler->mPassInstance->MoreInfo(
  3348. StrFormat("See method declaration '%s'", mModule->MethodToString(methodInstance).c_str()),
  3349. methodInstance->mMethodDef->GetRefNode());
  3350. };
  3351. BfIRConstHolder* constHolder = methodInstance->GetOwner()->mConstHolder;
  3352. auto customAttribute = customAttributes->Get(mModule->mCompiler->mObsoleteAttributeTypeDef);
  3353. if ((customAttribute != NULL) && (!customAttribute->mCtorArgs.IsEmpty()))
  3354. {
  3355. String err;
  3356. err = StrFormat("'%s' is obsolete", mModule->MethodToString(methodInstance).c_str());
  3357. bool isError = false;
  3358. auto constant = constHolder->GetConstant(customAttribute->mCtorArgs[0]);
  3359. if (constant->mTypeCode == BfTypeCode_Boolean)
  3360. {
  3361. isError = constant->mBool;
  3362. }
  3363. else if (customAttribute->mCtorArgs.size() >= 2)
  3364. {
  3365. String* str = mModule->GetStringPoolString(customAttribute->mCtorArgs[0], constHolder);
  3366. if (str != NULL)
  3367. {
  3368. err += ":\n '";
  3369. err += *str;
  3370. err += "'";
  3371. }
  3372. constant = constHolder->GetConstant(customAttribute->mCtorArgs[1]);
  3373. isError = constant->mBool;
  3374. }
  3375. BfError* error = NULL;
  3376. if (isError)
  3377. error = mModule->Fail(err, targetSrc);
  3378. else
  3379. error = mModule->Warn(0, err, targetSrc);
  3380. if (error != NULL)
  3381. _AddMethodDeclarationMoreInfo();
  3382. }
  3383. customAttribute = customAttributes->Get(mModule->mCompiler->mErrorAttributeTypeDef);
  3384. if ((customAttribute != NULL) && (!customAttribute->mCtorArgs.IsEmpty()))
  3385. {
  3386. String err = StrFormat("Method error: '", mModule->MethodToString(methodInstance).c_str());
  3387. String* str = mModule->GetStringPoolString(customAttribute->mCtorArgs[0], constHolder);
  3388. if (str != NULL)
  3389. err += *str;
  3390. err += "'";
  3391. if (mModule->Fail(err, targetSrc) != NULL)
  3392. _AddMethodDeclarationMoreInfo();
  3393. }
  3394. customAttribute = customAttributes->Get(mModule->mCompiler->mWarnAttributeTypeDef);
  3395. if ((customAttribute != NULL) && (!customAttribute->mCtorArgs.IsEmpty()))
  3396. {
  3397. String err = StrFormat("Method warning: '", mModule->MethodToString(methodInstance).c_str());
  3398. String* str = mModule->GetStringPoolString(customAttribute->mCtorArgs[0], constHolder);
  3399. if (str != NULL)
  3400. err += *str;
  3401. err += "'";
  3402. if (mModule->Warn(0, err, targetSrc) != NULL)
  3403. _AddMethodDeclarationMoreInfo();
  3404. }
  3405. }
  3406. }
  3407. BfTypedValue BfExprEvaluator::CreateCall(BfMethodInstance* methodInstance, BfIRValue func, bool bypassVirtual, SizedArrayImpl<BfIRValue>& irArgs, BfTypedValue* sret, bool isTailCall)
  3408. {
  3409. // static int sCallIdx = 0;
  3410. // if (!mModule->mCompiler->mIsResolveOnly)
  3411. // sCallIdx++;
  3412. // int callIdx = sCallIdx;
  3413. // if (callIdx == 0x000000E8)
  3414. // {
  3415. // NOP;
  3416. // }
  3417. auto methodDef = methodInstance->mMethodDef;
  3418. BfIRValue funcCallInst = func;
  3419. auto importCallKind = methodInstance->GetImportCallKind();
  3420. if ((funcCallInst) && (importCallKind != BfImportCallKind_None))
  3421. {
  3422. if ((funcCallInst.IsFake()) && (!mModule->mBfIRBuilder->mIgnoreWrites))
  3423. {
  3424. mModule->mFuncReferences.TryGetValue(methodInstance, &funcCallInst);
  3425. }
  3426. if (importCallKind == BfImportCallKind_GlobalVar_Hot)
  3427. {
  3428. //TODO: Check against NULL for calling BfLoadSharedLibraries
  3429. auto checkVal = mModule->mBfIRBuilder->CreateLoad(funcCallInst);
  3430. BfIRBlock nullBlock = mModule->mBfIRBuilder->CreateBlock("importNull");
  3431. BfIRBlock doneBlock = mModule->mBfIRBuilder->CreateBlock("importLoad");
  3432. auto condVal = mModule->mBfIRBuilder->CreateIsNull(checkVal);
  3433. mModule->mBfIRBuilder->CreateCondBr(condVal, nullBlock, doneBlock);
  3434. mModule->mBfIRBuilder->AddBlock(nullBlock);
  3435. mModule->mBfIRBuilder->SetInsertPoint(nullBlock);
  3436. auto loadSharedLibsFunc = mModule->GetBuiltInFunc(BfBuiltInFuncType_LoadSharedLibraries);
  3437. mModule->mBfIRBuilder->CreateCall(loadSharedLibsFunc, SizedArray<BfIRValue, 0>());
  3438. mModule->mBfIRBuilder->CreateBr(doneBlock);
  3439. mModule->mBfIRBuilder->AddBlock(doneBlock);
  3440. mModule->mBfIRBuilder->SetInsertPoint(doneBlock);
  3441. funcCallInst = mModule->mBfIRBuilder->CreateLoad(funcCallInst);
  3442. }
  3443. else
  3444. {
  3445. funcCallInst = mModule->mBfIRBuilder->CreateLoad(funcCallInst);
  3446. }
  3447. }
  3448. if ((methodInstance->GetOwner()->mTypeDef == mModule->mCompiler->mDeferredCallTypeDef) &&
  3449. (methodInstance->mMethodDef->mName == "Cancel"))
  3450. {
  3451. if (mModule->mCurMethodState != NULL)
  3452. mModule->mCurMethodState->mCancelledDeferredCall = true;
  3453. }
  3454. if (methodDef->mNoReturn)
  3455. {
  3456. mModule->mCurMethodState->SetHadReturn(true);
  3457. mModule->mCurMethodState->mLeftBlockUncond = true;
  3458. }
  3459. if (mModule->mCurTypeInstance != NULL)
  3460. {
  3461. bool isVirtual = (methodInstance->mVirtualTableIdx != -1) && (!bypassVirtual);
  3462. mModule->AddDependency(methodInstance->mMethodInstanceGroup->mOwner, mModule->mCurTypeInstance, isVirtual ? BfDependencyMap::DependencyFlag_VirtualCall : BfDependencyMap::DependencyFlag_Calls);
  3463. mModule->AddCallDependency(methodInstance, bypassVirtual);
  3464. }
  3465. if (methodInstance->GetOwner()->IsUnspecializedType())
  3466. {
  3467. BF_ASSERT((!methodInstance->mIRFunction) || (methodInstance == mModule->mCurMethodInstance));
  3468. }
  3469. if (mFunctionBindResult != NULL)
  3470. {
  3471. BF_ASSERT(mFunctionBindResult->mMethodInstance == NULL);
  3472. mFunctionBindResult->mMethodInstance = methodInstance;
  3473. for (auto arg : irArgs)
  3474. mFunctionBindResult->mIRArgs.push_back(arg);
  3475. }
  3476. BfType* origReturnType = methodInstance->mReturnType;
  3477. /*if (origReturnType->IsSelf())
  3478. {
  3479. origReturnType = methodInstance->GetOwner();
  3480. BF_ASSERT(origReturnType->IsInterface());
  3481. }*/
  3482. BfType* returnType = origReturnType;
  3483. BfTypedValue sretVal;
  3484. auto _GetDefaultReturnValue = [&]()
  3485. {
  3486. if (returnType->IsRef())
  3487. {
  3488. auto result = mModule->GetDefaultTypedValue(returnType->GetUnderlyingType(), true, BfDefaultValueKind_Addr);
  3489. if (methodDef->mIsReadOnly)
  3490. result.mKind = BfTypedValueKind_ReadOnlyAddr;
  3491. return result;
  3492. }
  3493. else
  3494. {
  3495. auto val = mModule->GetDefaultTypedValue(returnType, true, methodInstance->HasStructRet() ? BfDefaultValueKind_Addr : BfDefaultValueKind_Value);
  3496. if (val.mKind == BfTypedValueKind_Addr)
  3497. val.mKind = BfTypedValueKind_TempAddr;
  3498. return val;
  3499. }
  3500. };
  3501. mModule->PopulateType(origReturnType, BfPopulateType_Data);
  3502. if (methodInstance->HasStructRet())
  3503. {
  3504. // We need to ensure that mReceivingValue has the correct type, otherwise it's possible that a conversion operator needs to be applied
  3505. // This happens for returning Result<T>'s with a 'T' value
  3506. if ((sret == NULL) && (mReceivingValue != NULL) && (mReceivingValue->mType == returnType))
  3507. {
  3508. sretVal = *mReceivingValue;
  3509. sret = &sretVal;
  3510. auto ptrType = mModule->CreatePointerType(returnType);
  3511. if (returnType != sret->mType)
  3512. {
  3513. sret->mValue = mModule->mBfIRBuilder->CreateBitCast(sret->mValue, mModule->mBfIRBuilder->MapType(ptrType));
  3514. sret->mType = returnType;
  3515. }
  3516. mReceivingValue = NULL;
  3517. }
  3518. if (sret == NULL)
  3519. {
  3520. sretVal = BfTypedValue(mModule->CreateAlloca(returnType), returnType, BfTypedValueKind_TempAddr);
  3521. sret = &sretVal;
  3522. }
  3523. }
  3524. else
  3525. {
  3526. BF_ASSERT(sret == NULL);
  3527. }
  3528. if ((mModule->mCurMethodState != NULL) && (mModule->mCurMethodState->mClosureState != NULL) && (mModule->mCurMethodState->mClosureState->mCapturing))
  3529. {
  3530. return _GetDefaultReturnValue();
  3531. }
  3532. BF_ASSERT(!methodInstance->mDisallowCalling);
  3533. if ((mModule->mCompiler->mResolvePassData != NULL) && (mModule->mCompiler->mResolvePassData->mAutoComplete != NULL))
  3534. {
  3535. // In an autocomplete pass we may have stale method references that need to be resolved
  3536. // in the full classify pass, and in the full classify pass while just refreshing internals, we
  3537. // may have NULL funcs temporarily. We simply skip generating the method call here.
  3538. if (methodInstance->mVirtualTableIdx == -1)
  3539. {
  3540. if (methodInstance->GetOwner()->IsInterface())
  3541. {
  3542. // We're attempting to directly invoke a non-virtual interface method, if we're return an interface then
  3543. // it is a concrete interface
  3544. if (returnType->IsInterface())
  3545. returnType = mModule->CreateConcreteInterfaceType(returnType->ToTypeInstance());
  3546. }
  3547. }
  3548. BfTypedValue result;
  3549. if (sret != NULL)
  3550. result = *sret;
  3551. else
  3552. result = _GetDefaultReturnValue();
  3553. return result;
  3554. }
  3555. if (((!func) && (methodInstance->mIsUnspecialized)) || (mModule->mBfIRBuilder->mIgnoreWrites))
  3556. {
  3557. // We don't actually submit method calls for unspecialized methods
  3558. // - this includes all methods in unspecialized types
  3559. return _GetDefaultReturnValue();
  3560. }
  3561. if (methodInstance->mVirtualTableIdx != -1)
  3562. {
  3563. if ((!bypassVirtual) && (mDeferCallRef == NULL))
  3564. {
  3565. auto funcType = mModule->mBfIRBuilder->MapMethod(methodInstance);
  3566. auto funcPtrType1 = mModule->mBfIRBuilder->GetPointerTo(funcType);
  3567. auto funcPtrType2 = mModule->mBfIRBuilder->GetPointerTo(funcPtrType1);
  3568. auto funcPtrType3 = mModule->mBfIRBuilder->GetPointerTo(funcPtrType2);
  3569. auto funcPtrType4 = mModule->mBfIRBuilder->GetPointerTo(funcPtrType3);
  3570. if (methodInstance->mMethodInstanceGroup->mOwner->IsInterface())
  3571. {
  3572. // IFace dispatch
  3573. auto ifaceTypeInst = methodInstance->mMethodInstanceGroup->mOwner;
  3574. BfIRValue slotOfs = mModule->GetInterfaceSlotNum(methodInstance->mMethodInstanceGroup->mOwner);
  3575. auto vDataPtrPtr = mModule->mBfIRBuilder->CreateBitCast(irArgs[0], funcPtrType4);
  3576. auto vDataPtr = mModule->FixClassVData(mModule->mBfIRBuilder->CreateLoad(vDataPtrPtr/*, "vtable"*/));
  3577. auto ifacePtrPtr = mModule->mBfIRBuilder->CreateInBoundsGEP(vDataPtr, slotOfs/*, "iface"*/);
  3578. auto ifacePtr = mModule->mBfIRBuilder->CreateLoad(ifacePtrPtr);
  3579. auto funcPtr = mModule->mBfIRBuilder->CreateInBoundsGEP(ifacePtr, methodInstance->mVirtualTableIdx/*, "vfn"*/);
  3580. funcCallInst = mModule->mBfIRBuilder->CreateLoad(funcPtr);
  3581. }
  3582. else
  3583. {
  3584. mModule->HadSlotCountDependency();
  3585. // Virtual dispatch
  3586. // int vDataIdx = 0;
  3587. // vDataIdx += 1 + methodInstance->GetOwner()->GetDynCastVDataCount() + mModule->mCompiler->mMaxInterfaceSlots;
  3588. BfIRValue vDataPtr;
  3589. BfIRValue vDataIdx;
  3590. if ((mModule->mCompiler->mOptions.mHasVDataExtender) && (mModule->mCompiler->IsHotCompile()))
  3591. {
  3592. auto typeInst = methodInstance->mMethodInstanceGroup->mOwner;
  3593. int extMethodIdx = (methodInstance->mVirtualTableIdx - typeInst->GetBaseVTableSize()) - typeInst->GetOrigSelfVTableSize();
  3594. if (extMethodIdx >= 0)
  3595. {
  3596. BF_ASSERT(mModule->mCompiler->IsHotCompile());
  3597. // We have grown outside our original virtual table, Load the new vdataPtr from the mHasVDataExtender
  3598. // vDataPtr = obj.vtable.extension.entry[curVersion]
  3599. BfIRValue vDataPtrPtr = mModule->mBfIRBuilder->CreateBitCast(irArgs[0], funcPtrType4);
  3600. vDataPtr = mModule->FixClassVData(mModule->mBfIRBuilder->CreateLoad(vDataPtrPtr));
  3601. // The offset of the vExt is one past the base vtable. When a base class extends its virtual table, an entry
  3602. // for that new method is inserted in mVirtualMethodTable (thus increasing the index relative to GetBaseVTableSize()),
  3603. // but the actual written vtable position doesn't change, hence offsetting from GetOrigBaseVTableSize()
  3604. #ifdef _DEBUG
  3605. int vExtIdx = typeInst->GetBaseVTableSize();
  3606. BF_ASSERT(typeInst->mVirtualMethodTable[vExtIdx].mDeclaringMethod.mMethodNum == -1); // A type entry with a -1 mMethodNum means it's a vtable ext slot
  3607. #endif
  3608. int vExtOfs = typeInst->GetOrigBaseVTableSize();
  3609. vDataIdx = mModule->mBfIRBuilder->CreateConst(BfTypeCode_Int32, 1 + mModule->mCompiler->GetDynCastVDataCount() + mModule->mCompiler->mMaxInterfaceSlots);
  3610. vDataIdx = mModule->mBfIRBuilder->CreateAdd(vDataIdx, mModule->mBfIRBuilder->CreateConst(BfTypeCode_Int32, vExtOfs));
  3611. BfIRValue extendPtr = mModule->mBfIRBuilder->CreateInBoundsGEP(vDataPtr, vDataIdx);
  3612. vDataPtr = mModule->mBfIRBuilder->CreateLoad(extendPtr);
  3613. vDataIdx = mModule->mBfIRBuilder->CreateConst(BfTypeCode_Int32, extMethodIdx);
  3614. }
  3615. else
  3616. {
  3617. // Map this new virtual index back to the original index
  3618. //vDataIdx += (methodInstance->mVirtualTableIdx - typeInst->GetBaseVTableSize()) + typeInst->GetOrigBaseVTableSize();
  3619. //vDataIdx = mModule->mBfIRBuilder->CreateConst(BfTypeCode_Int32, 1 + methodInstance->GetOwner()->GetDynCastVDataCount() + mModule->mCompiler->mMaxInterfaceSlots);
  3620. vDataIdx = mModule->mBfIRBuilder->GetConfigConst(BfIRConfigConst_VirtualMethodOfs, BfTypeCode_Int32);
  3621. vDataIdx = mModule->mBfIRBuilder->CreateAdd(vDataIdx, mModule->mBfIRBuilder->CreateConst(BfTypeCode_Int32,
  3622. (methodInstance->mVirtualTableIdx - typeInst->GetBaseVTableSize()) + typeInst->GetOrigBaseVTableSize()));
  3623. }
  3624. }
  3625. else
  3626. {
  3627. //vDataIdx += methodInstance->mVirtualTableIdx;
  3628. //vDataIdx = mModule->mBfIRBuilder->CreateConst(BfTypeCode_Int32, 1 + methodInstance->GetOwner()->GetDynCastVDataCount() + mModule->mCompiler->mMaxInterfaceSlots);
  3629. vDataIdx = mModule->mBfIRBuilder->GetConfigConst(BfIRConfigConst_VirtualMethodOfs, BfTypeCode_Int32);
  3630. vDataIdx = mModule->mBfIRBuilder->CreateAdd(vDataIdx, mModule->mBfIRBuilder->CreateConst(BfTypeCode_Int32, methodInstance->mVirtualTableIdx));
  3631. }
  3632. if (!vDataPtr)
  3633. {
  3634. BfIRValue vDataPtrPtr = mModule->mBfIRBuilder->CreateBitCast(irArgs[0], funcPtrType3);
  3635. vDataPtr = mModule->FixClassVData(mModule->mBfIRBuilder->CreateLoad(vDataPtrPtr/*, "vtable"*/));
  3636. }
  3637. auto funcPtr = mModule->mBfIRBuilder->CreateInBoundsGEP(vDataPtr, vDataIdx/*, "vfn"*/);
  3638. funcCallInst = mModule->mBfIRBuilder->CreateLoad(funcPtr);
  3639. }
  3640. }
  3641. }
  3642. else // non-virtual
  3643. {
  3644. if (methodInstance->GetOwner()->IsInterface())
  3645. {
  3646. // We're attempting to directly invoke a non-virtual interface method, this will happen during the unspecialized pass
  3647. // OR if we had an error and didn't find an implementing member in the actual target
  3648. if (!mModule->mCurMethodInstance->mIsUnspecialized)
  3649. mModule->AssertErrorState();
  3650. if (returnType->IsInterface())
  3651. returnType = mModule->CreateConcreteInterfaceType(returnType->ToTypeInstance());
  3652. return _GetDefaultReturnValue();
  3653. }
  3654. }
  3655. if (mFunctionBindResult != NULL)
  3656. {
  3657. mFunctionBindResult->mFunc = funcCallInst;
  3658. if (irArgs.size() != 0)
  3659. {
  3660. auto targetType = methodInstance->mMethodInstanceGroup->mOwner;
  3661. if ((targetType->IsValueType()) && (targetType->IsSplattable()) && (!methodDef->HasNoThisSplat()))
  3662. mFunctionBindResult->mTarget = BfTypedValue(irArgs[0], targetType, BfTypedValueKind_SplatHead);
  3663. else
  3664. mFunctionBindResult->mTarget = BfTypedValue(irArgs[0], targetType, targetType->IsComposite() ? BfTypedValueKind_Addr : BfTypedValueKind_Value);
  3665. }
  3666. else
  3667. {
  3668. mFunctionBindResult->mTarget = BfTypedValue();
  3669. }
  3670. return BfTypedValue();
  3671. }
  3672. if (methodInstance->mReturnType == NULL)
  3673. {
  3674. mModule->AssertErrorState();
  3675. return BfTypedValue();
  3676. }
  3677. if ((mModule->mCurMethodInstance != NULL) && (mModule->mCurMethodInstance->mIsUnspecialized))
  3678. {
  3679. // Don't actually do the call - our target may be a generic param
  3680. return _GetDefaultReturnValue();
  3681. }
  3682. if (mDeferCallRef != NULL)
  3683. {
  3684. mModule->AddDeferredCall(BfModuleMethodInstance(methodInstance, func), irArgs, mDeferScopeAlloc, mDeferCallRef);
  3685. //return _GetDefaultReturnValue();
  3686. return mModule->GetFakeTypedValue(returnType);
  3687. }
  3688. if (!funcCallInst)
  3689. {
  3690. if ((mModule->HasCompiledOutput()) || (mModule->mCompiler->mOptions.mExtraResolveChecks))
  3691. {
  3692. // This can happen either from an error, or from the resolver while doing Internals_Changed processing
  3693. mModule->AssertErrorState();
  3694. }
  3695. //return mModule->GetDefaultTypedValue(returnType,/*, true*/false, returnType->IsComposite());
  3696. return _GetDefaultReturnValue();
  3697. }
  3698. bool hasResult = !methodInstance->mReturnType->IsValuelessType();
  3699. BfIRValue firstArg;
  3700. if (irArgs.size() != 0)
  3701. firstArg = irArgs[0];
  3702. auto methodInstOwner = methodInstance->GetOwner();
  3703. auto expectCallingConvention = mModule->GetCallingConvention(methodInstOwner, methodDef);
  3704. if ((methodInstOwner->IsFunction()) && (methodInstance->GetParamCount() > 0) && (methodInstance->GetParamName(0) == "this"))
  3705. {
  3706. auto paramType = methodInstance->GetParamType(0);
  3707. if (!paramType->IsValueType())
  3708. expectCallingConvention = BfIRCallingConv_ThisCall;
  3709. }
  3710. if ((methodInstance->mAlwaysInline) && (mModule->mCompiler->mOptions.mEmitLineInfo))
  3711. {
  3712. // Emit a NOP so we always have a "step over" point
  3713. mModule->EmitEnsureInstructionAt();
  3714. }
  3715. if (returnType->IsComposite())
  3716. mModule->mBfIRBuilder->PopulateType(returnType);
  3717. BfIRValue callInst;
  3718. if (sret != NULL)
  3719. {
  3720. SizedArray<BfIRValue, 8> sretIRArgs;
  3721. sretIRArgs.push_back(sret->mValue);
  3722. if (!irArgs.IsEmpty())
  3723. sretIRArgs.Insert(sretIRArgs.size(), &irArgs[0], irArgs.size());
  3724. callInst = mModule->mBfIRBuilder->CreateCall(funcCallInst, sretIRArgs);
  3725. }
  3726. else
  3727. {
  3728. callInst = mModule->mBfIRBuilder->CreateCall(funcCallInst, irArgs);
  3729. if (hasResult)
  3730. mModule->mBfIRBuilder->SetName(callInst, methodDef->mName);
  3731. }
  3732. if (expectCallingConvention != BfIRCallingConv_CDecl)
  3733. mModule->mBfIRBuilder->SetCallCallingConv(callInst, expectCallingConvention);
  3734. if (methodDef->mNoReturn)
  3735. mModule->mBfIRBuilder->Call_AddAttribute(callInst, -1, BfIRAttribute_NoReturn);
  3736. bool hadAttrs = false;
  3737. int paramIdx = 0;
  3738. bool doingThis = !methodDef->mIsStatic;
  3739. int argIdx = 0;
  3740. if (sret != NULL)
  3741. {
  3742. mModule->mBfIRBuilder->Call_AddAttribute(callInst, argIdx + 1, BfIRAttribute_StructRet);
  3743. argIdx++;
  3744. }
  3745. for ( ; argIdx < (int)irArgs.size(); /*argIdx++*/)
  3746. {
  3747. auto _HandleParamType = [&] (BfType* paramType)
  3748. {
  3749. if (paramType->IsStruct())
  3750. {
  3751. if ((!doingThis) || (!methodDef->mIsMutating && !methodDef->mNoSplat))
  3752. {
  3753. auto loweredTypeCode = paramType->GetLoweredType();
  3754. if (loweredTypeCode != BfTypeCode_None)
  3755. {
  3756. argIdx++;
  3757. return; // Lowering never requires attributes
  3758. }
  3759. }
  3760. }
  3761. int addDeref = -1;
  3762. if (paramType->IsRef())
  3763. {
  3764. auto refType = (BfRefType*)paramType;
  3765. auto elementType = refType->mElementType;
  3766. mModule->PopulateType(elementType, BfPopulateType_Data);
  3767. addDeref = elementType->mSize;
  3768. if ((addDeref <= 0) && (!elementType->IsValuelessType()))
  3769. mModule->AssertErrorState();
  3770. }
  3771. if ((paramType->IsComposite()) && (!paramType->IsTypedPrimitive()))
  3772. {
  3773. if (mModule->mCompiler->mOptions.mAllowStructByVal)
  3774. {
  3775. //byval
  3776. }
  3777. else
  3778. {
  3779. mModule->mBfIRBuilder->Call_AddAttribute(callInst, argIdx + 1, BfIRAttribute_NoCapture);
  3780. mModule->PopulateType(paramType, BfPopulateType_Data);
  3781. addDeref = paramType->mSize;
  3782. }
  3783. }
  3784. else if (paramType->IsPrimitiveType())
  3785. {
  3786. auto primType = (BfPrimitiveType*)paramType;
  3787. if ((primType->mTypeDef->mTypeCode == BfTypeCode_Boolean) && (!methodInstance->mIsIntrinsic))
  3788. mModule->mBfIRBuilder->Call_AddAttribute(callInst, argIdx + 1, BfIRAttribute_ZExt);
  3789. }
  3790. if (addDeref >= 0)
  3791. {
  3792. mModule->mBfIRBuilder->Call_AddAttribute(callInst, argIdx + 1, BfIRAttribute_Dereferencable, addDeref);
  3793. }
  3794. argIdx++;
  3795. };
  3796. BfType* paramType = NULL;
  3797. if (doingThis)
  3798. {
  3799. paramType = methodInstance->GetOwner();
  3800. if (paramType->IsValuelessType())
  3801. {
  3802. doingThis = false;
  3803. continue;
  3804. }
  3805. bool isSplatted = methodInstance->GetParamIsSplat(-1); // (resolvedTypeRef->IsSplattable()) && (!methodDef->mIsMutating);
  3806. if (isSplatted)
  3807. {
  3808. BfTypeUtils::SplatIterate(_HandleParamType, paramType);
  3809. doingThis = false;
  3810. continue;
  3811. }
  3812. else
  3813. _HandleParamType(paramType);
  3814. }
  3815. else
  3816. {
  3817. paramType = methodInstance->GetParamType(paramIdx);
  3818. if ((paramType->IsValuelessType()) && (!paramType->IsMethodRef()))
  3819. {
  3820. paramIdx++;
  3821. continue;
  3822. }
  3823. //if (resolvedTypeRef->IsSplattable())
  3824. if (methodInstance->GetParamIsSplat(paramIdx))
  3825. {
  3826. BfTypeUtils::SplatIterate(_HandleParamType, paramType);
  3827. paramIdx++;
  3828. continue;
  3829. }
  3830. else
  3831. _HandleParamType(methodInstance->GetParamType(paramIdx));
  3832. }
  3833. if (doingThis)
  3834. doingThis = false;
  3835. else
  3836. paramIdx++;
  3837. //argIdx++;
  3838. }
  3839. if (isTailCall)
  3840. mModule->mBfIRBuilder->SetTailCall(callInst);
  3841. if (methodDef->mNoReturn)
  3842. {
  3843. mModule->mBfIRBuilder->CreateUnreachable();
  3844. // For debuggability when looking back at stack trace
  3845. //mModule->ExtendLocalLifetimes(0);
  3846. if (mModule->IsTargetingBeefBackend())
  3847. {
  3848. auto checkScope = mModule->mCurMethodState->mCurScope;
  3849. while (checkScope != NULL)
  3850. {
  3851. mModule->EmitLifetimeEnds(checkScope);
  3852. checkScope = checkScope->mPrevScope;
  3853. }
  3854. // This 'fake' branch extends lifetimes of outer variable scopes
  3855. if (mModule->mCurMethodState->mIRExitBlock)
  3856. mModule->mBfIRBuilder->CreateBr_Fake(mModule->mCurMethodState->mIRExitBlock);
  3857. }
  3858. }
  3859. else
  3860. {
  3861. if (mModule->mCurMethodState != NULL)
  3862. mModule->mCurMethodState->mMayNeedThisAccessCheck = true;
  3863. }
  3864. BfTypedValue result;
  3865. if (sret != NULL)
  3866. result = *sret;
  3867. else if (hasResult)
  3868. result = BfTypedValue(callInst, methodInstance->mReturnType);
  3869. else
  3870. result = mModule->GetFakeTypedValue(methodInstance->mReturnType);
  3871. if (result.mType->IsRef())
  3872. {
  3873. result = mModule->RemoveRef(result);
  3874. if (methodDef->mIsReadOnly)
  3875. {
  3876. if (result.mKind == BfTypedValueKind_Addr)
  3877. result.mKind = BfTypedValueKind_ReadOnlyAddr;
  3878. }
  3879. }
  3880. return result;
  3881. }
  3882. BfTypedValue BfExprEvaluator::CreateCall(BfMethodMatcher* methodMatcher, BfTypedValue target)
  3883. {
  3884. auto moduleMethodInstance = mModule->GetMethodInstance(methodMatcher->mBestMethodTypeInstance, methodMatcher->mBestMethodDef, methodMatcher->mBestMethodGenericArguments);
  3885. if (moduleMethodInstance.mMethodInstance == NULL)
  3886. return BfTypedValue();
  3887. if ((target) && (target.mType != moduleMethodInstance.mMethodInstance->GetOwner()))
  3888. {
  3889. auto castedTarget = mModule->Cast(methodMatcher->mTargetSrc, target, moduleMethodInstance.mMethodInstance->GetOwner());
  3890. BF_ASSERT(castedTarget);
  3891. target = castedTarget;
  3892. }
  3893. return CreateCall(methodMatcher->mTargetSrc, target, BfTypedValue(), methodMatcher->mBestMethodDef, moduleMethodInstance, false, methodMatcher->mArguments);
  3894. }
  3895. void BfExprEvaluator::MakeBaseConcrete(BfTypedValue& typedValue)
  3896. {
  3897. if (typedValue.IsBase())
  3898. {
  3899. auto baseType = mModule->mCurTypeInstance->mBaseType;
  3900. if (baseType == NULL)
  3901. baseType = mModule->mContext->mBfObjectType;
  3902. mModule->PopulateType(baseType, BfPopulateType_Data);
  3903. typedValue = mModule->Cast(NULL, typedValue, baseType, BfCastFlags_Explicit);
  3904. }
  3905. }
  3906. void BfExprEvaluator::SplatArgs(BfTypedValue value, SizedArrayImpl<BfIRValue>& irArgs)
  3907. {
  3908. if (value.IsSplat())
  3909. {
  3910. int componentIdx = 0;
  3911. BfTypeUtils::SplatIterate([&](BfType* checkType) { irArgs.push_back(mModule->ExtractSplatValue(value, componentIdx++, checkType)); }, value.mType);
  3912. return;
  3913. }
  3914. mModule->mBfIRBuilder->PopulateType(value.mType);
  3915. std::function<void(BfTypedValue)> checkTypeLambda = [&](BfTypedValue curValue)
  3916. {
  3917. BfType* checkType = curValue.mType;
  3918. if (checkType->IsStruct())
  3919. {
  3920. auto checkTypeInstance = checkType->ToTypeInstance();
  3921. if ((checkTypeInstance->mBaseType != NULL) && (!checkTypeInstance->mBaseType->IsValuelessType()))
  3922. {
  3923. BfTypedValue baseValue;
  3924. if (curValue.IsAddr())
  3925. baseValue = BfTypedValue((!curValue.mValue) ? BfIRValue() : mModule->mBfIRBuilder->CreateInBoundsGEP(curValue.mValue, 0, 0), checkTypeInstance->mBaseType, true);
  3926. else
  3927. baseValue = BfTypedValue((!curValue.mValue) ? BfIRValue() : mModule->mBfIRBuilder->CreateExtractValue(curValue.mValue, 0), checkTypeInstance->mBaseType);
  3928. checkTypeLambda(baseValue);
  3929. }
  3930. if (checkTypeInstance->mIsUnion)
  3931. {
  3932. auto unionInnerType = checkTypeInstance->GetUnionInnerType();
  3933. if (!unionInnerType->IsValuelessType())
  3934. {
  3935. BfTypedValue unionValue = mModule->ExtractValue(curValue, NULL, 1);
  3936. checkTypeLambda(unionValue);
  3937. }
  3938. if (checkTypeInstance->IsEnum())
  3939. {
  3940. BfTypedValue dscrValue = mModule->ExtractValue(curValue, NULL, 2);
  3941. checkTypeLambda(dscrValue);
  3942. }
  3943. }
  3944. else
  3945. {
  3946. for (int fieldIdx = 0; fieldIdx < (int)checkTypeInstance->mFieldInstances.size(); fieldIdx++)
  3947. {
  3948. auto fieldInstance = (BfFieldInstance*)&checkTypeInstance->mFieldInstances[fieldIdx];
  3949. if (fieldInstance->mDataIdx >= 0)
  3950. {
  3951. BfTypedValue fieldValue = mModule->ExtractValue(curValue, fieldInstance, fieldInstance->mDataIdx);
  3952. checkTypeLambda(fieldValue);
  3953. }
  3954. }
  3955. }
  3956. }
  3957. else if (checkType->IsMethodRef())
  3958. {
  3959. BF_ASSERT(curValue.IsAddr());
  3960. BfMethodRefType* methodRefType = (BfMethodRefType*)checkType;
  3961. for (int dataIdx = 0; dataIdx < methodRefType->GetCaptureDataCount(); dataIdx++)
  3962. {
  3963. auto checkType = methodRefType->GetCaptureType(dataIdx);
  3964. if (methodRefType->WantsDataPassedAsSplat(dataIdx))
  3965. {
  3966. BF_ASSERT(dataIdx == 0);
  3967. auto ptrType = mModule->CreatePointerType(checkType);
  3968. auto elemPtr = mModule->mBfIRBuilder->CreateBitCast(curValue.mValue, mModule->mBfIRBuilder->MapType(ptrType));
  3969. checkTypeLambda(BfTypedValue(elemPtr, checkType, BfTypedValueKind_Addr));
  3970. //BfTypedValue fieldValue = mModule->ExtractValue(curValue, fieldInstance, fieldInstance->mDataIdx);
  3971. //checkTypeLambda(fieldValue);
  3972. }
  3973. else
  3974. {
  3975. auto elemVal = mModule->mBfIRBuilder->CreateInBoundsGEP(curValue.mValue, 0, dataIdx);
  3976. if (!checkType->IsComposite())
  3977. elemVal = mModule->mBfIRBuilder->CreateLoad(elemVal);
  3978. irArgs.Add(elemVal);
  3979. //irArgs.Add(mModule->ExtractValue(curValue, dataIdx));
  3980. }
  3981. }
  3982. }
  3983. else if (!checkType->IsValuelessType())
  3984. {
  3985. auto loadedVal = mModule->LoadValue(curValue);
  3986. irArgs.push_back(loadedVal.mValue);
  3987. }
  3988. };
  3989. checkTypeLambda(value);
  3990. }
  3991. void BfExprEvaluator::PushArg(BfTypedValue argVal, SizedArrayImpl<BfIRValue>& irArgs, bool disableSplat, bool disableLowering)
  3992. {
  3993. MakeBaseConcrete(argVal);
  3994. if (argVal.mType->IsValuelessType())
  3995. return;
  3996. bool wantSplat = false;
  3997. if ((argVal.mType->IsSplattable()) && (!disableSplat))
  3998. {
  3999. if ((int)irArgs.size() + argVal.mType->GetSplatCount() <= mModule->mCompiler->mOptions.mMaxSplatRegs)
  4000. wantSplat = true;
  4001. }
  4002. if (wantSplat)
  4003. {
  4004. SplatArgs(argVal, irArgs);
  4005. }
  4006. else
  4007. {
  4008. if (argVal.mType->IsComposite())
  4009. {
  4010. argVal = mModule->MakeAddressable(argVal);
  4011. if (!disableLowering)
  4012. {
  4013. auto loweredTypeCode = argVal.mType->GetLoweredType();
  4014. if (loweredTypeCode != BfTypeCode_None)
  4015. {
  4016. auto primType = mModule->GetPrimitiveType(loweredTypeCode);
  4017. auto ptrType = mModule->CreatePointerType(primType);
  4018. BfIRValue primPtrVal = mModule->mBfIRBuilder->CreateBitCast(argVal.mValue, mModule->mBfIRBuilder->MapType(ptrType));
  4019. auto primVal = mModule->mBfIRBuilder->CreateLoad(primPtrVal);
  4020. irArgs.push_back(primVal);
  4021. return;
  4022. }
  4023. }
  4024. }
  4025. else
  4026. argVal = mModule->LoadValue(argVal);
  4027. irArgs.push_back(argVal.mValue);
  4028. }
  4029. }
  4030. void BfExprEvaluator::PushThis(BfAstNode* targetSrc, BfTypedValue argVal, BfMethodInstance* methodInstance, SizedArrayImpl<BfIRValue>& irArgs, bool skipMutCheck)
  4031. {
  4032. MakeBaseConcrete(argVal);
  4033. auto methodDef = methodInstance->mMethodDef;
  4034. if (methodInstance->IsSkipCall())
  4035. return;
  4036. if (!argVal)
  4037. {
  4038. //BF_ASSERT(mFunctionBindResult != NULL);
  4039. return;
  4040. }
  4041. if (methodDef->mIsMutating)
  4042. {
  4043. bool checkMut = false;
  4044. if (argVal.mType->IsGenericParam())
  4045. {
  4046. // For capturing mutability
  4047. if (mResultLocalVar != NULL)
  4048. mResultLocalVar->mWrittenToId = mModule->mCurMethodState->GetRootMethodState()->mCurAccessId++;
  4049. }
  4050. if (((argVal.mType->IsComposite()) || (argVal.mType->IsTypedPrimitive())))
  4051. {
  4052. if ((argVal.IsReadOnly()) || (!argVal.IsAddr()))
  4053. {
  4054. if (!skipMutCheck)
  4055. {
  4056. String err = StrFormat("call mutating method '%s' on", mModule->MethodToString(methodInstance).c_str());
  4057. CheckModifyResult(argVal, targetSrc, err.c_str());
  4058. }
  4059. if (argVal.IsSplat())
  4060. {
  4061. argVal = mModule->AggregateSplat(argVal);
  4062. argVal = mModule->MakeAddressable(argVal);
  4063. }
  4064. }
  4065. else
  4066. {
  4067. if (mResultLocalVar != NULL)
  4068. {
  4069. // When we are capturing, we need to note that we require capturing by reference here
  4070. mResultLocalVar->mWrittenToId = mModule->mCurMethodState->GetRootMethodState()->mCurAccessId++;
  4071. }
  4072. }
  4073. }
  4074. }
  4075. if (argVal.mType->IsValuelessType())
  4076. return;
  4077. if ((argVal.mType->IsTypedPrimitive()) && (methodDef->HasNoThisSplat()))
  4078. {
  4079. argVal = mModule->MakeAddressable(argVal);
  4080. irArgs.push_back(argVal.mValue);
  4081. return;
  4082. }
  4083. auto thisType = methodInstance->GetParamType(-1);
  4084. PushArg(argVal, irArgs, methodDef->HasNoThisSplat(), thisType->IsPointer());
  4085. }
  4086. void BfExprEvaluator::FinishDeferredEvals(SizedArrayImpl<BfResolvedArg>& argValues)
  4087. {
  4088. for (int argIdx = 0; argIdx < argValues.size(); argIdx++)
  4089. {
  4090. auto argValue = argValues[argIdx].mTypedValue;
  4091. if ((argValues[argIdx].mArgFlags & (BfArgFlag_DelegateBindAttempt | BfArgFlag_LambdaBindAttempt | BfArgFlag_UnqualifiedDotAttempt | BfArgFlag_DeferredEval)) != 0)
  4092. {
  4093. if (!argValue)
  4094. {
  4095. auto expr = BfNodeDynCast<BfExpression>(argValues[argIdx].mExpression);
  4096. if (expr != NULL)
  4097. argValue = mModule->CreateValueFromExpression(expr);
  4098. }
  4099. }
  4100. }
  4101. }
  4102. void BfExprEvaluator::AddCallDependencies(BfMethodInstance* methodInstance)
  4103. {
  4104. if (methodInstance->mReturnType != NULL)
  4105. mModule->AddDependency(methodInstance->mReturnType, mModule->mCurTypeInstance, BfDependencyMap::DependencyFlag_LocalUsage);
  4106. for (int paramIdx = 0; paramIdx < methodInstance->GetParamCount(); paramIdx++)
  4107. {
  4108. auto paramType = methodInstance->GetParamType(paramIdx);
  4109. mModule->AddDependency(paramType, mModule->mCurTypeInstance, BfDependencyMap::DependencyFlag_LocalUsage);
  4110. }
  4111. if (methodInstance->mMethodInfoEx != NULL)
  4112. {
  4113. for (auto genericArg : methodInstance->mMethodInfoEx->mMethodGenericArguments)
  4114. {
  4115. if (genericArg->IsWrappableType())
  4116. genericArg = mModule->GetWrappedStructType(genericArg);
  4117. mModule->AddDependency(genericArg, mModule->mCurTypeInstance, BfDependencyMap::DependencyFlag_LocalUsage);
  4118. }
  4119. }
  4120. }
  4121. //TODO: delete argumentsZ
  4122. BfTypedValue BfExprEvaluator::CreateCall(BfAstNode* targetSrc, const BfTypedValue& inTarget, const BfTypedValue& origTarget, BfMethodDef* methodDef, BfModuleMethodInstance moduleMethodInstance, bool bypassVirtual, SizedArrayImpl<BfResolvedArg>& argValues, bool skipThis)
  4123. {
  4124. static int sCallIdx = 0;
  4125. if (!mModule->mCompiler->mIsResolveOnly)
  4126. sCallIdx++;
  4127. int callIdx = sCallIdx;
  4128. if (callIdx == 0x0000042B)
  4129. {
  4130. NOP;
  4131. }
  4132. // Temporarily disable so we don't capture calls in params
  4133. SetAndRestoreValue<BfFunctionBindResult*> prevBindResult(mFunctionBindResult, NULL);
  4134. BfMethodInstance* methodInstance = moduleMethodInstance.mMethodInstance;
  4135. SizedArray<BfIRValue, 4> irArgs;
  4136. if ((methodDef->mIsAbstract) && (bypassVirtual))
  4137. {
  4138. mModule->Fail(StrFormat("Abstract base method '%s' cannot be invoked", mModule->MethodToString(methodInstance).c_str()), targetSrc);
  4139. }
  4140. bool isSkipCall = moduleMethodInstance.mMethodInstance->IsSkipCall(bypassVirtual);
  4141. BfType* returnType = methodInstance->mReturnType;
  4142. /*if (returnType->IsSelf())
  4143. {
  4144. returnType = methodInstance->GetOwner();
  4145. BF_ASSERT(returnType->IsInterface());
  4146. }*/
  4147. BfTypedValue target = inTarget;
  4148. if (!skipThis)
  4149. {
  4150. if (!methodDef->mIsStatic)
  4151. {
  4152. if (!target)
  4153. {
  4154. FinishDeferredEvals(argValues);
  4155. mModule->Fail(StrFormat("An instance reference is required to %s the non-static method '%s'",
  4156. (prevBindResult.mPrevVal != NULL) ? "bind" : "invoke",
  4157. mModule->MethodToString(methodInstance).c_str()), targetSrc);
  4158. return mModule->GetDefaultTypedValue(returnType);
  4159. }
  4160. auto prevResult = mResult;
  4161. mResult = target;
  4162. CheckResultForReading(mResult);
  4163. mResult = prevResult;
  4164. if (methodDef->mMethodType != BfMethodType_Ctor)
  4165. {
  4166. bool doAccessCheck = true;
  4167. if (target.IsThis())
  4168. {
  4169. if (!mModule->mCurMethodState->mMayNeedThisAccessCheck)
  4170. doAccessCheck = false;
  4171. }
  4172. if ((mModule->mAttributeState != NULL) && (mModule->mAttributeState->mCustomAttributes != NULL) && (mModule->mAttributeState->mCustomAttributes->Contains(mModule->mCompiler->mSkipAccessCheckAttributeTypeDef)))
  4173. doAccessCheck = false;
  4174. if ((doAccessCheck) && (!isSkipCall))
  4175. mModule->EmitObjectAccessCheck(target);
  4176. }
  4177. if (((prevBindResult.mPrevVal == NULL) || (!prevBindResult.mPrevVal->mSkipThis)) &&
  4178. (!isSkipCall))
  4179. {
  4180. bool skipMutCheck = false;
  4181. if ((prevBindResult.mPrevVal != NULL) && (prevBindResult.mPrevVal->mSkipMutCheck))
  4182. {
  4183. // If we are binding a delegate, then we will end up making a copy of the target anyway
  4184. // so we don't need to do a mutability check
  4185. skipMutCheck = true;
  4186. }
  4187. PushThis(targetSrc, target, moduleMethodInstance.mMethodInstance, irArgs, skipMutCheck);
  4188. }
  4189. }
  4190. else if ((target) && (target.mType->IsFunction()))
  4191. {
  4192. CheckResultForReading(target);
  4193. target = mModule->LoadValue(target);
  4194. auto funcType = mModule->mBfIRBuilder->MapMethod(moduleMethodInstance.mMethodInstance);
  4195. auto funcPtrType = mModule->mBfIRBuilder->GetPointerTo(funcType);
  4196. moduleMethodInstance.mFunc = mModule->mBfIRBuilder->CreateIntToPtr(target.mValue, funcPtrType);
  4197. }
  4198. else
  4199. {
  4200. mModule->CheckStaticAccess(methodInstance->mMethodInstanceGroup->mOwner);
  4201. if (target)
  4202. {
  4203. FinishDeferredEvals(argValues);
  4204. mModule->Fail(StrFormat("Method '%s' cannot be accessed with an instance reference; qualify it with a type name instead",
  4205. mModule->MethodToString(methodInstance).c_str()), targetSrc);
  4206. return mModule->GetDefaultTypedValue(returnType);
  4207. }
  4208. }
  4209. }
  4210. if (isSkipCall)
  4211. {
  4212. FinishDeferredEvals(argValues);
  4213. mModule->EmitEnsureInstructionAt();
  4214. return mModule->GetDefaultTypedValue(returnType);
  4215. }
  4216. int argIdx = 0;
  4217. int paramIdx = 0;
  4218. BfIRValue expandedParamAlloca;
  4219. BfTypedValue expandedParamsArray;
  4220. BfType* expandedParamsElementType = NULL;
  4221. int extendedParamIdx = 0;
  4222. AddCallDependencies(methodInstance);
  4223. auto autoComplete = GetAutoComplete();
  4224. if (autoComplete != NULL)
  4225. {
  4226. // Set to false to make sure we don't capture method match info from 'params' array creation
  4227. autoComplete->mIsCapturingMethodMatchInfo = false;
  4228. }
  4229. BfScopeData* boxScopeData = mDeferScopeAlloc;
  4230. if ((boxScopeData == NULL) && (mModule->mCurMethodState != NULL))
  4231. boxScopeData = mModule->mCurMethodState->mCurScope;
  4232. bool failed = false;
  4233. while (true)
  4234. {
  4235. bool isDirectPass = false;
  4236. if (paramIdx >= (int)methodInstance->GetParamCount())
  4237. {
  4238. if (argIdx < (int)argValues.size())
  4239. {
  4240. BfAstNode* errorRef = argValues[argIdx].mExpression;
  4241. if (errorRef == NULL)
  4242. errorRef = targetSrc;
  4243. BfError* error = mModule->Fail(StrFormat("Too many arguments, expected %d fewer.", (int)argValues.size() - argIdx), errorRef);
  4244. if ((error != NULL) && (methodInstance->mMethodDef->mMethodDeclaration != NULL))
  4245. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("See method declaration"), methodInstance->mMethodDef->GetRefNode());
  4246. failed = true;
  4247. break;
  4248. }
  4249. break;
  4250. }
  4251. // Only create actual params if we're not just trying to bind the function
  4252. if ((prevBindResult.mPrevVal != NULL) && (!prevBindResult.mPrevVal->mWantsArgs))
  4253. break;
  4254. BfType* wantType = NULL;
  4255. bool wantsSplat = false;
  4256. if (expandedParamsElementType != NULL)
  4257. {
  4258. wantType = expandedParamsElementType;
  4259. }
  4260. else
  4261. {
  4262. wantsSplat = methodInstance->GetParamIsSplat(paramIdx);
  4263. if (methodInstance->IsImplicitCapture(paramIdx))
  4264. {
  4265. if (mModule->mCurMethodInstance->IsMixin())
  4266. {
  4267. // Don't bother, also- can fail on captures
  4268. }
  4269. else
  4270. {
  4271. // static int captureIdx = 0;
  4272. // captureIdx++;
  4273. // int curCaptureIdx = captureIdx;
  4274. //
  4275. // if (curCaptureIdx == 0x91)
  4276. // {
  4277. // NOP;
  4278. // }
  4279. auto lookupVal = DoImplicitArgCapture(targetSrc, methodInstance, paramIdx, failed, BfImplicitParamKind_General, origTarget);
  4280. if (lookupVal)
  4281. {
  4282. if (wantsSplat)
  4283. {
  4284. SplatArgs(lookupVal, irArgs);
  4285. }
  4286. else
  4287. {
  4288. irArgs.push_back(lookupVal.mValue);
  4289. }
  4290. }
  4291. }
  4292. paramIdx++;
  4293. continue;
  4294. }
  4295. wantType = methodInstance->GetParamType(paramIdx);
  4296. if (wantType->IsSelf())
  4297. wantType = methodInstance->GetOwner();
  4298. BfParamKind paramKind = methodInstance->GetParamKind(paramIdx);
  4299. if (paramKind == BfParamKind_Params)
  4300. {
  4301. //TODO: Check to see if it's a direct array pass
  4302. if (argIdx < (int)argValues.size())
  4303. {
  4304. auto argValue = argValues[argIdx].mTypedValue;
  4305. if ((argValue.IsParams()) /*&& (mModule->CanImplicitlyCast(argValue, wantType))*/)
  4306. isDirectPass = true;
  4307. }
  4308. if (!isDirectPass)
  4309. {
  4310. if (wantType->IsArray())
  4311. {
  4312. BfArrayType* arrayType = (BfArrayType*)wantType;
  4313. mModule->PopulateType(arrayType, BfPopulateType_DataAndMethods);
  4314. expandedParamsElementType = arrayType->mTypeGenericArguments[0];
  4315. int arrayClassSize = arrayType->mInstSize - expandedParamsElementType->mSize;
  4316. int numElements = (int)argValues.size() - argIdx;
  4317. expandedParamsArray = BfTypedValue(mModule->AllocFromType(arrayType->GetUnderlyingType(), boxScopeData, BfIRValue(), mModule->GetConstValue(numElements), 1, BfAllocFlags_None),
  4318. arrayType, false);
  4319. BfResolvedArgs resolvedArgs;
  4320. MatchConstructor(targetSrc, NULL, expandedParamsArray, arrayType, resolvedArgs, false, false);
  4321. //TODO: Assert 'length' var is at slot 1
  4322. auto arrayBits = mModule->mBfIRBuilder->CreateBitCast(expandedParamsArray.mValue, mModule->mBfIRBuilder->MapType(arrayType->mBaseType));
  4323. int arrayLengthBitCount = arrayType->GetLengthBitCount();
  4324. if (arrayLengthBitCount == 0)
  4325. {
  4326. mModule->Fail("INTERNAL ERROR: Unable to find array 'length' field", targetSrc);
  4327. return BfTypedValue();
  4328. }
  4329. auto addr = mModule->mBfIRBuilder->CreateInBoundsGEP(arrayBits, 0, 1);
  4330. if (arrayLengthBitCount == 64)
  4331. mModule->mBfIRBuilder->CreateAlignedStore(mModule->GetConstValue64(numElements), addr, 8);
  4332. else
  4333. mModule->mBfIRBuilder->CreateAlignedStore(mModule->GetConstValue32(numElements), addr, 4);
  4334. PushArg(expandedParamsArray, irArgs);
  4335. }
  4336. else
  4337. {
  4338. int numElements = (int)argValues.size() - argIdx;
  4339. auto genericTypeInst = wantType->ToGenericTypeInstance();
  4340. expandedParamsElementType = genericTypeInst->mTypeGenericArguments[0];
  4341. expandedParamsArray = BfTypedValue(mModule->CreateAlloca(wantType), wantType, true);
  4342. expandedParamAlloca = mModule->CreateAlloca(genericTypeInst->mTypeGenericArguments[0], true, NULL, mModule->GetConstValue(numElements));
  4343. mModule->mBfIRBuilder->CreateStore(expandedParamAlloca, mModule->mBfIRBuilder->CreateInBoundsGEP(expandedParamsArray.mValue, 0, 1));
  4344. mModule->mBfIRBuilder->CreateStore(mModule->GetConstValue(numElements), mModule->mBfIRBuilder->CreateInBoundsGEP(expandedParamsArray.mValue, 0, 2));
  4345. PushArg(expandedParamsArray, irArgs);
  4346. }
  4347. continue;
  4348. }
  4349. }
  4350. }
  4351. BfAstNode* arg = NULL;
  4352. bool hadMissingArg = false;
  4353. if (argIdx < (int)argValues.size())
  4354. {
  4355. arg = argValues[argIdx].mExpression;
  4356. if ((arg == NULL) && (argValues[0].mExpression != NULL))
  4357. hadMissingArg = true;
  4358. }
  4359. else
  4360. hadMissingArg = true;
  4361. BfTypedValue argValue;
  4362. if (hadMissingArg)
  4363. {
  4364. if (expandedParamsArray)
  4365. break;
  4366. if ((argIdx >= (int) methodInstance->mDefaultValues.size()) || (!methodInstance->mDefaultValues[argIdx]))
  4367. {
  4368. BfAstNode* refNode = targetSrc;
  4369. if (argValues.size() > 0)
  4370. {
  4371. auto checkExpr = argValues.back().mExpression;
  4372. if (checkExpr != NULL)
  4373. refNode = checkExpr;
  4374. }
  4375. BfAstNode* prevNode = NULL;
  4376. if (targetSrc == NULL)
  4377. {
  4378. // We must be in BfModule::EmitCtorBody
  4379. }
  4380. else if (auto tupleExpr = BfNodeDynCastExact<BfTupleExpression>(targetSrc))
  4381. {
  4382. if (tupleExpr->mCommas.size() > 0)
  4383. prevNode = tupleExpr->mCommas.back();
  4384. else
  4385. prevNode = tupleExpr->mOpenParen;
  4386. if (tupleExpr->mCloseParen != NULL)
  4387. refNode = tupleExpr->mCloseParen;
  4388. }
  4389. else if (mModule->mParentNodeEntry != NULL)
  4390. {
  4391. if (auto objectCreateExpr = BfNodeDynCast<BfObjectCreateExpression>(mModule->mParentNodeEntry->mNode))
  4392. {
  4393. if (objectCreateExpr->mCommas.size() > 0)
  4394. prevNode = objectCreateExpr->mCommas.back();
  4395. else
  4396. prevNode = objectCreateExpr->mOpenToken;
  4397. if (objectCreateExpr->mCloseToken != NULL)
  4398. refNode = objectCreateExpr->mCloseToken;
  4399. if (auto newNode = BfNodeDynCast<BfNewNode>(objectCreateExpr->mNewNode))
  4400. {
  4401. if (newNode->mAllocNode == targetSrc)
  4402. refNode = targetSrc;
  4403. }
  4404. }
  4405. else if (auto invokeExpr = BfNodeDynCast<BfInvocationExpression>(mModule->mParentNodeEntry->mNode))
  4406. {
  4407. if (invokeExpr->mCommas.size() > 0)
  4408. prevNode = invokeExpr->mCommas.back();
  4409. else
  4410. prevNode = invokeExpr->mOpenParen;
  4411. if (invokeExpr->mCloseParen != NULL)
  4412. refNode = invokeExpr->mCloseParen;
  4413. }
  4414. }
  4415. if ((autoComplete != NULL) && (prevNode != NULL))
  4416. autoComplete->CheckEmptyStart(prevNode, wantType);
  4417. BfError* error = mModule->Fail(StrFormat("Not enough parameters specified, expected %d more.", methodInstance->GetParamCount() - paramIdx), refNode);
  4418. if ((error != NULL) && (methodInstance->mMethodDef->mMethodDeclaration != NULL))
  4419. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("See method declaration"), methodInstance->mMethodDef->GetRefNode());
  4420. failed = true;
  4421. break;
  4422. }
  4423. auto foreignDefaultVal = methodInstance->mDefaultValues[argIdx];
  4424. auto foreignConst = methodInstance->GetOwner()->mConstHolder->GetConstant(methodInstance->mDefaultValues[argIdx]);
  4425. if (foreignConst->mConstType == BfConstType_AggZero)
  4426. {
  4427. // Allow this
  4428. }
  4429. else if (foreignConst->mTypeCode == BfTypeCode_NullPtr)
  4430. {
  4431. if (wantType->IsNullable())
  4432. {
  4433. argValue = mModule->GetDefaultTypedValue(wantType, false, BfDefaultValueKind_Addr);
  4434. }
  4435. }
  4436. if (!argValue)
  4437. {
  4438. argValue = mModule->GetTypedValueFromConstant(foreignConst, methodInstance->GetOwner()->mConstHolder, wantType);
  4439. }
  4440. }
  4441. else
  4442. {
  4443. argValue = argValues[argIdx].mTypedValue;
  4444. if ((argValue.IsParams()) && (!isDirectPass))
  4445. {
  4446. BfAstNode* refNode = argValues[argIdx].mExpression;
  4447. if (auto unaryOperatorExpr = BfNodeDynCast<BfUnaryOperatorExpression>(refNode))
  4448. refNode = unaryOperatorExpr->mOpToken;
  4449. mModule->Warn(0, "Unused 'params' expression", refNode);
  4450. }
  4451. if (wantType->IsMethodRef())
  4452. {
  4453. auto expr = argValues[argIdx].mExpression;
  4454. if (expr != NULL)
  4455. SetMethodElementType(expr);
  4456. if (!argValue)
  4457. argValue = mModule->CreateValueFromExpression(BfNodeDynCast<BfExpression>(argValues[argIdx].mExpression), wantType, BfEvalExprFlags_NoCast);
  4458. // Add any implicit captures now
  4459. auto methodRefType = (BfMethodRefType*)wantType;
  4460. BfMethodInstance* useMethodInstance = methodRefType->mMethodRef;
  4461. for (int dataIdx = 0; dataIdx < methodRefType->GetCaptureDataCount(); dataIdx++)
  4462. {
  4463. int paramIdx = methodRefType->GetParamIdxFromDataIdx(dataIdx);
  4464. auto lookupVal = DoImplicitArgCapture(argValues[argIdx].mExpression, useMethodInstance, paramIdx, failed, BfImplicitParamKind_General, argValue);
  4465. if (lookupVal)
  4466. {
  4467. if (methodRefType->WantsDataPassedAsSplat(dataIdx))
  4468. SplatArgs(lookupVal, irArgs);
  4469. else if (lookupVal.mType->IsComposite())
  4470. {
  4471. irArgs.push_back(lookupVal.mValue);
  4472. }
  4473. else
  4474. irArgs.push_back(lookupVal.mValue);
  4475. }
  4476. }
  4477. paramIdx++;
  4478. argIdx++;
  4479. continue;
  4480. }
  4481. else
  4482. {
  4483. BfParamKind paramKind = BfParamKind_Normal;
  4484. if (paramIdx < methodInstance->GetParamCount())
  4485. paramKind = methodInstance->GetParamKind(paramIdx);
  4486. argValues[argIdx].mExpectedType = wantType;
  4487. argValue = ResolveArgValue(argValues[argIdx], wantType, NULL, paramKind);
  4488. }
  4489. }
  4490. if (!argValue)
  4491. {
  4492. failed = true;
  4493. }
  4494. if ((argValue) && (arg != NULL))
  4495. {
  4496. argValue = mModule->Cast(arg, argValue, wantType);
  4497. if (!argValue)
  4498. {
  4499. failed = true;
  4500. }
  4501. else if ((wantType->IsComposite()) && (!expandedParamsArray))
  4502. {
  4503. // We need to make a temp and get the addr of that
  4504. if ((!wantsSplat) && (!argValue.IsValuelessType()) && (!argValue.IsAddr()))
  4505. {
  4506. argValue = mModule->MakeAddressable(argValue);
  4507. }
  4508. }
  4509. else if (!wantType->IsRef())
  4510. argValue = mModule->LoadValue(argValue);
  4511. }
  4512. if (expandedParamsArray)
  4513. {
  4514. if (argValue)
  4515. {
  4516. if (expandedParamAlloca)
  4517. {
  4518. argValue = mModule->LoadValue(argValue);
  4519. auto addr = mModule->mBfIRBuilder->CreateInBoundsGEP(expandedParamAlloca, extendedParamIdx);
  4520. auto storeInst = mModule->mBfIRBuilder->CreateAlignedStore(argValue.mValue, addr, argValue.mType->mAlign);
  4521. }
  4522. else
  4523. {
  4524. argValue = mModule->LoadValue(argValue);
  4525. auto firstAddr = mModule->mBfIRBuilder->CreateInBoundsGEP(expandedParamsArray.mValue, 0, 1);
  4526. auto indexedAddr = mModule->CreateIndexedValue(argValue.mType, firstAddr, extendedParamIdx);
  4527. auto storeInst = mModule->mBfIRBuilder->CreateAlignedStore(argValue.mValue, indexedAddr, argValue.mType->mAlign);
  4528. }
  4529. }
  4530. extendedParamIdx++;
  4531. }
  4532. else
  4533. {
  4534. if ((paramIdx == 0) && (methodInstance->GetParamName(paramIdx) == "this") && (wantType->IsPointer()))
  4535. {
  4536. auto underlyingType = wantType->GetUnderlyingType();
  4537. mModule->PopulateType(underlyingType, BfPopulateType_Data);
  4538. if (underlyingType->IsValuelessType())
  4539. {
  4540. // We don't actually pass a 'this' pointer for mut methods on valueless structs
  4541. argIdx++;
  4542. paramIdx++;
  4543. continue;
  4544. }
  4545. }
  4546. if (argValue)
  4547. {
  4548. if (wantsSplat)
  4549. SplatArgs(argValue, irArgs);
  4550. else
  4551. PushArg(argValue, irArgs, true, false);
  4552. }
  4553. paramIdx++;
  4554. }
  4555. argIdx++;
  4556. }
  4557. if (failed)
  4558. {
  4559. // Process the other unused arguments
  4560. while (argIdx < argValues.size())
  4561. {
  4562. mModule->AssertErrorState();
  4563. auto argValue = argValues[argIdx].mTypedValue;
  4564. if ((argValues[argIdx].mArgFlags & (BfArgFlag_DelegateBindAttempt | BfArgFlag_LambdaBindAttempt | BfArgFlag_UnqualifiedDotAttempt | BfArgFlag_DeferredEval | BfArgFlag_VariableDeclaration)) != 0)
  4565. {
  4566. if (!argValue)
  4567. {
  4568. auto expr = BfNodeDynCast<BfExpression>(argValues[argIdx].mExpression);
  4569. if (expr != NULL)
  4570. argValue = mModule->CreateValueFromExpression(expr);
  4571. }
  4572. }
  4573. argIdx++;
  4574. }
  4575. mModule->AssertErrorState();
  4576. return mModule->GetDefaultTypedValue(returnType, false, BfDefaultValueKind_Addr);
  4577. }
  4578. prevBindResult.Restore();
  4579. if (!methodDef->mIsStatic)
  4580. {
  4581. if ((methodInstance->GetOwner()->IsInterface()) && (!target.mType->IsGenericParam()) && (!target.mType->IsConcreteInterfaceType()))
  4582. {
  4583. if (methodInstance->mVirtualTableIdx == -1)
  4584. {
  4585. mModule->PopulateType(methodInstance->GetOwner(), BfPopulateType_DataAndMethods);
  4586. }
  4587. if (methodInstance->mVirtualTableIdx == -1)
  4588. {
  4589. if (methodInstance->mMethodDef->mIsConcrete)
  4590. {
  4591. 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);
  4592. }
  4593. else if (methodInstance->HasSelf())
  4594. {
  4595. 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);
  4596. }
  4597. else
  4598. {
  4599. if ((bypassVirtual) && (mModule->mCurTypeInstance->IsInterface()))
  4600. {
  4601. // Allow a base call to be defined
  4602. }
  4603. else if ((!mModule->mCurMethodInstance->mIsUnspecialized))
  4604. {
  4605. // Compiler error?
  4606. mModule->Fail(StrFormat("Unable to dynamically dispatch '%s'", mModule->MethodToString(methodInstance).c_str()), targetSrc);
  4607. }
  4608. //BF_ASSERT(mModule->mCurMethodInstance->mIsUnspecialized);
  4609. }
  4610. if (mFunctionBindResult != NULL)
  4611. {
  4612. mFunctionBindResult->mMethodInstance = methodInstance;
  4613. mFunctionBindResult->mTarget = target;
  4614. mFunctionBindResult->mFunc = moduleMethodInstance.mFunc;
  4615. for (auto arg : irArgs)
  4616. mFunctionBindResult->mIRArgs.push_back(arg);
  4617. }
  4618. return mModule->GetDefaultTypedValue(returnType);
  4619. }
  4620. }
  4621. }
  4622. else
  4623. {
  4624. //BF_ASSERT(!methodInstance->GetOwner()->IsInterface());
  4625. }
  4626. if (target.mType != NULL)
  4627. {
  4628. // When we call a method from a static ctor, that method could access static fields so we need to make sure
  4629. // the type has been initialized
  4630. auto targetTypeInst = target.mType->ToTypeInstance();
  4631. if (targetTypeInst != NULL)
  4632. mModule->CheckStaticAccess(targetTypeInst);
  4633. }
  4634. auto func = moduleMethodInstance.mFunc;
  4635. BfTypedValue result = CreateCall(methodInstance, func, bypassVirtual, irArgs);
  4636. if ((result.mType != NULL) && (result.mType->IsVar()) && (mModule->mCompiler->mIsResolveOnly))
  4637. mModule->Fail("Method return type reference failed to resolve", targetSrc);
  4638. return result;
  4639. }
  4640. BfTypedValue BfExprEvaluator::MatchConstructor(BfAstNode* targetSrc, BfMethodBoundExpression* methodBoundExpr, BfTypedValue target, BfTypeInstance* targetType, BfResolvedArgs& argValues, bool callCtorBodyOnly, bool allowAppendAlloc, BfTypedValue* appendIndexValue)
  4641. {
  4642. // Temporarily disable so we don't capture calls in params
  4643. SetAndRestoreValue<BfFunctionBindResult*> prevBindResult(mFunctionBindResult, NULL);
  4644. static int sCtorCount = 0;
  4645. sCtorCount++;
  4646. BfMethodMatcher methodMatcher(targetSrc, mModule, "", argValues.mResolvedArgs, NULL);
  4647. BfTypeVector typeGenericArguments;
  4648. auto curTypeInst = targetType;
  4649. auto curTypeDef = targetType->mTypeDef;
  4650. BfProtectionCheckFlags protectionCheckFlags = BfProtectionCheckFlag_None;
  4651. auto activeTypeDef = mModule->GetActiveTypeDef();
  4652. bool isFailurePass = false;
  4653. for (int pass = 0; pass < 2; pass++)
  4654. {
  4655. isFailurePass = pass == 1;
  4656. curTypeDef->PopulateMemberSets();
  4657. BfMethodDef* nextMethodDef = NULL;
  4658. BfMemberSetEntry* entry;
  4659. if (curTypeDef->mMethodSet.TryGetWith(String("__BfCtor"), &entry))
  4660. nextMethodDef = (BfMethodDef*)entry->mMemberDef;
  4661. while (nextMethodDef != NULL)
  4662. {
  4663. auto checkMethod = nextMethodDef;
  4664. nextMethodDef = nextMethodDef->mNextWithSameName;
  4665. if ((isFailurePass) && (checkMethod->mMethodDeclaration == NULL))
  4666. continue; // Don't match private default ctor if there's a user-defined one
  4667. if (checkMethod->mIsStatic)
  4668. continue;
  4669. if ((!curTypeInst->IsTypeMemberIncluded(checkMethod->mDeclaringType, activeTypeDef, mModule)) ||
  4670. (!curTypeInst->IsTypeMemberAccessible(checkMethod->mDeclaringType, activeTypeDef)))
  4671. continue;
  4672. auto checkProt = checkMethod->mProtection;
  4673. if (!isFailurePass)
  4674. {
  4675. if (callCtorBodyOnly)
  4676. {
  4677. // We're calling the base class's ctor from a derived class
  4678. if (checkProt == BfProtection_Private)
  4679. continue;
  4680. }
  4681. else
  4682. {
  4683. if (checkProt == BfProtection_Protected) // Treat protected constructors as private
  4684. checkProt = BfProtection_Private;
  4685. if (!mModule->CheckProtection(protectionCheckFlags, curTypeInst, checkProt, curTypeInst))
  4686. continue;
  4687. }
  4688. }
  4689. methodMatcher.CheckMethod(curTypeInst, checkMethod, isFailurePass);
  4690. }
  4691. if ((methodMatcher.mBestMethodDef != NULL) || (methodMatcher.mBackupMethodDef != NULL))
  4692. break;
  4693. }
  4694. if (methodMatcher.mBestMethodDef == NULL)
  4695. methodMatcher.mBestMethodDef = methodMatcher.mBackupMethodDef;
  4696. if (methodMatcher.mBestMethodDef == NULL)
  4697. {
  4698. mModule->Fail("No constructor available", targetSrc);
  4699. return BfTypedValue();
  4700. }
  4701. auto methodDef = methodMatcher.mBestMethodDef;
  4702. if (mModule->mCompiler->mResolvePassData != NULL)
  4703. mModule->mCompiler->mResolvePassData->HandleMethodReference(targetSrc, curTypeInst->mTypeDef, methodDef);
  4704. BfAutoComplete* autoComplete = GetAutoComplete();
  4705. if (autoComplete != NULL)
  4706. {
  4707. BfTypeInstance* resolvedTypeInstance = target.mType->ToTypeInstance();
  4708. auto ctorDecl = BfNodeDynCast<BfConstructorDeclaration>(methodDef->mMethodDeclaration);
  4709. if ((autoComplete->mIsGetDefinition) && (autoComplete->IsAutocompleteNode(targetSrc)) && (!BfNodeIsA<BfDelegateBindExpression>(targetSrc)))
  4710. {
  4711. if ((autoComplete->mDefMethod == NULL) && (autoComplete->mDefField == NULL) &&
  4712. (autoComplete->mDefProp == NULL)
  4713. && ((autoComplete->mDefType == NULL) || (autoComplete->mDefType == resolvedTypeInstance->mTypeDef)))
  4714. {
  4715. // Do we need to do this mDefType setting? If we do, then make sure we only get the element type of generics and such
  4716. //autoComplete->mDefType = resolvedTypeInstance->mTypeDef;
  4717. if (ctorDecl != NULL)
  4718. autoComplete->SetDefinitionLocation(ctorDecl->mThisToken, true);
  4719. else if (resolvedTypeInstance->mTypeDef->mTypeDeclaration != NULL)
  4720. autoComplete->SetDefinitionLocation(resolvedTypeInstance->mTypeDef->mTypeDeclaration->mNameNode, true);
  4721. }
  4722. }
  4723. }
  4724. // There should always be a constructor
  4725. BF_ASSERT(methodMatcher.mBestMethodDef != NULL);
  4726. auto moduleMethodInstance = mModule->GetMethodInstance(methodMatcher.mBestMethodTypeInstance, methodMatcher.mBestMethodDef, methodMatcher.mBestMethodGenericArguments);
  4727. BfConstructorDeclaration* ctorDecl = (BfConstructorDeclaration*)methodMatcher.mBestMethodDef->mMethodDeclaration;
  4728. if ((methodMatcher.mBestMethodDef->mHasAppend) && (targetType->IsObject()))
  4729. {
  4730. if (!allowAppendAlloc)
  4731. {
  4732. if (mModule->mCurMethodInstance->mMethodDef->mMethodDeclaration == NULL)
  4733. mModule->Fail("Constructors with append allocations cannot be called from a default constructor. Considering adding an explicit default constructor with the [AllowAppend] specifier.", targetSrc);
  4734. else
  4735. mModule->Fail("Constructors with append allocations cannot be called from a constructor without [AllowAppend] specified.", targetSrc);
  4736. }
  4737. else
  4738. {
  4739. BfResolvedArg resolvedArg;
  4740. if (appendIndexValue != NULL)
  4741. {
  4742. resolvedArg.mTypedValue = *appendIndexValue;
  4743. }
  4744. else
  4745. {
  4746. auto intPtrType = mModule->GetPrimitiveType(BfTypeCode_IntPtr);
  4747. auto intPtrRefType = mModule->CreateRefType(intPtrType);
  4748. if (target.mValue.IsFake())
  4749. {
  4750. resolvedArg.mTypedValue = BfTypedValue(mModule->mBfIRBuilder->GetFakeVal(), intPtrType);
  4751. }
  4752. else
  4753. {
  4754. // auto thisVal = target;
  4755. // BfIRValue intPtrVal = mModule->CreateAlloca(intPtrType);
  4756. // auto intPtrThisVal = mModule->mBfIRBuilder->CreatePtrToInt(thisVal.mValue, (intPtrType->mSize == 4) ? BfTypeCode_Int32 : BfTypeCode_Int64);
  4757. // auto curValPtr = mModule->mBfIRBuilder->CreateAdd(intPtrThisVal, mModule->GetConstValue(targetType->mInstSize, intPtrType));
  4758. // mModule->mBfIRBuilder->CreateStore(curValPtr, intPtrVal);
  4759. // resolvedArg.mTypedValue = BfTypedValue(intPtrVal, intPtrRefType);
  4760. BF_FATAL("Bad");
  4761. }
  4762. }
  4763. methodMatcher.mArguments.Insert(0, resolvedArg);
  4764. }
  4765. }
  4766. if (isFailurePass)
  4767. mModule->Fail(StrFormat("'%s' is inaccessible due to its protection level", mModule->MethodToString(moduleMethodInstance.mMethodInstance).c_str()), targetSrc);
  4768. prevBindResult.Restore();
  4769. return CreateCall(methodMatcher.mTargetSrc, target, BfTypedValue(), methodMatcher.mBestMethodDef, moduleMethodInstance, false, methodMatcher.mArguments);
  4770. }
  4771. static int sInvocationIdx = 0;
  4772. BfTypedValue BfExprEvaluator::ResolveArgValue(BfResolvedArg& resolvedArg, BfType* wantType, BfTypedValue* receivingValue, BfParamKind paramKind)
  4773. {
  4774. BfTypedValue argValue = resolvedArg.mTypedValue;
  4775. if ((resolvedArg.mArgFlags & (BfArgFlag_DelegateBindAttempt | BfArgFlag_LambdaBindAttempt | BfArgFlag_UnqualifiedDotAttempt | BfArgFlag_DeferredEval)) != 0)
  4776. {
  4777. if ((!argValue) || (argValue.mValue.IsFake()) || (resolvedArg.mWantsRecalc))
  4778. {
  4779. resolvedArg.mWantsRecalc = false;
  4780. auto expr = BfNodeDynCast<BfExpression>(resolvedArg.mExpression);
  4781. if (expr != NULL)
  4782. {
  4783. BfExprEvaluator exprEvaluator(mModule);
  4784. exprEvaluator.mReceivingValue = receivingValue;
  4785. BfEvalExprFlags flags = BfEvalExprFlags_NoCast;
  4786. if ((paramKind == BfParamKind_Params) || (paramKind == BfParamKind_DelegateParam))
  4787. flags = (BfEvalExprFlags)(flags | BfEvalExprFlags_AllowParamsExpr);
  4788. // if ((mModule->mCurMethodInstance->mHadGenericDelegateParams) && (!mModule->mCurMethodInstance->mIsUnspecialized))
  4789. // flags = (BfEvalExprFlags)(flags | BfEvalExprFlags_AllowParamsExpr);
  4790. argValue = mModule->CreateValueFromExpression(exprEvaluator, expr, wantType, flags);
  4791. // if ((resolvedArg.mArgFlags & BfArgFlag_ParamsExpr) != 0)
  4792. // {
  4793. // if ((mModule->mCurMethodState != NULL) && (exprEvaluator.mResultLocalVar != NULL) && (exprEvaluator.mResultLocalVarRefNode != NULL))
  4794. // {
  4795. // auto localVar = exprEvaluator.mResultLocalVar;
  4796. // int fieldIdx = mResultLocalVarField - 1;
  4797. // auto methodState = mModule->mCurMethodState->GetMethodStateForLocal(localVar);
  4798. // if (localVar->mCompositeCount >= 0)
  4799. // {
  4800. // for (int compositeIdx = 0; compositeIdx < localVar->mCompositeCount; compositeIdx++)
  4801. // {
  4802. // BfResolvedArg compositeResolvedArg;
  4803. // auto compositeLocalVar = methodState->mLocals[localVar->mLocalVarIdx + compositeIdx + 1];
  4804. // auto argValue = exprEvaluator.LoadLocal(compositeLocalVar);
  4805. // if (argValue)
  4806. // {
  4807. // if (argValue.mType->IsRef())
  4808. // argValue.mKind = BfTypedValueKind_Value;
  4809. // else if (!argValue.mType->IsStruct())
  4810. // argValue = mModule->LoadValue(argValue, NULL, exprEvaluator.mIsVolatileReference);
  4811. // }
  4812. // resolvedArg.mTypedValue = argValue;
  4813. // resolvedArg.mArgFlags = (BfArgFlags)(resolvedArg.mArgFlags | BfArgFlag_FromParamComposite);
  4814. // return resolvedArg.mTypedValue;
  4815. // }
  4816. // }
  4817. // }
  4818. // }
  4819. if ((argValue) && (argValue.mType != wantType))
  4820. {
  4821. if ((mDeferScopeAlloc != NULL) && (wantType == mModule->mContext->mBfObjectType))
  4822. {
  4823. BfAllocTarget allocTarget(mDeferScopeAlloc);
  4824. argValue = mModule->BoxValue(expr, argValue, wantType, allocTarget);
  4825. }
  4826. else
  4827. argValue = mModule->Cast(expr, argValue, wantType);
  4828. }
  4829. }
  4830. }
  4831. }
  4832. else if ((resolvedArg.mArgFlags & (BfArgFlag_DeferredValue)) != 0)
  4833. {
  4834. // We should have already had an error on the first call
  4835. SetAndRestoreValue<bool> prevIgnoreErrors(mModule->mIgnoreErrors, mModule->mHadBuildError);
  4836. auto expr = BfNodeDynCast<BfExpression>(resolvedArg.mExpression);
  4837. BF_ASSERT(expr != NULL);
  4838. argValue = mModule->CreateValueFromExpression(expr, wantType, (BfEvalExprFlags)(BfEvalExprFlags_NoCast | BfEvalExprFlags_AllowRefExpr | BfEvalExprFlags_AllowOutExpr));
  4839. if (argValue)
  4840. argValue = mModule->Cast(expr, argValue, wantType);
  4841. }
  4842. else if ((resolvedArg.mArgFlags & (BfArgFlag_UntypedDefault)) != 0)
  4843. {
  4844. argValue = mModule->GetDefaultTypedValue(wantType);
  4845. }
  4846. else if ((resolvedArg.mArgFlags & (BfArgFlag_VariableDeclaration)) != 0)
  4847. {
  4848. auto variableDeclaration = BfNodeDynCast<BfVariableDeclaration>(resolvedArg.mExpression);
  4849. auto variableType = wantType;
  4850. bool isLet = variableDeclaration->mTypeRef->IsExact<BfLetTypeReference>();
  4851. bool isVar = variableDeclaration->mTypeRef->IsExact<BfVarTypeReference>();
  4852. if ((!isLet) && (!isVar))
  4853. {
  4854. mModule->Fail("Only 'ref' or 'var' variables can be declared in method arguments", variableDeclaration);
  4855. auto autoComplete = GetAutoComplete();
  4856. if (autoComplete != NULL)
  4857. autoComplete->CheckTypeRef(variableDeclaration->mTypeRef, true, true);
  4858. }
  4859. if (wantType->IsRef())
  4860. {
  4861. auto refType = (BfRefType*)wantType;
  4862. variableType = refType->mElementType;
  4863. }
  4864. if (variableDeclaration->mInitializer != NULL)
  4865. {
  4866. mModule->Fail("Initializers cannot be used when declaring variables for 'out' parameters", variableDeclaration->mEqualsNode);
  4867. mModule->CreateValueFromExpression(variableDeclaration->mInitializer, variableType, BfEvalExprFlags_NoCast);
  4868. }
  4869. if (variableDeclaration->mNameNode == NULL)
  4870. return argValue;
  4871. BfLocalVariable* localVar = new BfLocalVariable();
  4872. localVar->mName = variableDeclaration->mNameNode->ToString();
  4873. localVar->mNameNode = BfNodeDynCast<BfIdentifierNode>(variableDeclaration->mNameNode);
  4874. localVar->mResolvedType = variableType;
  4875. if (!variableType->IsValuelessType())
  4876. localVar->mAddr = mModule->CreateAlloca(variableType);
  4877. localVar->mIsReadOnly = isLet;
  4878. localVar->mReadFromId = 0;
  4879. localVar->mWrittenToId = 0;
  4880. localVar->mIsAssigned = true;
  4881. mModule->CheckVariableDef(localVar);
  4882. localVar->Init();
  4883. mModule->AddLocalVariableDef(localVar, true);
  4884. CheckVariableDeclaration(resolvedArg.mExpression, false, false, false);
  4885. argValue = BfTypedValue(localVar->mAddr, mModule->CreateRefType(variableType, BfRefType::RefKind_Out));
  4886. //argValue = mModule->GetDefaultTypedValue(wantType);
  4887. }
  4888. return argValue;
  4889. }
  4890. BfTypedValue BfExprEvaluator::CheckEnumCreation(BfAstNode* targetSrc, BfTypeInstance* enumType, const StringImpl& caseName, BfResolvedArgs& argValues)
  4891. {
  4892. auto activeTypeDef = mModule->GetActiveTypeDef();
  4893. mModule->mBfIRBuilder->PopulateType(enumType);
  4894. auto resolvePassData = mModule->mCompiler->mResolvePassData;
  4895. // if (resolvePassData != NULL)
  4896. // {
  4897. // if (mModule->mParentNodeEntry != NULL)
  4898. // {
  4899. // if (auto invocationExpr = BfNodeDynCast<BfInvocationExpression>(mModule->mParentNodeEntry->mNode))
  4900. // {
  4901. // if (auto memberRefExpr = BfNodeDynCast<BfMemberReferenceExpression>(invocationExpr->mTarget))
  4902. // {
  4903. // BfAstNode* dotNode = memberRefExpr->mDotToken;
  4904. // BfAstNode* nameNode = targetSrc;
  4905. // String filter;
  4906. // auto autoComplete = resolvePassData->mAutoComplete;
  4907. // if ((autoComplete != NULL) && (autoComplete->InitAutocomplete(dotNode, nameNode, filter)))
  4908. // autoComplete->AddEnumTypeMembers(enumType, caseName, false, enumType == mModule->mCurTypeInstance);
  4909. // }
  4910. // }
  4911. // }
  4912. // }
  4913. for (int fieldIdx = 0; fieldIdx < (int)enumType->mFieldInstances.size(); fieldIdx++)
  4914. {
  4915. auto fieldInstance = &enumType->mFieldInstances[fieldIdx];
  4916. auto fieldDef = fieldInstance->GetFieldDef();
  4917. if (fieldDef == NULL)
  4918. continue;
  4919. if ((fieldInstance->mIsEnumPayloadCase) && (fieldDef->mName == caseName))
  4920. {
  4921. if ((!enumType->IsTypeMemberIncluded(fieldDef->mDeclaringType, activeTypeDef, mModule)) ||
  4922. (!enumType->IsTypeMemberAccessible(fieldDef->mDeclaringType, activeTypeDef)))
  4923. continue;
  4924. auto autoComplete = GetAutoComplete();
  4925. if ((autoComplete != NULL) && (autoComplete->mIsCapturingMethodMatchInfo))
  4926. {
  4927. BfAutoComplete::MethodMatchEntry methodMatchEntry;
  4928. methodMatchEntry.mPayloadEnumField = fieldInstance;
  4929. methodMatchEntry.mTypeInstance = enumType;
  4930. methodMatchEntry.mCurMethodInstance = mModule->mCurMethodInstance;
  4931. autoComplete->mMethodMatchInfo->mInstanceList.push_back(methodMatchEntry);
  4932. }
  4933. if (resolvePassData != NULL)
  4934. {
  4935. BfAstNode* nameNode = targetSrc;
  4936. if (resolvePassData->mGetSymbolReferenceKind == BfGetSymbolReferenceKind_Field)
  4937. resolvePassData->HandleFieldReference(nameNode, enumType->mTypeDef, fieldDef);
  4938. }
  4939. BfIRValue enumValue;
  4940. BfTypedValue result;
  4941. if ((mReceivingValue != NULL) && (mReceivingValue->mType == enumType) && (mReceivingValue->IsAddr()))
  4942. {
  4943. result = *mReceivingValue;
  4944. mReceivingValue = NULL;
  4945. enumValue = result.mValue;
  4946. }
  4947. else
  4948. {
  4949. mResultIsTempComposite = true;
  4950. enumValue = mModule->CreateAlloca(enumType);
  4951. result = BfTypedValue(enumValue, fieldInstance->mOwner, BfTypedValueKind_TempAddr);
  4952. }
  4953. BF_ASSERT(fieldInstance->mResolvedType->IsTuple());
  4954. auto tupleType = (BfTupleType*)fieldInstance->mResolvedType;
  4955. mModule->mBfIRBuilder->PopulateType(tupleType);
  4956. BfIRValue fieldPtr;
  4957. BfIRValue tuplePtr;
  4958. if (!tupleType->IsValuelessType())
  4959. {
  4960. fieldPtr = mModule->mBfIRBuilder->CreateInBoundsGEP(enumValue, 0, 1);
  4961. auto tuplePtrType = mModule->CreatePointerType(tupleType);
  4962. auto mappedPtrType = mModule->mBfIRBuilder->MapType(tuplePtrType);
  4963. tuplePtr = mModule->mBfIRBuilder->CreateBitCast(fieldPtr, mappedPtrType);
  4964. }
  4965. for (int tupleFieldIdx = 0; tupleFieldIdx < (int)tupleType->mFieldInstances.size(); tupleFieldIdx++)
  4966. {
  4967. auto tupleFieldInstance = &tupleType->mFieldInstances[tupleFieldIdx];
  4968. auto resolvedFieldType = tupleFieldInstance->GetResolvedType();
  4969. if (tupleFieldIdx >= argValues.mResolvedArgs.size())
  4970. {
  4971. BfAstNode* refNode = targetSrc;
  4972. BfAstNode* prevNode = NULL;
  4973. if (mModule->mParentNodeEntry != NULL)
  4974. {
  4975. if (auto invokeExpr = BfNodeDynCast<BfInvocationExpression>(mModule->mParentNodeEntry->mNode))
  4976. {
  4977. if (invokeExpr->mCloseParen != NULL)
  4978. refNode = invokeExpr->mCloseParen;
  4979. }
  4980. }
  4981. BfError* error = mModule->Fail(StrFormat("Not enough parameters specified, expected %d more.", tupleType->mFieldInstances.size() - (int)argValues.mArguments->size()), refNode);
  4982. if (error != NULL)
  4983. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("See enum declaration"), fieldDef->mFieldDeclaration);
  4984. break;
  4985. }
  4986. BfTypedValue receivingValue;
  4987. BfIRValue tupleFieldPtr;
  4988. if (tuplePtr)
  4989. {
  4990. tupleFieldPtr = mModule->mBfIRBuilder->CreateInBoundsGEP(tuplePtr, 0, tupleFieldInstance->mDataIdx);
  4991. receivingValue = BfTypedValue(tupleFieldPtr, tupleFieldInstance->mResolvedType, true);
  4992. }
  4993. auto argValue = ResolveArgValue(argValues.mResolvedArgs[tupleFieldIdx], resolvedFieldType, &receivingValue);
  4994. // Used receiving value?
  4995. if (argValue.mValue == receivingValue.mValue)
  4996. continue;
  4997. if ((!argValue) || (argValue.IsValuelessType()))
  4998. continue;
  4999. argValue = mModule->AggregateSplat(argValue);
  5000. argValues.mResolvedArgs[tupleFieldIdx].mExpectedType = resolvedFieldType;
  5001. if ((argValues.mResolvedArgs[tupleFieldIdx].mArgFlags & (BfArgFlag_DelegateBindAttempt | BfArgFlag_LambdaBindAttempt | BfArgFlag_UnqualifiedDotAttempt)) != 0)
  5002. {
  5003. auto expr = BfNodeDynCast<BfExpression>(argValues.mResolvedArgs[tupleFieldIdx].mExpression);
  5004. BF_ASSERT(expr != NULL);
  5005. argValue = mModule->CreateValueFromExpression(expr, resolvedFieldType);
  5006. }
  5007. if (argValue)
  5008. {
  5009. // argValue can have a value even if tuplePtr does not have a value. This can happen if we are assigning to a (void) tuple,
  5010. // but we have a value that needs to be attempted to be casted to void
  5011. argValue = mModule->Cast(argValues.mResolvedArgs[tupleFieldIdx].mExpression, argValue, resolvedFieldType);
  5012. if (tupleFieldPtr)
  5013. {
  5014. argValue = mModule->LoadValue(argValue);
  5015. if (argValue)
  5016. mModule->mBfIRBuilder->CreateAlignedStore(argValue.mValue, tupleFieldPtr, resolvedFieldType->mAlign);
  5017. }
  5018. }
  5019. }
  5020. if ((intptr)argValues.mResolvedArgs.size() > tupleType->mFieldInstances.size())
  5021. {
  5022. BfAstNode* errorRef = argValues.mResolvedArgs[tupleType->mFieldInstances.size()].mExpression;
  5023. if (errorRef == NULL)
  5024. errorRef = targetSrc;
  5025. BfError* error = mModule->Fail(StrFormat("Too many arguments, expected %d fewer.", argValues.mResolvedArgs.size() - tupleType->mFieldInstances.size()), errorRef);
  5026. if (error != NULL)
  5027. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("See enum declaration"), fieldDef->mFieldDeclaration);
  5028. }
  5029. //auto fieldPtr = mModule->mBfIRBuilder->CreateInBoundsGEP(enumValue, 0, 2);
  5030. auto dscrType = enumType->GetDiscriminatorType();
  5031. auto dscrField = &enumType->mFieldInstances.back();
  5032. int tagIdx = -fieldInstance->mDataIdx - 1;
  5033. auto dscFieldPtr = mModule->mBfIRBuilder->CreateInBoundsGEP(enumValue, 0, dscrField->mDataIdx);
  5034. mModule->mBfIRBuilder->CreateAlignedStore(mModule->mBfIRBuilder->CreateConst(dscrType->mTypeDef->mTypeCode, tagIdx), dscFieldPtr, 4);
  5035. return result;
  5036. }
  5037. }
  5038. return BfTypedValue();
  5039. }
  5040. BfTypedValue BfExprEvaluator::MatchMethod(BfAstNode* targetSrc, BfMethodBoundExpression* methodBoundExpr, BfTypedValue target, bool allowImplicitThis, bool bypassVirtual, const StringImpl& methodName,
  5041. BfResolvedArgs& argValues, BfSizedArray<ASTREF(BfTypeReference*)>* methodGenericArguments, BfCheckedKind checkedKind)
  5042. {
  5043. BP_ZONE("MatchMethod");
  5044. if (bypassVirtual)
  5045. {
  5046. // "bypassVirtual" means that we know for sure that the target is EXACTLY the specified target type,
  5047. // not derived from (or implementing) the target type. This cannot apply to interfaces.
  5048. BF_ASSERT(!target.mType->IsInterface());
  5049. }
  5050. auto origTarget = target;
  5051. if (mFunctionBindResult != NULL)
  5052. {
  5053. BF_ASSERT(!mFunctionBindResult->mOrigTarget);
  5054. mFunctionBindResult->mOrigTarget = origTarget;
  5055. }
  5056. if (target)
  5057. {
  5058. if ((!target.mType->IsGenericParam()) && (!target.IsSplat()) && (!target.mType->IsVar()))
  5059. target = MakeCallableTarget(targetSrc, target);
  5060. }
  5061. // static int sCallIdx = 0;
  5062. // if (!mModule->mCompiler->mIsResolveOnly)
  5063. // sCallIdx++;
  5064. // int callIdx = sCallIdx;
  5065. // if (callIdx == 118)
  5066. // {
  5067. // NOP;
  5068. // }
  5069. // Temporarily disable so we don't capture calls in params
  5070. SetAndRestoreValue<BfFunctionBindResult*> prevBindResult(mFunctionBindResult, NULL);
  5071. sInvocationIdx++;
  5072. bool wantCtor = methodName.IsEmpty();
  5073. BfAutoComplete::MethodMatchInfo* restoreCapturingMethodMatchInfo = NULL;
  5074. auto autoComplete = GetAutoComplete();
  5075. if ((autoComplete != NULL) && (autoComplete->mIsCapturingMethodMatchInfo))
  5076. {
  5077. if ((!targetSrc->IsFromParser(mModule->mCompiler->mResolvePassData->mParser)) ||
  5078. ((autoComplete->mMethodMatchInfo->mInvocationSrcIdx != -1) && (autoComplete->mMethodMatchInfo->mInvocationSrcIdx != targetSrc->GetSrcStart())))
  5079. {
  5080. autoComplete->mIsCapturingMethodMatchInfo = false;
  5081. restoreCapturingMethodMatchInfo = autoComplete->mMethodMatchInfo;
  5082. }
  5083. }
  5084. defer(
  5085. {
  5086. if ((restoreCapturingMethodMatchInfo != NULL) && (autoComplete->mMethodMatchInfo == restoreCapturingMethodMatchInfo))
  5087. autoComplete->mIsCapturingMethodMatchInfo = true;
  5088. });
  5089. /*if ((autoComplete != NULL) && (autoComplete->mIsCapturingMethodMatchInfo) && (autoComplete->mMethodMatchInfo->mInstanceList.size() != 0))
  5090. autoComplete->mIsCapturingMethodMatchInfo = false;*/
  5091. bool isUnboundCall = false;
  5092. if (target.mType != NULL)
  5093. {
  5094. if (target.mType->IsGenericParam())
  5095. {
  5096. auto genericParamTarget = (BfGenericParamType*) target.mType;
  5097. auto genericParamInstance = mModule->GetGenericParamInstance(genericParamTarget);
  5098. isUnboundCall = (genericParamInstance->mGenericParamFlags & BfGenericParamFlag_Var) != 0;
  5099. if (isUnboundCall)
  5100. {
  5101. if (mModule->mCurMethodInstance->mIsUnspecialized)
  5102. {
  5103. auto varType = mModule->GetPrimitiveType(BfTypeCode_Var);
  5104. target.mType = varType;
  5105. }
  5106. }
  5107. }
  5108. else if (target.mType->IsVar())
  5109. isUnboundCall = true;
  5110. }
  5111. /*if (mPrefixedAttributeState != NULL)
  5112. {
  5113. auto customAttr = mPrefixedAttributeState->mCustomAttributes->Get(mModule->mCompiler->mUnboundAttributeTypeDef);
  5114. if (customAttr != NULL)
  5115. {
  5116. if (!mModule->IsInGeneric())
  5117. {
  5118. mModule->Fail("'Unbound' can only be used within generics");
  5119. }
  5120. mPrefixedAttributeState->mUsed = true;
  5121. isUnboundCall = true;
  5122. }
  5123. }*/
  5124. if ((mModule->mAttributeState != NULL) && (mModule->mAttributeState->mCustomAttributes != NULL))
  5125. {
  5126. auto customAttr = mModule->mAttributeState->mCustomAttributes->Get(mModule->mCompiler->mUnboundAttributeTypeDef);
  5127. if (customAttr != NULL)
  5128. {
  5129. if (!mModule->IsInGeneric())
  5130. {
  5131. mModule->Fail("'Unbound' can only be used within generics");
  5132. }
  5133. mModule->mAttributeState->mUsed = true;
  5134. isUnboundCall = true;
  5135. }
  5136. }
  5137. if (isUnboundCall)
  5138. {
  5139. if (mModule->mCurMethodInstance->mIsUnspecialized)
  5140. {
  5141. auto varType = mModule->GetPrimitiveType(BfTypeCode_Var);
  5142. for (int argIdx = 0; argIdx < (int)argValues.mResolvedArgs.size(); argIdx++)
  5143. {
  5144. if ((argValues.mResolvedArgs[argIdx].mArgFlags & BfArgFlag_DeferredEval) != 0)
  5145. {
  5146. mModule->CreateValueFromExpression((*argValues.mArguments)[argIdx], varType);
  5147. }
  5148. }
  5149. return BfTypedValue(mModule->GetDefaultValue(varType), varType);
  5150. }
  5151. }
  5152. SetAndRestoreValue<bool> prevNoBind(mNoBind, mNoBind || isUnboundCall);
  5153. auto targetType = target.mType;
  5154. BfTypeDef* curTypeDef = NULL;
  5155. BfTypeInstance* targetTypeInst = NULL;
  5156. bool checkNonStatic = true;
  5157. if (target)
  5158. {
  5159. if (targetType->IsVar())
  5160. return mModule->GetDefaultTypedValue(targetType);
  5161. targetTypeInst = targetType->ToTypeInstance();
  5162. if (targetTypeInst != NULL)
  5163. curTypeDef = targetTypeInst->mTypeDef;
  5164. }
  5165. else if (targetType != NULL) // Static targeted
  5166. {
  5167. if (targetType->IsWrappableType())
  5168. {
  5169. targetTypeInst = mModule->GetWrappedStructType(targetType);
  5170. }
  5171. else if (targetType->IsGenericParam())
  5172. {
  5173. auto genericParamInstance = mModule->GetGenericParamInstance((BfGenericParamType*)targetType);
  5174. if (genericParamInstance->mTypeConstraint != NULL)
  5175. targetTypeInst = genericParamInstance->mTypeConstraint->ToTypeInstance();
  5176. if (genericParamInstance->mGenericParamFlags & BfGenericParamFlag_Var)
  5177. {
  5178. auto varType = mModule->GetPrimitiveType(BfTypeCode_Var);
  5179. return BfTypedValue(mModule->GetDefaultValue(varType), varType);
  5180. }
  5181. }
  5182. else
  5183. targetTypeInst = targetType->ToTypeInstance();
  5184. if (targetTypeInst == NULL)
  5185. {
  5186. //mModule->Fail("No static methods available", targetSrc);
  5187. //return BfTypedValue();
  5188. }
  5189. else
  5190. {
  5191. curTypeDef = targetTypeInst->mTypeDef;
  5192. checkNonStatic = false;
  5193. }
  5194. }
  5195. else // Current scopeData
  5196. {
  5197. if ((mModule->mCurMethodInstance != NULL) && (mModule->mCurMethodInstance->mIsForeignMethodDef) && (mModule->mCurMethodInstance->mMethodInfoEx->mForeignType->IsInterface()))
  5198. {
  5199. targetTypeInst = mModule->mCurMethodInstance->mMethodInfoEx->mForeignType;
  5200. curTypeDef = targetTypeInst->mTypeDef;
  5201. checkNonStatic = true;
  5202. target = mModule->GetThis();
  5203. //target.mType = targetTypeInst;
  5204. }
  5205. else
  5206. {
  5207. curTypeDef = mModule->mCurTypeInstance->mTypeDef;
  5208. targetTypeInst = mModule->mCurTypeInstance;
  5209. if (mModule->mCurMethodState == NULL)
  5210. {
  5211. checkNonStatic = false;
  5212. }
  5213. else if (mModule->mCurMethodState->mTempKind != BfMethodState::TempKind_None)
  5214. {
  5215. checkNonStatic = mModule->mCurMethodState->mTempKind == BfMethodState::TempKind_NonStatic;
  5216. }
  5217. else
  5218. checkNonStatic = !mModule->mCurMethodInstance->mMethodDef->mIsStatic;
  5219. }
  5220. }
  5221. bool isIndirectMethodCall = false;
  5222. BfType* lookupType = targetType;
  5223. BfTypeInstance* lookupTypeInst = targetTypeInst;
  5224. if (targetType != NULL)
  5225. {
  5226. lookupType = BindGenericType(targetSrc, targetType);
  5227. if (lookupType->IsGenericParam())
  5228. lookupTypeInst = NULL;
  5229. }
  5230. BfMethodDef* methodDef = NULL;
  5231. BfTypeVector checkMethodGenericArguments;
  5232. BfTypeInstance* curTypeInst = targetTypeInst;
  5233. BfMethodMatcher methodMatcher(targetSrc, mModule, methodName, argValues.mResolvedArgs, methodGenericArguments);
  5234. methodMatcher.mCheckedKind = checkedKind;
  5235. methodMatcher.mAllowImplicitThis = allowImplicitThis;
  5236. methodMatcher.mAllowStatic = !target.mValue;
  5237. methodMatcher.mAllowNonStatic = !methodMatcher.mAllowStatic;
  5238. if (allowImplicitThis)
  5239. {
  5240. if (mModule->mCurMethodState == NULL)
  5241. {
  5242. methodMatcher.mAllowStatic = true;
  5243. methodMatcher.mAllowNonStatic = false;
  5244. }
  5245. else if (mModule->mCurMethodState->mTempKind != BfMethodState::TempKind_None)
  5246. {
  5247. methodMatcher.mAllowNonStatic = mModule->mCurMethodState->mTempKind == BfMethodState::TempKind_NonStatic;
  5248. methodMatcher.mAllowStatic = true;
  5249. }
  5250. else
  5251. {
  5252. if (!mModule->mCurMethodInstance->mMethodDef->mIsStatic)
  5253. methodMatcher.mAllowNonStatic = true;
  5254. methodMatcher.mAllowStatic = true;
  5255. if (mModule->mCurMethodInstance->mMethodDef->mIsLocalMethod)
  5256. {
  5257. auto rootMethodState = mModule->mCurMethodState->GetRootMethodState();
  5258. methodMatcher.mAllowNonStatic = !rootMethodState->mMethodInstance->mMethodDef->mIsStatic;
  5259. }
  5260. }
  5261. }
  5262. if (methodName == BF_METHODNAME_CALCAPPEND)
  5263. methodMatcher.mMethodType = BfMethodType_CtorCalcAppend;
  5264. BF_ASSERT(methodMatcher.mBestMethodDef == NULL);
  5265. BfLocalMethod* matchedLocalMethod = NULL;
  5266. if (target.mType == NULL)
  5267. {
  5268. CheckLocalMethods(targetSrc, curTypeInst, methodName, methodMatcher, BfMethodType_Normal);
  5269. if (methodMatcher.mBestMethodDef == NULL)
  5270. methodMatcher.mBestMethodDef = methodMatcher.mBackupMethodDef;
  5271. if (methodMatcher.mBestMethodDef != NULL)
  5272. {
  5273. auto rootMethodState = mModule->mCurMethodState->GetRootMethodState();
  5274. auto methodDef = methodMatcher.mBestMethodDef;
  5275. if (mModule->mCompiler->mResolvePassData != NULL)
  5276. {
  5277. auto identifierNode = BfNodeDynCast<BfIdentifierNode>(targetSrc);
  5278. mModule->mCompiler->mResolvePassData->HandleLocalReference(identifierNode, curTypeInst->mTypeDef, rootMethodState->mMethodInstance->mMethodDef, ~methodDef->mIdx);
  5279. auto autoComplete = GetAutoComplete();
  5280. if ((autoComplete != NULL) && (autoComplete->IsAutocompleteNode(identifierNode)))
  5281. {
  5282. autoComplete->SetDefinitionLocation(methodDef->GetRefNode());
  5283. if (autoComplete->mDefType == NULL)
  5284. {
  5285. autoComplete->mDefMethod = mModule->mCurMethodState->GetRootMethodState()->mMethodInstance->mMethodDef;
  5286. autoComplete->mDefType = curTypeDef;
  5287. autoComplete->mReplaceLocalId = ~methodDef->mIdx;
  5288. }
  5289. }
  5290. if ((autoComplete != NULL) && (autoComplete->mIsCapturingMethodMatchInfo))
  5291. {
  5292. BfAutoComplete::MethodMatchEntry methodMatchEntry;
  5293. methodMatchEntry.mMethodDef = methodDef;
  5294. methodMatchEntry.mTypeInstance = mModule->mCurTypeInstance;
  5295. methodMatchEntry.mCurMethodInstance = mModule->mCurMethodInstance;
  5296. autoComplete->mMethodMatchInfo->mInstanceList.push_back(methodMatchEntry);
  5297. }
  5298. }
  5299. if ((mModule->mCurMethodState->mClosureState != NULL) && (mModule->mCurMethodState->mClosureState->mCapturing))
  5300. {
  5301. auto methodInstance = mModule->GetRawMethodInstance(methodMatcher.mBestMethodTypeInstance, methodMatcher.mBestMethodDef);
  5302. if (methodInstance->mReturnType == NULL)
  5303. {
  5304. FinishDeferredEvals(argValues.mResolvedArgs);
  5305. // If we are recursive then we won't even have a completed methodInstance yet to look at
  5306. return mModule->GetDefaultTypedValue(mModule->mContext->mBfObjectType);
  5307. }
  5308. }
  5309. }
  5310. }
  5311. if (methodMatcher.mBestMethodDef == NULL)
  5312. {
  5313. if (lookupTypeInst == NULL)
  5314. {
  5315. if ((lookupType != NULL) && (lookupType->IsConcreteInterfaceType()))
  5316. {
  5317. auto concreteInterfaceType = (BfConcreteInterfaceType*)lookupType;
  5318. lookupTypeInst = concreteInterfaceType->mInterface;
  5319. }
  5320. else if (isUnboundCall)
  5321. {
  5322. //auto resolvedType = mModule->ResolveGenericType(lookupType);
  5323. }
  5324. else if (lookupType->IsGenericParam())
  5325. {
  5326. auto genericParamTarget = (BfGenericParamType*)lookupType;
  5327. auto _HandleGenericParamInstance = [&](BfGenericParamInstance* genericParamInstance)
  5328. {
  5329. if (genericParamInstance->mTypeConstraint != NULL)
  5330. lookupTypeInst = genericParamInstance->mTypeConstraint->ToTypeInstance();
  5331. else
  5332. lookupTypeInst = mModule->mContext->mBfObjectType;
  5333. for (BfType* ifaceInst : genericParamInstance->mInterfaceConstraints)
  5334. {
  5335. if (ifaceInst->IsUnspecializedType())
  5336. ifaceInst = mModule->ResolveType(ifaceInst);
  5337. BfTypeInstance* typeInst = ifaceInst->ToTypeInstance();
  5338. BF_ASSERT(typeInst != NULL);
  5339. if (methodMatcher.CheckType(typeInst, target, false))
  5340. methodMatcher.mSelfType = lookupType;
  5341. }
  5342. };
  5343. auto genericParamInstance = mModule->GetGenericParamInstance(genericParamTarget);
  5344. _HandleGenericParamInstance(genericParamInstance);
  5345. // Check method generic constraints
  5346. if ((mModule->mCurMethodInstance != NULL) && (mModule->mCurMethodInstance->mIsUnspecialized) && (mModule->mCurMethodInstance->mMethodInfoEx != NULL))
  5347. {
  5348. for (int genericParamIdx = (int)mModule->mCurMethodInstance->mMethodInfoEx->mMethodGenericArguments.size();
  5349. genericParamIdx < mModule->mCurMethodInstance->mMethodInfoEx->mGenericParams.size(); genericParamIdx++)
  5350. {
  5351. auto genericParam = mModule->mCurMethodInstance->mMethodInfoEx->mGenericParams[genericParamIdx];
  5352. if (genericParam->mExternType == lookupType)
  5353. _HandleGenericParamInstance(genericParam);
  5354. }
  5355. }
  5356. }
  5357. }
  5358. if ((lookupTypeInst != NULL) && (!wantCtor))
  5359. {
  5360. methodMatcher.mBypassVirtual = bypassVirtual;
  5361. methodMatcher.CheckType(lookupTypeInst, target, false);
  5362. }
  5363. if ((lookupType != NULL) && (lookupType->IsGenericParam()))
  5364. {
  5365. //lookupType = mModule->ResolveGenericType(lookupType);
  5366. if (!lookupType->IsGenericParam())
  5367. {
  5368. target = MakeCallableTarget(targetSrc, target);
  5369. if (target)
  5370. {
  5371. lookupTypeInst = lookupType->ToTypeInstance();
  5372. }
  5373. }
  5374. }
  5375. }
  5376. bool isFailurePass = false;
  5377. if (methodMatcher.mBestMethodDef == NULL)
  5378. {
  5379. isFailurePass = true;
  5380. if (lookupTypeInst != NULL)
  5381. methodMatcher.CheckType(lookupTypeInst, target, true);
  5382. }
  5383. BfTypedValue staticResult;
  5384. methodMatcher.TryDevirtualizeCall(target, &origTarget, &staticResult);
  5385. if (staticResult)
  5386. return staticResult;
  5387. bypassVirtual |= methodMatcher.mBypassVirtual;
  5388. if (methodMatcher.mBestMethodDef != NULL)
  5389. {
  5390. curTypeInst = methodMatcher.mBestMethodTypeInstance;
  5391. methodDef = methodMatcher.mBestMethodDef;
  5392. }
  5393. if ((methodDef) && (!methodDef->mIsStatic) && (!target) && (allowImplicitThis))
  5394. {
  5395. target = mModule->GetThis();
  5396. }
  5397. // If we call "GetType" on a value type, statically determine the type rather than boxing and then dispatching
  5398. if ((methodDef) && (target) && (curTypeInst == mModule->mContext->mBfObjectType) &&
  5399. (methodDef->mName == "GetType") && (target.mType->IsValueType()))
  5400. {
  5401. BfType* targetType = target.mType;
  5402. if (origTarget)
  5403. targetType = origTarget.mType;
  5404. auto typeType = mModule->ResolveTypeDef(mModule->mCompiler->mTypeTypeDef);
  5405. mModule->AddDependency(targetType, mModule->mCurTypeInstance, BfDependencyMap::DependencyFlag_ExprTypeReference);
  5406. return BfTypedValue(mModule->CreateTypeDataRef(targetType), typeType);
  5407. }
  5408. bool skipThis = false;
  5409. // Fail, check for delegate field invocation
  5410. if ((methodDef == NULL) && ((methodGenericArguments == NULL) || (methodGenericArguments->size() == 0)))
  5411. {
  5412. // Check for payload enum initialization first
  5413. BfTypedValue enumResult;
  5414. BfTypeInstance* enumType = NULL;
  5415. if ((!target) && (mModule->mCurTypeInstance->IsPayloadEnum()))
  5416. {
  5417. enumType = mModule->mCurTypeInstance;
  5418. //enumResult = CheckEnumCreation(targetSrc, mModule->mCurTypeInstance, methodName, argValues);
  5419. }
  5420. else if ((!target) && (target.HasType()) && (targetType->IsPayloadEnum()))
  5421. {
  5422. enumType = targetType->ToTypeInstance();
  5423. //enumResult = CheckEnumCreation(targetSrc, enumType, methodName, argValues);
  5424. }
  5425. if (enumType != NULL)
  5426. {
  5427. enumResult = CheckEnumCreation(targetSrc, enumType, methodName, argValues);
  5428. }
  5429. if (enumResult)
  5430. {
  5431. if ((mModule->mCompiler->mResolvePassData != NULL) &&
  5432. (targetSrc->IsFromParser(mModule->mCompiler->mResolvePassData->mParser)) &&
  5433. (mModule->mCompiler->mResolvePassData->mSourceClassifier != NULL))
  5434. {
  5435. mModule->mCompiler->mResolvePassData->mSourceClassifier->SetElementType(targetSrc, BfSourceElementType_Normal);
  5436. }
  5437. return enumResult;
  5438. }
  5439. BfTypedValue fieldVal;
  5440. if (allowImplicitThis)
  5441. {
  5442. auto identifierNode = BfNodeDynCast<BfIdentifierNode>(targetSrc);
  5443. if (identifierNode != NULL)
  5444. fieldVal = LookupIdentifier(identifierNode);
  5445. }
  5446. else
  5447. {
  5448. fieldVal = LookupField(targetSrc, target, methodName);
  5449. }
  5450. if (mPropDef != NULL)
  5451. fieldVal = GetResult();
  5452. if (fieldVal)
  5453. {
  5454. if (fieldVal.mType->IsGenericParam())
  5455. {
  5456. bool delegateFailed = true;
  5457. auto genericParamInstance = mModule->GetGenericParamInstance((BfGenericParamType*)fieldVal.mType);
  5458. BfTypeInstance* typeInstConstraint = NULL;
  5459. if (genericParamInstance->mTypeConstraint != NULL)
  5460. typeInstConstraint = genericParamInstance->mTypeConstraint->ToTypeInstance();
  5461. if ((typeInstConstraint != NULL) &&
  5462. ((typeInstConstraint->mTypeDef == mModule->mCompiler->mDelegateTypeDef) || (typeInstConstraint->mTypeDef == mModule->mCompiler->mFunctionTypeDef)))
  5463. {
  5464. MarkResultUsed();
  5465. // if (argValues.mResolvedArgs.size() > 0)
  5466. // {
  5467. // if ((argValues.mResolvedArgs[0].mArgFlags & BfArgFlag_FromParamComposite) != 0)
  5468. // delegateFailed = false;
  5469. // }
  5470. // else
  5471. if (argValues.mArguments->size() == 1)
  5472. {
  5473. BfExprEvaluator exprEvaluator(mModule);
  5474. exprEvaluator.mBfEvalExprFlags = BfEvalExprFlags_AllowParamsExpr;
  5475. exprEvaluator.Evaluate((*argValues.mArguments)[0]);
  5476. if ((mModule->mCurMethodState != NULL) && (exprEvaluator.mResultLocalVar != NULL) && (exprEvaluator.mResultLocalVarRefNode != NULL))
  5477. {
  5478. /*if (exprEvaluator.mResult.mKind != BfTypedValueKind_Params)
  5479. mModule->Warn(0, "'params' token expected", (*argValues.mArguments)[0]);*/
  5480. auto localVar = exprEvaluator.mResultLocalVar;
  5481. if ((localVar->mCompositeCount >= 0) && (localVar->mResolvedType == fieldVal.mType))
  5482. {
  5483. delegateFailed = false;
  5484. if (mModule->mCurMethodInstance->mIsUnspecialized)
  5485. {
  5486. auto retTypeType = mModule->CreateRetTypeType(fieldVal.mType);
  5487. return mModule->GetFakeTypedValue(retTypeType);
  5488. }
  5489. }
  5490. }
  5491. }
  5492. if (delegateFailed)
  5493. {
  5494. mModule->Fail(StrFormat("Generic delegates can only be invoked with 'params %s' composite parameters", mModule->TypeToString(fieldVal.mType).c_str()), targetSrc);
  5495. return BfTypedValue();
  5496. }
  5497. }
  5498. }
  5499. if (fieldVal.mType->IsTypeInstance())
  5500. {
  5501. prevBindResult.Restore();
  5502. auto fieldTypeInst = fieldVal.mType->ToTypeInstance();
  5503. MarkResultUsed();
  5504. return MatchMethod(targetSrc, NULL, fieldVal, false, false, "Invoke", argValues, methodGenericArguments, checkedKind);
  5505. }
  5506. if (fieldVal.mType->IsVar())
  5507. return BfTypedValue(mModule->GetDefaultValue(fieldVal.mType), fieldVal.mType);
  5508. if (fieldVal.mType->IsGenericParam())
  5509. {
  5510. auto genericParam = mModule->GetGenericParamInstance((BfGenericParamType*)fieldVal.mType);
  5511. if ((genericParam->mTypeConstraint != NULL) &&
  5512. ((genericParam->mTypeConstraint->IsDelegate()) || (genericParam->mTypeConstraint->IsFunction())))
  5513. {
  5514. BfMethodInstance* invokeMethodInstance = mModule->GetRawMethodInstanceAtIdx(genericParam->mTypeConstraint->ToTypeInstance(), 0, "Invoke");
  5515. methodDef = invokeMethodInstance->mMethodDef;
  5516. methodMatcher.mBestMethodInstance = invokeMethodInstance;
  5517. methodMatcher.mBestMethodTypeInstance = invokeMethodInstance->GetOwner();
  5518. methodMatcher.mBestMethodDef = invokeMethodInstance->mMethodDef;
  5519. target = mModule->GetDefaultTypedValue(methodMatcher.mBestMethodTypeInstance);
  5520. isFailurePass = false;
  5521. isIndirectMethodCall = true;
  5522. }
  5523. }
  5524. else if (fieldVal.mType->IsMethodRef())
  5525. {
  5526. auto functionBindResults = prevBindResult.mPrevVal;
  5527. if (functionBindResults != NULL)
  5528. {
  5529. functionBindResults->mOrigTarget = fieldVal;
  5530. }
  5531. origTarget = fieldVal;
  5532. auto methodRefType = (BfMethodRefType*)fieldVal.mType;
  5533. BfMethodInstance* methodInstance = methodRefType->mMethodRef;
  5534. methodDef = methodInstance->mMethodDef;
  5535. if (methodDef->mIsLocalMethod)
  5536. {
  5537. methodMatcher.mBestMethodInstance = mModule->ReferenceExternalMethodInstance(methodInstance);
  5538. }
  5539. else
  5540. {
  5541. BfTypeVector methodGenericArguments;
  5542. if (methodInstance->mMethodInfoEx != NULL)
  5543. methodGenericArguments = methodInstance->mMethodInfoEx->mMethodGenericArguments;
  5544. methodMatcher.mBestMethodInstance = mModule->GetMethodInstance(methodInstance->GetOwner(), methodInstance->mMethodDef, methodGenericArguments);
  5545. }
  5546. methodMatcher.mBestMethodTypeInstance = methodInstance->GetOwner();
  5547. if (methodInstance->HasThis())
  5548. {
  5549. bool failed = false;
  5550. target = DoImplicitArgCapture(targetSrc, methodInstance, -1, failed, BfImplicitParamKind_General, origTarget);
  5551. }
  5552. else if (!methodDef->mIsStatic)
  5553. {
  5554. auto thisType = methodInstance->GetParamType(-1);
  5555. BF_ASSERT(thisType->IsValuelessType());
  5556. target = BfTypedValue(mModule->mBfIRBuilder->GetFakeVal(), methodMatcher.mBestMethodTypeInstance);
  5557. }
  5558. else
  5559. target = BfTypedValue(methodMatcher.mBestMethodTypeInstance);
  5560. methodMatcher.mBypassVirtual = true;
  5561. bypassVirtual = true;
  5562. isFailurePass = false;
  5563. isIndirectMethodCall = true;
  5564. }
  5565. if (methodDef == NULL)
  5566. {
  5567. mModule->Fail(StrFormat("Cannot perform invocation on type '%s'", mModule->TypeToString(fieldVal.mType).c_str()), targetSrc);
  5568. return BfTypedValue();
  5569. }
  5570. }
  5571. }
  5572. if ((!methodDef) && (!target.mValue))
  5573. {
  5574. // Check to see if we're constructing a struct via a call like: "Struct structVal = Struct()"
  5575. int wantNumGenericArgs = 0;
  5576. if ((methodGenericArguments != NULL) && (methodGenericArguments->size() > 0))
  5577. wantNumGenericArgs = (int)methodGenericArguments->size();
  5578. BfTypeInstance* resolvedTypeInstance = NULL;
  5579. if (wantCtor)
  5580. {
  5581. resolvedTypeInstance = targetTypeInst;
  5582. }
  5583. else if (targetType != NULL)
  5584. {
  5585. if (auto invocationExpr = BfNodeDynCast<BfInvocationExpression>(methodBoundExpr))
  5586. {
  5587. auto resolvedType = mModule->ResolveTypeRef(invocationExpr->mTarget, methodGenericArguments);
  5588. if (resolvedType != NULL)
  5589. resolvedTypeInstance = resolvedType->ToTypeInstance();
  5590. }
  5591. }
  5592. else
  5593. {
  5594. BfIdentifierNode* identifierNode = BfNodeDynCast<BfIdentifierNode>(targetSrc);
  5595. if (identifierNode != NULL)
  5596. {
  5597. SetAndRestoreValue<bool> prevIgnoreErrors(mModule->mIgnoreErrors, true);
  5598. BfType* refType;
  5599. if (methodGenericArguments != NULL)
  5600. {
  5601. refType = mModule->ResolveTypeRef(identifierNode, methodGenericArguments);
  5602. }
  5603. else
  5604. refType = mModule->ResolveTypeRef(identifierNode, NULL);
  5605. prevIgnoreErrors.Restore();
  5606. if ((refType != NULL) && (refType->IsPrimitiveType()))
  5607. {
  5608. if (argValues.mResolvedArgs.size() != 1)
  5609. {
  5610. mModule->Fail("Cast requires one parameter", targetSrc);
  5611. return BfTypedValue();
  5612. }
  5613. // This is just a primitive cast
  5614. auto& resolvedArg = argValues.mResolvedArgs[0];
  5615. BfTypedValue castedValue;
  5616. BfTypedValue castTarget = resolvedArg.mTypedValue;
  5617. if (resolvedArg.mTypedValue)
  5618. {
  5619. castTarget = mModule->LoadValue(castTarget);
  5620. castedValue = mModule->Cast(targetSrc, castTarget, refType, BfCastFlags_Explicit);
  5621. }
  5622. if (!castedValue)
  5623. castedValue = mModule->GetDefaultTypedValue(refType);
  5624. return castedValue;
  5625. }
  5626. if (refType != NULL)
  5627. resolvedTypeInstance = refType->ToTypeInstance();
  5628. }
  5629. }
  5630. if (resolvedTypeInstance != NULL)
  5631. {
  5632. if ((!resolvedTypeInstance->IsStruct()) && (!resolvedTypeInstance->IsTypedPrimitive()))
  5633. {
  5634. mModule->Fail("Objects must be allocated through 'new' or 'stack'", targetSrc);
  5635. return BfTypedValue();
  5636. }
  5637. if (auto identifier = BfNodeDynCastExact<BfIdentifierNode>(targetSrc))
  5638. mModule->SetElementType(identifier, BfSourceElementType_TypeRef);
  5639. if (mModule->mCompiler->mResolvePassData != NULL)
  5640. mModule->mCompiler->mResolvePassData->HandleTypeReference(targetSrc, resolvedTypeInstance->mTypeDef);
  5641. BfTypedValue structInst;
  5642. if (!resolvedTypeInstance->IsValuelessType())
  5643. {
  5644. if ((mReceivingValue != NULL) && (mReceivingValue->mType == resolvedTypeInstance) && (mReceivingValue->IsAddr()))
  5645. {
  5646. structInst = *mReceivingValue;
  5647. mReceivingValue = NULL;
  5648. }
  5649. else
  5650. {
  5651. auto allocaInst = mModule->CreateAlloca(resolvedTypeInstance);
  5652. structInst = BfTypedValue(allocaInst, resolvedTypeInstance, true);
  5653. }
  5654. mResultIsTempComposite = true;
  5655. }
  5656. else
  5657. {
  5658. structInst = BfTypedValue(mModule->mBfIRBuilder->GetFakeVal(), resolvedTypeInstance, true);
  5659. }
  5660. mResultLocalVar = NULL;
  5661. mResultLocalVarRefNode = NULL;
  5662. MatchConstructor(targetSrc, methodBoundExpr, structInst, resolvedTypeInstance, argValues, false, false);
  5663. mModule->ValidateAllocation(resolvedTypeInstance, targetSrc);
  5664. mModule->AddDependency(resolvedTypeInstance, mModule->mCurTypeInstance, BfDependencyMap::DependencyFlag_LocalUsage);
  5665. if (mUsedAsStatement)
  5666. {
  5667. mModule->Warn(0, "Struct constructor being used as a statement", targetSrc);
  5668. }
  5669. return structInst;
  5670. }
  5671. }
  5672. if ((methodDef == NULL) && (!target) && (mModule->mContext->mCurTypeState != NULL))
  5673. {
  5674. //BF_ASSERT(mModule->mCurTypeInstance == mModule->mContext->mCurTypeState->mTypeInstance);
  5675. BfGlobalLookup globalLookup;
  5676. globalLookup.mKind = BfGlobalLookup::Kind_Method;
  5677. globalLookup.mName = methodName;
  5678. mModule->PopulateGlobalContainersList(globalLookup);
  5679. for (auto& globalContainer : mModule->mContext->mCurTypeState->mGlobalContainers)
  5680. {
  5681. if (globalContainer.mTypeInst == NULL)
  5682. continue;
  5683. methodMatcher.CheckType(globalContainer.mTypeInst, BfTypedValue(), false);
  5684. if (methodMatcher.mBestMethodDef != NULL)
  5685. {
  5686. isFailurePass = false;
  5687. curTypeInst = methodMatcher.mBestMethodTypeInstance;
  5688. methodDef = methodMatcher.mBestMethodDef;
  5689. break;
  5690. }
  5691. }
  5692. }
  5693. if (methodDef == NULL)
  5694. {
  5695. auto compiler = mModule->mCompiler;
  5696. if ((compiler->IsAutocomplete()) && (compiler->mResolvePassData->mAutoComplete->CheckFixit(targetSrc)))
  5697. {
  5698. mModule->CheckTypeRefFixit(targetSrc);
  5699. bool wantStatic = !target.mValue;
  5700. if ((targetType == NULL) && (allowImplicitThis))
  5701. {
  5702. targetType = mModule->mCurTypeInstance;
  5703. if (mModule->mCurMethodInstance != NULL)
  5704. wantStatic = mModule->mCurMethodInstance->mMethodDef->mIsStatic;
  5705. }
  5706. if (targetType != NULL)
  5707. {
  5708. auto typeInst = targetType->ToTypeInstance();
  5709. if ((typeInst->mTypeDef->mSource != NULL) && (typeInst != mModule->mContext->mBfObjectType))
  5710. {
  5711. auto parser = typeInst->mTypeDef->mSource->ToParser();
  5712. if (parser != NULL)
  5713. {
  5714. String fullName = typeInst->mTypeDef->mFullName.ToString();
  5715. String methodStr;
  5716. if (typeInst == mModule->mCurTypeInstance)
  5717. {
  5718. // Implicitly private
  5719. }
  5720. else if (mModule->TypeIsSubTypeOf(mModule->mCurTypeInstance, typeInst))
  5721. {
  5722. methodStr += "protected ";
  5723. }
  5724. else
  5725. {
  5726. methodStr += "public ";
  5727. }
  5728. if (wantStatic)
  5729. methodStr += "static ";
  5730. if (mExpectingType != NULL)
  5731. methodStr += mModule->TypeToString(mExpectingType, BfTypeNameFlag_ReduceName);
  5732. else
  5733. methodStr += "void";
  5734. methodStr += " " + methodName + "(";
  5735. std::set<String> usedNames;
  5736. for (int argIdx = 0; argIdx < (int)argValues.mResolvedArgs.size(); argIdx++)
  5737. {
  5738. if (argIdx > 0)
  5739. methodStr += ", ";
  5740. auto& resolvedArg = argValues.mResolvedArgs[argIdx];
  5741. String checkName = "param";
  5742. if (resolvedArg.mTypedValue.mType != NULL)
  5743. {
  5744. bool isOut = false;
  5745. bool isArr = false;
  5746. BfType* checkType = resolvedArg.mTypedValue.mType;
  5747. while (true)
  5748. {
  5749. if ((checkType->IsArray()) || (checkType->IsSizedArray()))
  5750. {
  5751. isArr = true;
  5752. checkType = checkType->GetUnderlyingType();
  5753. }
  5754. else if (checkType->IsRef())
  5755. {
  5756. BfRefType* refType = (BfRefType*)checkType;
  5757. if (refType->mRefKind == BfRefType::RefKind_Out)
  5758. isOut = true;
  5759. checkType = refType->GetUnderlyingType();
  5760. }
  5761. else if (checkType->IsTypeInstance())
  5762. {
  5763. BfTypeInstance* typeInst = (BfTypeInstance*)checkType;
  5764. checkName = typeInst->mTypeDef->mName->ToString();
  5765. if (checkName == "String")
  5766. checkName = "Str";
  5767. if (checkName == "Object")
  5768. checkName = "Obj";
  5769. if (isOut)
  5770. checkName = "out" + checkName;
  5771. else if (isupper(checkName[0]))
  5772. checkName[0] = tolower(checkName[0]);
  5773. if (isArr)
  5774. checkName += "Arr";
  5775. break;
  5776. }
  5777. else
  5778. break;
  5779. }
  5780. methodStr += mModule->TypeToString(resolvedArg.mTypedValue.mType, BfTypeNameFlag_ReduceName);
  5781. }
  5782. else
  5783. {
  5784. checkName = "param";
  5785. methodStr += "Object";
  5786. }
  5787. for (int i = 1; i < 10; i++)
  5788. {
  5789. String lookupName = checkName;
  5790. if (i > 1)
  5791. lookupName += StrFormat("%d", i);
  5792. if (usedNames.insert(lookupName).second)
  5793. {
  5794. methodStr += " " + lookupName;
  5795. break;
  5796. }
  5797. }
  5798. }
  5799. int fileLoc = typeInst->mTypeDef->mTypeDeclaration->GetSrcEnd();
  5800. if (auto defineBlock = BfNodeDynCast<BfBlock>(typeInst->mTypeDef->mTypeDeclaration->mDefineNode))
  5801. fileLoc = defineBlock->mCloseBrace->GetSrcStart();
  5802. methodStr += ")";
  5803. compiler->mResolvePassData->mAutoComplete->AddEntry(AutoCompleteEntry("fixit", StrFormat("Create method '%s' in '%s'\taddMethod|%s|%d|||%s|{||}", methodName.c_str(), fullName.c_str(), parser->mFileName.c_str(), fileLoc, methodStr.c_str()).c_str()));
  5804. }
  5805. }
  5806. }
  5807. }
  5808. if (methodName.IsEmpty())
  5809. {
  5810. // Would have caused a parsing error
  5811. }
  5812. else if (target.mType != NULL)
  5813. mModule->Fail(StrFormat("Method '%s' does not exist in type '%s'", methodName.c_str(), mModule->TypeToString(target.mType).c_str()), targetSrc);
  5814. else
  5815. mModule->Fail(StrFormat("Method '%s' does not exist", methodName.c_str()), targetSrc);
  5816. FinishDeferredEvals(argValues.mResolvedArgs);
  5817. return BfTypedValue();
  5818. }
  5819. if ((mModule->mCurMethodInstance != NULL) && (mModule->mCurMethodInstance->mIsUnspecialized))
  5820. {
  5821. for (auto& arg : methodMatcher.mBestMethodGenericArguments)
  5822. {
  5823. if ((arg != NULL) && (arg->IsVar()))
  5824. return mModule->GetDefaultTypedValue(mModule->GetPrimitiveType(BfTypeCode_Var));
  5825. }
  5826. }
  5827. if ((prevBindResult.mPrevVal != NULL) && (methodMatcher.mMethodCheckCount > 1))
  5828. prevBindResult.mPrevVal->mCheckedMultipleMethods = true;
  5829. BfModuleMethodInstance moduleMethodInstance = GetSelectedMethod(targetSrc, curTypeInst, methodDef, methodMatcher);
  5830. if ((bypassVirtual) && (!target.mValue) && (target.mType->IsInterface()))
  5831. {
  5832. target = mModule->GetThis();
  5833. }
  5834. if (!moduleMethodInstance)
  5835. return BfTypedValue();
  5836. bool isSkipCall = moduleMethodInstance.mMethodInstance->IsSkipCall(bypassVirtual);
  5837. if (methodDef->IsEmptyPartial())
  5838. {
  5839. // Ignore call
  5840. return mModule->GetDefaultTypedValue(moduleMethodInstance.mMethodInstance->mReturnType);
  5841. }
  5842. if ((moduleMethodInstance.mMethodInstance->mMethodDef->mIsStatic) && (moduleMethodInstance.mMethodInstance->GetOwner()->IsInterface()))
  5843. {
  5844. bool isConstrained = false;
  5845. if (target.mType != NULL)
  5846. isConstrained = target.mType->IsGenericParam();
  5847. if ((target.mType == NULL) && ((mModule->mCurMethodInstance->mIsForeignMethodDef) || (mModule->mCurTypeInstance->IsInterface())))
  5848. isConstrained = true;
  5849. if (!isConstrained)
  5850. {
  5851. if (mModule->mCurTypeInstance->IsInterface())
  5852. {
  5853. if (methodDef->mBody == NULL)
  5854. mModule->Fail(StrFormat("Interface method '%s' must provide a body to be explicitly invoked", mModule->MethodToString(moduleMethodInstance.mMethodInstance).c_str()), targetSrc);
  5855. }
  5856. else
  5857. 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);
  5858. FinishDeferredEvals(argValues.mResolvedArgs);
  5859. return mModule->GetDefaultTypedValue(moduleMethodInstance.mMethodInstance->mReturnType);
  5860. }
  5861. }
  5862. // 'base' could really mean 'this' if we're in an extension
  5863. if ((target.IsBase()) && (targetTypeInst == mModule->mCurTypeInstance))
  5864. target.ToThis();
  5865. else
  5866. MakeBaseConcrete(target);
  5867. BfTypedValue callTarget;
  5868. if (isSkipCall)
  5869. {
  5870. // Just a fake value so we can continue on without generating any code (boxing, conversion, etc)
  5871. if (target)
  5872. callTarget = BfTypedValue(mModule->mBfIRBuilder->GetFakeVal(), targetTypeInst);
  5873. }
  5874. else if (targetTypeInst == curTypeInst)
  5875. {
  5876. if ((target) && (methodDef->HasNoThisSplat()))
  5877. {
  5878. callTarget = mModule->MakeAddressable(target);
  5879. }
  5880. else
  5881. callTarget = target;
  5882. }
  5883. else if (target)
  5884. {
  5885. if (methodMatcher.mFakeConcreteTarget)
  5886. {
  5887. BF_ASSERT(curTypeInst->IsInterface());
  5888. callTarget = mModule->GetDefaultTypedValue(mModule->CreateConcreteInterfaceType(curTypeInst));
  5889. }
  5890. else if (((target.mType->IsGenericParam()) || (target.mType->IsConcreteInterfaceType())) && (curTypeInst->IsInterface()))
  5891. {
  5892. // Leave as generic
  5893. callTarget = target;
  5894. }
  5895. else
  5896. {
  5897. bool handled = false;
  5898. if ((target.mType->IsTypedPrimitive()) && (curTypeInst->IsTypedPrimitive()))
  5899. {
  5900. handled = true;
  5901. callTarget = target;
  5902. }
  5903. else if ((target.mType->IsStructOrStructPtr()) || (target.mType->IsTypedPrimitive()))
  5904. {
  5905. //BF_ASSERT(target.IsAddr());
  5906. if (curTypeInst->IsObjectOrInterface())
  5907. {
  5908. // Box it
  5909. callTarget = mModule->Cast(targetSrc, target, curTypeInst, BfCastFlags_Explicit);
  5910. handled = true;
  5911. }
  5912. else
  5913. {
  5914. //BF_ASSERT(target.IsAddr() || target.IsSplat() || target.mType->IsPointer());
  5915. }
  5916. }
  5917. else
  5918. target = mModule->LoadValue(target);
  5919. if (!handled)
  5920. {
  5921. // Could we have just unconditionally done this?
  5922. callTarget = mModule->Cast(targetSrc, target, curTypeInst, BfCastFlags_Explicit);
  5923. }
  5924. }
  5925. }
  5926. if (isFailurePass)
  5927. {
  5928. BfError* error;
  5929. if (methodMatcher.mMatchFailKind == BfMethodMatcher::MatchFailKind_CheckedMismatch)
  5930. 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);
  5931. else
  5932. error = mModule->Fail(StrFormat("'%s' is inaccessible due to its protection level", mModule->MethodToString(moduleMethodInstance.mMethodInstance).c_str()), targetSrc);
  5933. if (error != NULL)
  5934. {
  5935. if ((error != NULL) && (moduleMethodInstance.mMethodInstance->mMethodDef->mMethodDeclaration != NULL))
  5936. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("See method declaration"), moduleMethodInstance.mMethodInstance->mMethodDef->GetRefNode());
  5937. }
  5938. }
  5939. if ((mModule->mCompiler->mResolvePassData != NULL) && (methodDef != NULL))
  5940. {
  5941. auto identifierNode = BfNodeDynCast<BfIdentifierNode>(targetSrc);
  5942. while (auto qualifiedNameNode = BfNodeDynCast<BfQualifiedNameNode>(identifierNode))
  5943. identifierNode = qualifiedNameNode->mRight;
  5944. if ((identifierNode != NULL) && (methodDef->mIdx >= 0) && (!isIndirectMethodCall))
  5945. {
  5946. mModule->mCompiler->mResolvePassData->HandleMethodReference(identifierNode, curTypeInst->mTypeDef, methodDef);
  5947. auto autoComplete = GetAutoComplete();
  5948. if ((autoComplete != NULL) && (autoComplete->IsAutocompleteNode(identifierNode)))
  5949. {
  5950. autoComplete->SetDefinitionLocation(methodDef->GetRefNode());
  5951. int virtualIdx = moduleMethodInstance.mMethodInstance->mVirtualTableIdx;
  5952. if ((autoComplete->mResolveType == BfResolveType_GoToDefinition) &&
  5953. (virtualIdx != -1) && (targetTypeInst != NULL) && (!targetTypeInst->IsStruct()) && (!targetTypeInst->IsTypedPrimitive()) && (!targetTypeInst->IsInterface()) &&
  5954. // 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
  5955. (targetTypeInst->mVirtualMethodTable.size() != 0))
  5956. {
  5957. auto methodEntry = targetTypeInst->mVirtualMethodTable[virtualIdx];
  5958. if (methodEntry.mImplementingMethod.mMethodNum != -1)
  5959. {
  5960. BfMethodInstance* callingMethodInstance = methodEntry.mImplementingMethod;
  5961. if (callingMethodInstance != NULL)
  5962. {
  5963. auto callingMethodDef = callingMethodInstance->mMethodDef;
  5964. auto callingMethodDeclaration = callingMethodDef->GetMethodDeclaration();
  5965. if ((callingMethodDeclaration != NULL) && (callingMethodDeclaration->mNameNode != NULL))
  5966. autoComplete->SetDefinitionLocation(callingMethodDeclaration->mNameNode, true);
  5967. }
  5968. }
  5969. }
  5970. if (autoComplete->mDefType == NULL)
  5971. {
  5972. autoComplete->mDefMethod = methodDef;
  5973. autoComplete->mDefType = curTypeInst->mTypeDef;
  5974. }
  5975. }
  5976. }
  5977. }
  5978. // This was causing forward-backward-forward steps when we just used 'targetSrc'. Using closeParen is undesirable because most of the time
  5979. // we DO just want it to just go to the targetSrc... do we even need this?
  5980. /*if (auto invokeExpr = BfNodeDynCast<BfInvocationExpression>(targetSrc->mParent))
  5981. {
  5982. // We set the srcPos to the close paren right before the call so we keep a forward progression of src positions in the case
  5983. // where some of the params are method calls and such
  5984. if (invokeExpr->mCloseParen != NULL)
  5985. mModule->UpdateExprSrcPos(invokeExpr->mCloseParen);
  5986. else
  5987. mModule->UpdateExprSrcPos(targetSrc);
  5988. }
  5989. else
  5990. mModule->UpdateExprSrcPos(targetSrc);*/
  5991. if (!mModule->mBfIRBuilder->mIgnoreWrites)
  5992. {
  5993. //BF_ASSERT(!callTarget.mValue.IsFake());
  5994. }
  5995. prevBindResult.Restore();
  5996. if ((callTarget.mType != NULL) &&
  5997. (callTarget.mType->IsGenericParam()) &&
  5998. ((!callTarget.IsAddr()) || (callTarget.IsReadOnly())) &&
  5999. (callTarget.mKind != BfTypedValueKind_MutableValue) &&
  6000. (moduleMethodInstance.mMethodInstance->mMethodDef->mIsMutating))
  6001. {
  6002. auto genericParamInstance = mModule->GetGenericParamInstance((BfGenericParamType*)callTarget.mType);
  6003. bool needsMut = true;
  6004. if ((genericParamInstance->mGenericParamFlags & (BfGenericParamFlag_StructPtr | BfGenericParamFlag_Class | BfGenericParamFlag_Var)) != 0)
  6005. needsMut = false;
  6006. if (genericParamInstance->mTypeConstraint != NULL)
  6007. {
  6008. auto typeConstaintTypeInstance = genericParamInstance->mTypeConstraint->ToTypeInstance();
  6009. if ((typeConstaintTypeInstance != NULL) && (!typeConstaintTypeInstance->IsComposite()))
  6010. needsMut = false;
  6011. }
  6012. if (needsMut)
  6013. {
  6014. String err = StrFormat("call mutating method '%s' on", mModule->MethodToString(moduleMethodInstance.mMethodInstance).c_str());
  6015. CheckModifyResult(callTarget, targetSrc, err.c_str(), true);
  6016. }
  6017. }
  6018. if ((callTarget.mType != NULL) &&
  6019. (callTarget.mType->IsInterface()) &&
  6020. (target.IsThis()) &&
  6021. (mModule->mCurTypeInstance) &&
  6022. (!mModule->mCurMethodInstance->mMethodDef->mIsMutating) &&
  6023. (methodDef->mIsMutating))
  6024. {
  6025. mModule->Fail(StrFormat("Cannot call mutating method '%s' within default interface method '%s'. Consider adding 'mut' specifier to this method.",
  6026. mModule->MethodToString(moduleMethodInstance.mMethodInstance).c_str(), mModule->MethodToString(mModule->mCurMethodInstance).c_str()), targetSrc);
  6027. }
  6028. auto result = CreateCall(targetSrc, callTarget, origTarget, methodDef, moduleMethodInstance, bypassVirtual, argValues.mResolvedArgs, skipThis);
  6029. if (result)
  6030. {
  6031. if (result.mType->IsRef())
  6032. result = mModule->RemoveRef(result);
  6033. if (result.mType->IsSelf())
  6034. {
  6035. if (methodMatcher.mSelfType != NULL)
  6036. {
  6037. BF_ASSERT(mModule->IsInGeneric());
  6038. result = mModule->GetDefaultTypedValue(methodMatcher.mSelfType);
  6039. }
  6040. else
  6041. {
  6042. // Will be an error
  6043. result = mModule->GetDefaultTypedValue(methodMatcher.mBestMethodTypeInstance);
  6044. }
  6045. }
  6046. }
  6047. PerformCallChecks(moduleMethodInstance.mMethodInstance, targetSrc);
  6048. if (result)
  6049. {
  6050. bool discardedReturnValue = mUsedAsStatement;
  6051. if (discardedReturnValue)
  6052. {
  6053. auto _ShowDiscardWaring = [&](const String& text, BfCustomAttributes* customAttributes, BfIRConstHolder* constHolder, BfAstNode* refNode)
  6054. {
  6055. if (customAttributes != NULL)
  6056. {
  6057. auto customAttribute = customAttributes->Get(mModule->mCompiler->mNoDiscardAttributeTypeDef);
  6058. if (!customAttribute->mCtorArgs.IsEmpty())
  6059. {
  6060. String* str = mModule->GetStringPoolString(customAttribute->mCtorArgs[0], constHolder);
  6061. if ((str != NULL) && (!str->IsEmpty()))
  6062. {
  6063. mModule->Warn(0, text + ": " + *str, targetSrc);
  6064. return;
  6065. }
  6066. }
  6067. }
  6068. mModule->Warn(0, text, targetSrc);
  6069. };
  6070. bool showedWarning = false;
  6071. if (moduleMethodInstance.mMethodInstance->mMethodDef->mIsNoDiscard)
  6072. {
  6073. _ShowDiscardWaring("Discarding return value of method with [NoDiscard] attribute", moduleMethodInstance.mMethodInstance->GetCustomAttributes(),
  6074. moduleMethodInstance.mMethodInstance->GetOwner()->mConstHolder, targetSrc);
  6075. showedWarning = true;
  6076. }
  6077. auto typeInst = result.mType->ToTypeInstance();
  6078. if (typeInst != NULL)
  6079. {
  6080. if ((typeInst->mTypeDef->mIsNoDiscard) && (!showedWarning))
  6081. {
  6082. _ShowDiscardWaring("Discarding return value whose type has [NoDiscard] attribute", typeInst->mCustomAttributes, typeInst->mConstHolder, targetSrc);
  6083. }
  6084. BfModuleMethodInstance moduleMethodInstance = mModule->GetMethodByName(typeInst, "ReturnValueDiscarded", 0, true);
  6085. if (moduleMethodInstance)
  6086. {
  6087. auto wasGetDefinition = (autoComplete != NULL) && (autoComplete->mIsGetDefinition);
  6088. if (wasGetDefinition)
  6089. autoComplete->mIsGetDefinition = false;
  6090. result = mModule->MakeAddressable(result);
  6091. BfResolvedArgs resolvedArgs;
  6092. MatchMethod(targetSrc, NULL, result, false, false, "ReturnValueDiscarded", resolvedArgs, NULL);
  6093. if (wasGetDefinition)
  6094. autoComplete->mIsGetDefinition = true;
  6095. }
  6096. }
  6097. }
  6098. }
  6099. return result;
  6100. }
  6101. void BfExprEvaluator::LookupQualifiedName(BfQualifiedNameNode* nameNode, bool ignoreInitialError, bool* hadError)
  6102. {
  6103. BfIdentifierNode* nameLeft = nameNode->mLeft;
  6104. BfIdentifierNode* nameRight = nameNode->mRight;
  6105. StringT<64> fieldName;
  6106. if (nameNode->mRight != NULL)
  6107. nameNode->mRight->ToString(fieldName);
  6108. bool wasBaseLookup = false;
  6109. if (auto qualifiedLeftName = BfNodeDynCast<BfQualifiedNameNode>(nameNode->mLeft))
  6110. {
  6111. if ((qualifiedLeftName->mRight->GetSrcLength() == 4) && (qualifiedLeftName->mRight->ToStringView() == "base"))
  6112. {
  6113. wasBaseLookup = true;
  6114. auto type = mModule->ResolveTypeRef(qualifiedLeftName->mLeft, NULL);
  6115. if (type == NULL)
  6116. return;
  6117. auto fieldName = nameNode->mRight->ToString();
  6118. auto target = mModule->GetThis();
  6119. target.mType = type;
  6120. mResult = LookupField(nameNode->mRight, target, fieldName);
  6121. if (mPropDef != NULL)
  6122. {
  6123. mPropDefBypassVirtual = true;
  6124. }
  6125. return;
  6126. }
  6127. }
  6128. if (!wasBaseLookup)
  6129. mResult = LookupIdentifier(nameNode->mLeft, ignoreInitialError, hadError);
  6130. GetResult();
  6131. if (!mResult)
  6132. {
  6133. if (!ignoreInitialError)
  6134. mModule->Fail("Identifier not found", nameNode->mLeft);
  6135. return;
  6136. }
  6137. if (mResult.mType->IsObject())
  6138. {
  6139. mResult = mModule->LoadValue(mResult, 0, mIsVolatileReference);
  6140. }
  6141. else if ((mResult.mType->IsPointer()) && mResult.mType->IsStructOrStructPtr())
  6142. {
  6143. BfPointerType* structPtrType = (BfPointerType*)mResult.mType;
  6144. mResult = mModule->LoadValue(mResult, 0, mIsVolatileReference);
  6145. mResult.mType = structPtrType->mElementType;
  6146. if (mResult.mKind == BfTypedValueKind_ThisValue)
  6147. mResult.mKind = BfTypedValueKind_ThisAddr;
  6148. else
  6149. mResult.mKind = BfTypedValueKind_Addr;
  6150. }
  6151. mIsVolatileReference = false;
  6152. mIsHeapReference = false;
  6153. if (!mResult)
  6154. return;
  6155. //if (mResult.mType->IsVar())
  6156. //ResolveGenericType();
  6157. auto origResult = mResult;
  6158. auto lookupType = BindGenericType(nameNode, mResult.mType);
  6159. if (mResult.mType->IsGenericParam())
  6160. {
  6161. auto genericParamInst = mModule->GetGenericParamInstance((BfGenericParamType*)mResult.mType);
  6162. if (mModule->mCurMethodInstance->mIsUnspecialized)
  6163. {
  6164. if (genericParamInst->mTypeConstraint != NULL)
  6165. mResult.mType = genericParamInst->mTypeConstraint;
  6166. else
  6167. mResult.mType = mModule->mContext->mBfObjectType;
  6168. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_Var) != 0)
  6169. {
  6170. mResult.mType = mModule->GetPrimitiveType(BfTypeCode_Var);
  6171. }
  6172. }
  6173. else
  6174. {
  6175. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_Var) != 0)
  6176. {
  6177. //mResult.mType = mModule->ResolveGenericType(mResult.mType);
  6178. }
  6179. else if (genericParamInst->mTypeConstraint != NULL)
  6180. {
  6181. mResult = mModule->Cast(nameNode, mResult, genericParamInst->mTypeConstraint);
  6182. BF_ASSERT(mResult);
  6183. }
  6184. else
  6185. {
  6186. // This shouldn't occur - this would infer that we are accessing a member of Object or something...
  6187. //mResult.mType = mModule->ResolveGenericType(mResult.mType);
  6188. }
  6189. }
  6190. }
  6191. if (mResult.mType->IsVar())
  6192. {
  6193. mResult = BfTypedValue(mModule->GetDefaultValue(mResult.mType), mResult.mType, true);
  6194. return;
  6195. }
  6196. if (!mResult.mType->IsTypeInstance())
  6197. {
  6198. if (hadError != NULL)
  6199. *hadError = true;
  6200. mModule->Fail(StrFormat("Type '%s' has no fields", mModule->TypeToString(mResult.mType).c_str()), nameNode->mLeft);
  6201. mResult = BfTypedValue();
  6202. return;
  6203. }
  6204. BfTypedValue lookupVal = mResult;
  6205. mResult = LookupField(nameNode->mRight, lookupVal, fieldName);
  6206. if ((!mResult) && (mPropDef == NULL) && (lookupType->IsGenericParam()))
  6207. {
  6208. auto genericParamInst = mModule->GetGenericParamInstance((BfGenericParamType*)lookupType);
  6209. SizedArray<BfTypeInstance*, 8> searchConstraints;
  6210. for (auto ifaceConstraint : genericParamInst->mInterfaceConstraints)
  6211. {
  6212. //if (std::find(searchConstraints.begin(), searchConstraints.end(), ifaceConstraint) == searchConstraints.end())
  6213. if (!searchConstraints.Contains(ifaceConstraint))
  6214. {
  6215. searchConstraints.push_back(ifaceConstraint);
  6216. for (auto& innerIFaceEntry : ifaceConstraint->mInterfaces)
  6217. {
  6218. auto innerIFace = innerIFaceEntry.mInterfaceType;
  6219. //if (std::find(searchConstraints.begin(), searchConstraints.end(), innerIFace) == searchConstraints.end())
  6220. if (!searchConstraints.Contains(innerIFace))
  6221. {
  6222. searchConstraints.push_back(innerIFace);
  6223. }
  6224. }
  6225. }
  6226. }
  6227. BfTypedValue prevTarget;
  6228. BfPropertyDef* prevDef = NULL;
  6229. for (auto ifaceConstraint : searchConstraints)
  6230. {
  6231. //auto lookupVal = mModule->GetDefaultTypedValue(ifaceConstraint, origResult.IsAddr());
  6232. BfTypedValue lookupVal = BfTypedValue(mModule->mBfIRBuilder->GetFakeVal(), ifaceConstraint);
  6233. mResult = LookupField(nameNode->mRight, lookupVal, fieldName);
  6234. if (mPropDef != NULL)
  6235. {
  6236. if (prevDef != NULL)
  6237. {
  6238. bool isBetter = mModule->TypeIsSubTypeOf(mPropTarget.mType->ToTypeInstance(), prevTarget.mType->ToTypeInstance());
  6239. bool isWorse = mModule->TypeIsSubTypeOf(prevTarget.mType->ToTypeInstance(), mPropTarget.mType->ToTypeInstance());
  6240. if ((isWorse) && (!isBetter))
  6241. continue;
  6242. if (isBetter == isWorse)
  6243. {
  6244. auto error = mModule->Fail("Ambiguous property reference", nameNode->mRight);
  6245. if (error != NULL)
  6246. {
  6247. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("'%s' has a candidate", mModule->TypeToString(prevTarget.mType).c_str()), prevDef->GetRefNode());
  6248. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("'%s' has a candidate", mModule->TypeToString(mPropTarget.mType).c_str()), mPropDef->GetRefNode());
  6249. }
  6250. }
  6251. }
  6252. prevDef = mPropDef;
  6253. prevTarget = mPropTarget;
  6254. }
  6255. }
  6256. /*if ((mResult) || (mPropDef != NULL))
  6257. break;*/
  6258. }
  6259. if (mPropDef != NULL)
  6260. {
  6261. mOrigPropTarget = origResult;
  6262. if ((nameNode->mLeft->ToString() == "base") || (wasBaseLookup))
  6263. {
  6264. mPropDefBypassVirtual = true;
  6265. }
  6266. }
  6267. if ((mResult) || (mPropDef != NULL))
  6268. return;
  6269. if (hadError != NULL)
  6270. *hadError = true;
  6271. BfTypeInstance* typeInst = lookupType->ToTypeInstance();
  6272. auto compiler = mModule->mCompiler;
  6273. if ((typeInst != NULL) && (compiler->IsAutocomplete()) && (compiler->mResolvePassData->mAutoComplete->CheckFixit(nameNode->mRight)))
  6274. {
  6275. FixitAddMember(typeInst, mExpectingType, nameNode->mRight->ToString(), false);
  6276. }
  6277. mModule->Fail("Unable to find member", nameNode->mRight);
  6278. }
  6279. void BfExprEvaluator::LookupQualifiedName(BfAstNode* nameNode, BfIdentifierNode* nameLeft, BfIdentifierNode* nameRight, bool ignoreInitialError, bool* hadError)
  6280. {
  6281. String fieldName;
  6282. if (nameRight != NULL)
  6283. fieldName = nameRight->ToString();
  6284. bool wasBaseLookup = false;
  6285. if (auto qualifiedLeftName = BfNodeDynCast<BfQualifiedNameNode>(nameLeft))
  6286. {
  6287. if (qualifiedLeftName->mRight->ToString() == "base")
  6288. {
  6289. wasBaseLookup = true;
  6290. auto type = mModule->ResolveTypeRef(qualifiedLeftName->mLeft, NULL);
  6291. if (type == NULL)
  6292. return;
  6293. auto fieldName = nameRight->ToString();
  6294. auto target = mModule->GetThis();
  6295. target.mType = type;
  6296. mResult = LookupField(nameRight, target, fieldName);
  6297. if (mPropDef != NULL)
  6298. {
  6299. mPropDefBypassVirtual = true;
  6300. }
  6301. return;
  6302. }
  6303. }
  6304. if (!wasBaseLookup)
  6305. {
  6306. mResult = LookupIdentifier(nameLeft, ignoreInitialError, hadError);
  6307. if ((mResult) && (!mResult.mType->IsComposite()))
  6308. CheckResultForReading(mResult);
  6309. }
  6310. GetResult();
  6311. if (!mResult)
  6312. {
  6313. if (!ignoreInitialError)
  6314. mModule->Fail("Identifier not found", nameLeft);
  6315. return;
  6316. }
  6317. if (mResult.mType->IsObject())
  6318. {
  6319. mResult = mModule->LoadValue(mResult, 0, mIsVolatileReference);
  6320. }
  6321. else if ((mResult.mType->IsPointer()) && mResult.mType->IsStructOrStructPtr())
  6322. {
  6323. BfPointerType* structPtrType = (BfPointerType*)mResult.mType;
  6324. mResult = mModule->LoadValue(mResult, 0, mIsVolatileReference);
  6325. mResult.mType = structPtrType->mElementType;
  6326. if (mResult.mKind == BfTypedValueKind_ThisValue)
  6327. mResult.mKind = BfTypedValueKind_ThisAddr;
  6328. else
  6329. mResult.mKind = BfTypedValueKind_Addr;
  6330. }
  6331. mIsVolatileReference = false;
  6332. mIsHeapReference = false;
  6333. if (!mResult)
  6334. return;
  6335. //if (mResult.mType->IsVar())
  6336. //ResolveGenericType();
  6337. auto origResult = mResult;
  6338. auto lookupType = BindGenericType(nameNode, mResult.mType);
  6339. if (mResult.mType->IsGenericParam())
  6340. {
  6341. auto genericParamInst = mModule->GetGenericParamInstance((BfGenericParamType*)mResult.mType);
  6342. if (mModule->mCurMethodInstance->mIsUnspecialized)
  6343. {
  6344. if (genericParamInst->mTypeConstraint != NULL)
  6345. mResult.mType = genericParamInst->mTypeConstraint;
  6346. else
  6347. mResult.mType = mModule->mContext->mBfObjectType;
  6348. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_Var) != 0)
  6349. {
  6350. mResult.mType = mModule->GetPrimitiveType(BfTypeCode_Var);
  6351. }
  6352. }
  6353. else
  6354. {
  6355. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_Var) != 0)
  6356. {
  6357. //mResult.mType = mModule->ResolveGenericType(mResult.mType);
  6358. }
  6359. else if (genericParamInst->mTypeConstraint != NULL)
  6360. {
  6361. mResult = mModule->Cast(nameNode, mResult, genericParamInst->mTypeConstraint);
  6362. BF_ASSERT(mResult);
  6363. }
  6364. else
  6365. {
  6366. // This shouldn't occur - this would infer that we are accessing a member of Object or something...
  6367. //mResult.mType = mModule->ResolveGenericType(mResult.mType);
  6368. }
  6369. }
  6370. }
  6371. if (mResult.mType->IsVar())
  6372. {
  6373. mResult = BfTypedValue(mModule->GetDefaultValue(mResult.mType), mResult.mType, true);
  6374. return;
  6375. }
  6376. if (!mResult.mType->IsTypeInstance())
  6377. {
  6378. if (mResult.mType->IsSizedArray())
  6379. {
  6380. mResult.mType = mModule->GetWrappedStructType(mResult.mType);
  6381. mResult.mValue = mModule->mBfIRBuilder->CreateBitCast(mResult.mValue, mModule->mBfIRBuilder->MapTypeInstPtr(mResult.mType->ToTypeInstance()));
  6382. }
  6383. else if (mResult.mType->IsWrappableType())
  6384. {
  6385. mResult.mType = mModule->GetWrappedStructType(mResult.mType);
  6386. }
  6387. else
  6388. {
  6389. if (hadError != NULL)
  6390. *hadError = true;
  6391. mModule->Fail(StrFormat("Type '%s' has no fields", mModule->TypeToString(mResult.mType).c_str()), nameLeft);
  6392. mResult = BfTypedValue();
  6393. return;
  6394. }
  6395. }
  6396. BfTypedValue lookupVal = mResult;
  6397. mResult = LookupField(nameRight, lookupVal, fieldName);
  6398. if ((!mResult) && (mPropDef == NULL) && (lookupType->IsGenericParam()))
  6399. {
  6400. auto genericParamInst = mModule->GetGenericParamInstance((BfGenericParamType*)lookupType);
  6401. SizedArray<BfTypeInstance*, 8> searchConstraints;
  6402. for (auto ifaceConstraint : genericParamInst->mInterfaceConstraints)
  6403. {
  6404. //if (std::find(searchConstraints.begin(), searchConstraints.end(), ifaceConstraint) == searchConstraints.end())
  6405. if (!searchConstraints.Contains(ifaceConstraint))
  6406. {
  6407. searchConstraints.push_back(ifaceConstraint);
  6408. for (auto& innerIFaceEntry : ifaceConstraint->mInterfaces)
  6409. {
  6410. auto innerIFace = innerIFaceEntry.mInterfaceType;
  6411. //if (std::find(searchConstraints.begin(), searchConstraints.end(), innerIFace) == searchConstraints.end())
  6412. if (!searchConstraints.Contains(innerIFace))
  6413. {
  6414. searchConstraints.push_back(innerIFace);
  6415. }
  6416. }
  6417. }
  6418. }
  6419. BfTypedValue prevTarget;
  6420. BfPropertyDef* prevDef = NULL;
  6421. for (auto ifaceConstraint : searchConstraints)
  6422. {
  6423. //auto lookupVal = mModule->GetDefaultTypedValue(ifaceConstraint, origResult.IsAddr());
  6424. BfTypedValue lookupVal = BfTypedValue(mModule->mBfIRBuilder->GetFakeVal(), ifaceConstraint);
  6425. mResult = LookupField(nameRight, lookupVal, fieldName);
  6426. if (mPropDef != NULL)
  6427. {
  6428. if (prevDef != NULL)
  6429. {
  6430. bool isBetter = mModule->TypeIsSubTypeOf(mPropTarget.mType->ToTypeInstance(), prevTarget.mType->ToTypeInstance());
  6431. bool isWorse = mModule->TypeIsSubTypeOf(prevTarget.mType->ToTypeInstance(), mPropTarget.mType->ToTypeInstance());
  6432. if ((isWorse) && (!isBetter))
  6433. continue;
  6434. if (isBetter == isWorse)
  6435. {
  6436. auto error = mModule->Fail("Ambiguous property reference", nameRight);
  6437. if (error != NULL)
  6438. {
  6439. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("'%s' has a candidate", mModule->TypeToString(prevTarget.mType).c_str()), prevDef->GetRefNode());
  6440. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("'%s' has a candidate", mModule->TypeToString(mPropTarget.mType).c_str()), mPropDef->GetRefNode());
  6441. }
  6442. }
  6443. }
  6444. prevDef = mPropDef;
  6445. prevTarget = mPropTarget;
  6446. }
  6447. }
  6448. /*if ((mResult) || (mPropDef != NULL))
  6449. break;*/
  6450. }
  6451. if (mPropDef != NULL)
  6452. {
  6453. mOrigPropTarget = origResult;
  6454. if ((nameLeft->ToString() == "base") || (wasBaseLookup))
  6455. {
  6456. mPropDefBypassVirtual = true;
  6457. }
  6458. }
  6459. if ((mResult) || (mPropDef != NULL))
  6460. return;
  6461. if (hadError != NULL)
  6462. *hadError = true;
  6463. BfTypeInstance* typeInst = lookupType->ToTypeInstance();
  6464. auto compiler = mModule->mCompiler;
  6465. if ((typeInst != NULL) && (compiler->IsAutocomplete()) && (compiler->mResolvePassData->mAutoComplete->CheckFixit(nameRight)))
  6466. {
  6467. FixitAddMember(typeInst, mExpectingType, nameRight->ToString(), false);
  6468. }
  6469. mModule->Fail("Unable to find member", nameRight);
  6470. }
  6471. void BfExprEvaluator::LookupQualifiedStaticField(BfQualifiedNameNode* nameNode, bool ignoreIdentifierNotFoundError)
  6472. {
  6473. // Lookup left side as a type
  6474. {
  6475. BfType* type = NULL;
  6476. {
  6477. type = mModule->ResolveTypeRef(nameNode->mLeft, NULL, BfPopulateType_Data, BfResolveTypeRefFlag_AllowRef);
  6478. mModule->CheckTypeRefFixit(nameNode->mLeft);
  6479. }
  6480. if (type != NULL)
  6481. {
  6482. BfTypedValue lookupType;
  6483. if (type->IsWrappableType())
  6484. lookupType = BfTypedValue(mModule->GetWrappedStructType(type));
  6485. else
  6486. lookupType = BfTypedValue(type);
  6487. auto findName = nameNode->mRight->ToString();
  6488. /*if (findName == "base")
  6489. {
  6490. mResult = BfTypedValue(lookupType);
  6491. return;
  6492. }*/
  6493. mResult = LookupField(nameNode->mRight, lookupType, findName);
  6494. if ((mResult) || (mPropDef != NULL))
  6495. return;
  6496. if (lookupType.mType != NULL)
  6497. {
  6498. BfTypeInstance* typeInst = lookupType.mType->ToTypeInstance();
  6499. auto compiler = mModule->mCompiler;
  6500. if ((typeInst != NULL) && (compiler->IsAutocomplete()) && (compiler->mResolvePassData->mAutoComplete->CheckFixit(nameNode->mRight)))
  6501. {
  6502. FixitAddMember(typeInst, mExpectingType, nameNode->mRight->ToString(), true);
  6503. }
  6504. }
  6505. mModule->Fail("Field not found", nameNode->mRight);
  6506. return;
  6507. }
  6508. }
  6509. String fieldName = nameNode->mRight->ToString();
  6510. if (auto qualifiedLeftName = BfNodeDynCast<BfQualifiedNameNode>(nameNode->mLeft))
  6511. LookupQualifiedStaticField(qualifiedLeftName, true);
  6512. else if (auto leftName = BfNodeDynCast<BfIdentifierNode>(nameNode->mLeft))
  6513. {
  6514. mResult = LookupIdentifier(leftName);
  6515. }
  6516. GetResult();
  6517. if (!mResult)
  6518. {
  6519. if (!ignoreIdentifierNotFoundError)
  6520. mModule->Fail("Identifier not found", nameNode->mLeft);
  6521. return;
  6522. }
  6523. if (mResult.mType->IsObject())
  6524. {
  6525. mResult = mModule->LoadValue(mResult);
  6526. }
  6527. else if ((mResult.mType->IsPointer()) && mResult.mType->IsStructOrStructPtr())
  6528. {
  6529. BfPointerType* structPtrType = (BfPointerType*) mResult.mType;
  6530. mResult = mModule->LoadValue(mResult);
  6531. mResult.mType = structPtrType->mElementType;
  6532. }
  6533. if (!mResult)
  6534. return;
  6535. if (!mResult.mType->IsTypeInstance())
  6536. {
  6537. mModule->Fail(StrFormat("Type '%s' has no fields", mModule->TypeToString(mResult.mType).c_str()), nameNode->mLeft);
  6538. return;
  6539. }
  6540. mResult = LookupField(nameNode->mRight, mResult, fieldName);
  6541. if ((mResult) || (mPropDef != NULL))
  6542. return;
  6543. mModule->Fail("Unable to find member", nameNode->mRight);
  6544. }
  6545. void BfExprEvaluator::LookupQualifiedStaticField(BfAstNode* nameNode, BfIdentifierNode* nameLeft, BfIdentifierNode* nameRight, bool ignoreIdentifierNotFoundError)
  6546. {
  6547. // Lookup left side as a type
  6548. {
  6549. BfType* type = NULL;
  6550. {
  6551. SetAndRestoreValue<bool> prevIgnoreErrors(mModule->mIgnoreErrors, true);
  6552. type = mModule->ResolveTypeRef(nameLeft, NULL, BfPopulateType_Data, BfResolveTypeRefFlag_AllowRef);
  6553. }
  6554. if (type != NULL)
  6555. {
  6556. BfTypedValue lookupType;
  6557. if (type->IsWrappableType())
  6558. lookupType = BfTypedValue(mModule->GetWrappedStructType(type));
  6559. else
  6560. lookupType = BfTypedValue(type);
  6561. auto findName = nameRight->ToString();
  6562. /*if (findName == "base")
  6563. {
  6564. mResult = BfTypedValue(lookupType);
  6565. return;
  6566. }*/
  6567. mResult = LookupField(nameRight, lookupType, findName);
  6568. if ((mResult) || (mPropDef != NULL))
  6569. return;
  6570. if (lookupType.mType != NULL)
  6571. {
  6572. BfTypeInstance* typeInst = lookupType.mType->ToTypeInstance();
  6573. auto compiler = mModule->mCompiler;
  6574. if ((typeInst != NULL) && (compiler->IsAutocomplete()) && (compiler->mResolvePassData->mAutoComplete->CheckFixit(nameRight)))
  6575. {
  6576. FixitAddMember(typeInst, mExpectingType, nameRight->ToString(), true);
  6577. }
  6578. }
  6579. mModule->Fail("Field not found", nameRight);
  6580. return;
  6581. }
  6582. }
  6583. String fieldName = nameRight->ToString();
  6584. if (auto qualifiedLeftName = BfNodeDynCast<BfQualifiedNameNode>(nameLeft))
  6585. LookupQualifiedStaticField(qualifiedLeftName, qualifiedLeftName->mLeft, qualifiedLeftName->mRight, true);
  6586. else if (auto leftName = BfNodeDynCast<BfIdentifierNode>(nameLeft))
  6587. {
  6588. mResult = LookupIdentifier(leftName);
  6589. }
  6590. GetResult();
  6591. if (!mResult)
  6592. {
  6593. if (!ignoreIdentifierNotFoundError)
  6594. mModule->Fail("Identifier not found", nameLeft);
  6595. return;
  6596. }
  6597. if (mResult.mType->IsObject())
  6598. {
  6599. mResult = mModule->LoadValue(mResult);
  6600. }
  6601. else if ((mResult.mType->IsPointer()) && mResult.mType->IsStructOrStructPtr())
  6602. {
  6603. BfPointerType* structPtrType = (BfPointerType*)mResult.mType;
  6604. mResult = mModule->LoadValue(mResult);
  6605. mResult.mType = structPtrType->mElementType;
  6606. }
  6607. if (!mResult)
  6608. return;
  6609. if (!mResult.mType->IsTypeInstance())
  6610. {
  6611. mModule->Fail(StrFormat("Type '%s' has no fields", mModule->TypeToString(mResult.mType).c_str()), nameLeft);
  6612. return;
  6613. }
  6614. mResult = LookupField(nameRight, mResult, fieldName);
  6615. if ((mResult) || (mPropDef != NULL))
  6616. return;
  6617. mModule->CheckTypeRefFixit(nameLeft);
  6618. mModule->Fail("Unable to find member", nameRight);
  6619. }
  6620. void BfExprEvaluator::Visit(BfQualifiedNameNode* nameNode)
  6621. {
  6622. auto autoComplete = GetAutoComplete();
  6623. if (autoComplete != NULL)
  6624. {
  6625. autoComplete->CheckMemberReference(nameNode->mLeft, nameNode->mDot, nameNode->mRight);
  6626. }
  6627. bool hadError = false;
  6628. LookupQualifiedName(nameNode, nameNode->mLeft, nameNode->mRight, true, &hadError);
  6629. if ((mResult) || (mPropDef != NULL))
  6630. return;
  6631. if (hadError)
  6632. return;
  6633. LookupQualifiedStaticField(nameNode, nameNode->mLeft, nameNode->mRight, false);
  6634. }
  6635. void BfExprEvaluator::Visit(BfThisExpression* thisExpr)
  6636. {
  6637. mResult = mModule->GetThis();
  6638. if (!mResult)
  6639. {
  6640. mModule->Fail("Static methods don't have 'this'", thisExpr);
  6641. return;
  6642. }
  6643. //if (mResult.mType->IsTypedPrimitive())
  6644. {
  6645. mResultLocalVar = mModule->GetThisVariable();
  6646. }
  6647. }
  6648. void BfExprEvaluator::Visit(BfBaseExpression* baseExpr)
  6649. {
  6650. mResult = mModule->GetThis();
  6651. if (!mResult)
  6652. {
  6653. mModule->Fail("Static methods don't have 'base'", baseExpr);
  6654. return;
  6655. }
  6656. auto baseType = mModule->mCurTypeInstance->mBaseType;
  6657. if (baseType == NULL)
  6658. baseType = mModule->mContext->mBfObjectType;
  6659. mModule->PopulateType(baseType, BfPopulateType_Data);
  6660. mResult = mModule->Cast(baseExpr, mResult, baseType, BfCastFlags_Explicit);
  6661. }
  6662. void BfExprEvaluator::Visit(BfMixinExpression* mixinExpr)
  6663. {
  6664. if (mModule->mCurMethodInstance->mMethodDef->mMethodType == BfMethodType_Mixin)
  6665. {
  6666. auto varType = mModule->GetPrimitiveType(BfTypeCode_Var);
  6667. auto newVar = mModule->AllocFromType(varType, mModule->mCurMethodState->mCurScope);
  6668. mResult = BfTypedValue(newVar, varType, true);
  6669. return;
  6670. }
  6671. auto curMethodState = mModule->mCurMethodState;
  6672. if (curMethodState->mMixinState == NULL)
  6673. {
  6674. mModule->Fail("Mixin references can only be used within mixins", mixinExpr);
  6675. return;
  6676. }
  6677. int localIdx = GetMixinVariable();
  6678. if (localIdx != -1)
  6679. {
  6680. auto varDecl = curMethodState->mLocals[localIdx];
  6681. if (varDecl != NULL)
  6682. {
  6683. BfTypedValue localResult = LoadLocal(varDecl);
  6684. mResult = localResult;
  6685. mResultLocalVar = varDecl;
  6686. mResultLocalVarRefNode = mixinExpr;
  6687. return;
  6688. }
  6689. }
  6690. if (mModule->mCurMethodInstance->mIsUnspecialized)
  6691. {
  6692. mResult = mModule->GetDefaultTypedValue(mModule->GetPrimitiveType(BfTypeCode_Var));
  6693. return;
  6694. }
  6695. mModule->Fail("Mixin value cannot be inferred", mixinExpr);
  6696. }
  6697. void BfExprEvaluator::Visit(BfSizedArrayCreateExpression* createExpr)
  6698. {
  6699. auto type = mModule->ResolveTypeRef(createExpr->mTypeRef);
  6700. if (type == NULL)
  6701. return;
  6702. if (type->IsArray())
  6703. {
  6704. // If we have a case like 'int[] (1, 2)' then we infer the sized array size from the initializer
  6705. auto arrayType = (BfArrayType*)type;
  6706. if (arrayType->mDimensions == 1)
  6707. {
  6708. int arraySize = 0;
  6709. if (auto arrayInitExpr = BfNodeDynCast<BfCollectionInitializerExpression>(createExpr->mInitializer))
  6710. {
  6711. arraySize = (int)arrayInitExpr->mValues.size();
  6712. }
  6713. type = mModule->CreateSizedArrayType(arrayType->GetUnderlyingType(), arraySize);
  6714. }
  6715. }
  6716. if (!type->IsSizedArray())
  6717. {
  6718. mModule->Fail("Sized array expected", createExpr->mTypeRef);
  6719. return;
  6720. }
  6721. BfSizedArrayType* arrayType = (BfSizedArrayType*)type;
  6722. if (createExpr->mInitializer == NULL)
  6723. {
  6724. mModule->AssertErrorState();
  6725. mResult = mModule->GetDefaultTypedValue(arrayType);
  6726. return;
  6727. }
  6728. InitializedSizedArray(arrayType, createExpr->mInitializer->mOpenBrace, createExpr->mInitializer->mValues, createExpr->mInitializer->mCommas, createExpr->mInitializer->mCloseBrace);
  6729. }
  6730. void BfExprEvaluator::Visit(BfCollectionInitializerExpression* arrayInitExpr)
  6731. {
  6732. mModule->Fail("Collection initializer not usable here", arrayInitExpr);
  6733. }
  6734. void BfExprEvaluator::Visit(BfParamsExpression* paramsExpr)
  6735. {
  6736. mModule->Fail("Params expression is only usable as a call parameter", paramsExpr);
  6737. }
  6738. void BfExprEvaluator::Visit(BfTypeOfExpression* typeOfExpr)
  6739. {
  6740. auto typeType = mModule->ResolveTypeDef(mModule->mCompiler->mTypeTypeDef);
  6741. auto autoComplete = GetAutoComplete();
  6742. if ((autoComplete != NULL) && (typeOfExpr->mTypeRef != NULL))
  6743. {
  6744. autoComplete->CheckTypeRef(typeOfExpr->mTypeRef, false, true);
  6745. }
  6746. BfType* type;
  6747. if (auto genericTypeRef = BfNodeDynCast<BfGenericInstanceTypeRef>(typeOfExpr->mTypeRef))
  6748. {
  6749. type = mModule->ResolveTypeRefAllowUnboundGenerics(typeOfExpr->mTypeRef, BfPopulateType_Identity);
  6750. }
  6751. else
  6752. {
  6753. type = ResolveTypeRef(typeOfExpr->mTypeRef, BfPopulateType_Identity);
  6754. }
  6755. if (type == NULL)
  6756. {
  6757. mResult = mModule->GetDefaultTypedValue(mModule->ResolveTypeDef(mModule->mCompiler->mTypeTypeDef));
  6758. return;
  6759. }
  6760. mModule->AddDependency(type, mModule->mCurTypeInstance, BfDependencyMap::DependencyFlag_ExprTypeReference);
  6761. mResult = BfTypedValue(mModule->CreateTypeDataRef(type), typeType);
  6762. }
  6763. bool BfExprEvaluator::LookupTypeProp(BfTypeOfExpression* typeOfExpr, BfIdentifierNode* propName)
  6764. {
  6765. // We ignore errors because we go through the normal Visit(BfTypeOfExpression) if this fails, which will throw the error again
  6766. SetAndRestoreValue<bool> prevIgnoreErrors(mModule->mIgnoreErrors, true);
  6767. auto typeType = mModule->ResolveTypeDef(mModule->mCompiler->mTypeTypeDef);
  6768. BfType* type;
  6769. if (auto genericTypeRef = BfNodeDynCast<BfGenericInstanceTypeRef>(typeOfExpr->mTypeRef))
  6770. {
  6771. type = mModule->ResolveTypeRefAllowUnboundGenerics(typeOfExpr->mTypeRef, BfPopulateType_Identity);
  6772. }
  6773. else
  6774. {
  6775. type = ResolveTypeRef(typeOfExpr->mTypeRef, BfPopulateType_Identity);
  6776. }
  6777. if (type == NULL)
  6778. {
  6779. mResult = mModule->GetDefaultTypedValue(mModule->ResolveTypeDef(mModule->mCompiler->mTypeTypeDef));
  6780. return false;
  6781. }
  6782. mModule->AddDependency(type, mModule->mCurTypeInstance, BfDependencyMap::DependencyFlag_ExprTypeReference);
  6783. mModule->PopulateType(type);
  6784. auto typeInstance = type->ToTypeInstance();
  6785. auto _BoolResult = [&](bool val)
  6786. {
  6787. mResult = BfTypedValue(mModule->GetConstValue8(val ? 1 : 0), mModule->GetPrimitiveType(BfTypeCode_Boolean));
  6788. };
  6789. auto _Int32Result = [&](int32 val)
  6790. {
  6791. mResult = BfTypedValue(mModule->GetConstValue32(val), mModule->GetPrimitiveType(BfTypeCode_Int32));
  6792. };
  6793. String memberName;
  6794. propName->ToString(memberName);
  6795. bool handled = true;
  6796. if (memberName == "IsTypedPrimitive")
  6797. _BoolResult(type->IsPrimitiveType());
  6798. else if (memberName == "IsObject")
  6799. _BoolResult(type->IsObject());
  6800. else if (memberName == "IsValueType")
  6801. _BoolResult(type->IsValueType());
  6802. else if (memberName == "IsStruct")
  6803. _BoolResult(type->IsStruct());
  6804. else if (memberName == "IsSplattable")
  6805. _BoolResult(type->IsSplattable());
  6806. else if (memberName == "IsUnion")
  6807. _BoolResult(type->IsUnion());
  6808. else if (memberName == "IsBoxed")
  6809. _BoolResult(type->IsBoxed());
  6810. else if (memberName == "IsEnum")
  6811. _BoolResult(type->IsEnum());
  6812. else if (memberName == "IsTuple")
  6813. _BoolResult(type->IsTuple());
  6814. else if (memberName == "IsNullable")
  6815. _BoolResult(type->IsNullable());
  6816. else if (memberName == "IsGenericType")
  6817. _BoolResult(type->IsGenericTypeInstance());
  6818. else if (memberName == "TypeId")
  6819. _Int32Result(type->mTypeId);
  6820. else if (memberName == "GenericParamCount")
  6821. {
  6822. auto genericTypeInst = type->ToGenericTypeInstance();
  6823. _Int32Result((genericTypeInst != NULL) ? (int)genericTypeInst->mTypeGenericArguments.size() : 0);
  6824. }
  6825. else if (memberName == "Size")
  6826. _Int32Result(type->mSize);
  6827. else if (memberName == "Align")
  6828. _Int32Result(type->mAlign);
  6829. else if (memberName == "Stride")
  6830. _Int32Result(type->GetStride());
  6831. else if (memberName == "InstanceSize")
  6832. _Int32Result((typeInstance != NULL) ? typeInstance->mInstSize : type->mSize);
  6833. else if (memberName == "InstanceAlign")
  6834. _Int32Result((typeInstance != NULL) ? typeInstance->mInstAlign : type->mSize);
  6835. else if (memberName == "InstanceStride")
  6836. _Int32Result((typeInstance != NULL) ? typeInstance->GetInstStride() : type->GetStride());
  6837. else if ((memberName == "MinValue") || (memberName == "MaxValue"))
  6838. {
  6839. bool isMin = memberName == "MinValue";
  6840. BfType* checkType = typeInstance;
  6841. if (checkType->IsTypedPrimitive())
  6842. checkType = checkType->GetUnderlyingType();
  6843. if (checkType->IsPrimitiveType())
  6844. {
  6845. auto primType = (BfPrimitiveType*)checkType;
  6846. if (typeInstance->IsEnum())
  6847. {
  6848. if (typeInstance->mTypeInfoEx != NULL)
  6849. {
  6850. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConst(primType->mTypeDef->mTypeCode, isMin ? (uint64)typeInstance->mTypeInfoEx->mMinValue : (uint64)typeInstance->mTypeInfoEx->mMaxValue), typeInstance);
  6851. return true;
  6852. }
  6853. }
  6854. else
  6855. {
  6856. switch (primType->mTypeDef->mTypeCode)
  6857. {
  6858. case BfTypeCode_Int8:
  6859. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConst(primType->mTypeDef->mTypeCode, isMin ? -0x80 : 0x7F), typeInstance);
  6860. return true;
  6861. case BfTypeCode_Int16:
  6862. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConst(primType->mTypeDef->mTypeCode, isMin ? -0x8000 : 0x7FFF), typeInstance);
  6863. return true;
  6864. case BfTypeCode_Int32:
  6865. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConst(primType->mTypeDef->mTypeCode, isMin ? (uint64)-0x80000000LL : 0x7FFFFFFF), typeInstance);
  6866. return true;
  6867. case BfTypeCode_Int64:
  6868. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConst(primType->mTypeDef->mTypeCode, isMin ? (uint64)-0x8000000000000000LL : (uint64)0x7FFFFFFFFFFFFFFFLL), typeInstance);
  6869. return true;
  6870. case BfTypeCode_UInt8:
  6871. case BfTypeCode_Char8:
  6872. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConst(primType->mTypeDef->mTypeCode, isMin ? 0 : 0xFF), typeInstance);
  6873. return true;
  6874. case BfTypeCode_UInt16:
  6875. case BfTypeCode_Char16:
  6876. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConst(primType->mTypeDef->mTypeCode, isMin ? 0 : 0xFFFF), typeInstance);
  6877. return true;
  6878. case BfTypeCode_UInt32:
  6879. case BfTypeCode_Char32:
  6880. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConst(primType->mTypeDef->mTypeCode, isMin ? 0 : (uint64)0xFFFFFFFFLL), typeInstance);
  6881. return true;
  6882. case BfTypeCode_UInt64:
  6883. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConst(primType->mTypeDef->mTypeCode, isMin ? 0 : (uint64)0xFFFFFFFFFFFFFFFFLL), typeInstance);
  6884. return true;
  6885. default: break;
  6886. }
  6887. }
  6888. }
  6889. if (typeInstance->IsEnum())
  6890. {
  6891. mModule->Fail("'MinValue' cannot be used on enums with payloads", propName);
  6892. }
  6893. else
  6894. {
  6895. mModule->Fail(StrFormat("'%s' cannot be used on type '%s'", memberName.c_str(), mModule->TypeToString(typeInstance).c_str()), propName);
  6896. }
  6897. }
  6898. else
  6899. return false;
  6900. auto autoComplete = GetAutoComplete();
  6901. if ((autoComplete != NULL) && (typeOfExpr->mTypeRef != NULL))
  6902. {
  6903. autoComplete->CheckTypeRef(typeOfExpr->mTypeRef, false, true);
  6904. }
  6905. return true;
  6906. }
  6907. void BfExprEvaluator::DoTypeIntAttr(BfTypeReference* typeRef, BfToken token)
  6908. {
  6909. auto type = mModule->ResolveTypeRef(typeRef, BfPopulateType_Data, BfResolveTypeRefFlag_AutoComplete);
  6910. if (type == NULL)
  6911. return;
  6912. mModule->AddDependency(type, mModule->mCurTypeInstance, BfDependencyMap::DependencyFlag_LocalUsage); // Local usage ensures it changes when the type data changes
  6913. auto typeInst = type->ToTypeInstance();
  6914. if ((typeInst != NULL) && (typeInst->mTypeDef->mIsOpaque))
  6915. {
  6916. mModule->Fail(StrFormat("Unable to determine attributes for opaque type '%s'", mModule->TypeToString(type).c_str()), typeRef);
  6917. }
  6918. BfType* sizeType = mModule->GetPrimitiveType(BfTypeCode_Int32);
  6919. int attrVal = 0;
  6920. switch (token)
  6921. {
  6922. case BfToken_SizeOf: attrVal = type->mSize; break;
  6923. case BfToken_AlignOf: attrVal = type->mAlign; break;
  6924. case BfToken_StrideOf: attrVal = type->GetStride(); break;
  6925. default: break;
  6926. }
  6927. bool isUndefVal = false;
  6928. if (type->IsGenericParam())
  6929. isUndefVal = true;
  6930. if (type->IsSizedArray())
  6931. {
  6932. auto sizedArray = (BfSizedArrayType*)type;
  6933. if (sizedArray->mElementCount == -1)
  6934. isUndefVal = true;
  6935. }
  6936. if (isUndefVal)
  6937. {
  6938. // We do this so we know it's a constant but we can't assume anything about its value
  6939. // We make the value an Int32 which doesn't match the IntPtr type, but it allows us to
  6940. // assume it can be implicitly cased to int32
  6941. mResult = BfTypedValue(mModule->mBfIRBuilder->GetUndefConstValue(BfTypeCode_Int32), sizeType);
  6942. }
  6943. else
  6944. mResult = BfTypedValue(mModule->GetConstValue(attrVal, sizeType), sizeType);
  6945. }
  6946. void BfExprEvaluator::Visit(BfSizeOfExpression* sizeOfExpr)
  6947. {
  6948. DoTypeIntAttr(sizeOfExpr->mTypeRef, BfToken_SizeOf);
  6949. }
  6950. void BfExprEvaluator::Visit(BfAlignOfExpression* alignOfExpr)
  6951. {
  6952. DoTypeIntAttr(alignOfExpr->mTypeRef, BfToken_AlignOf);
  6953. }
  6954. void BfExprEvaluator::Visit(BfStrideOfExpression* strideOfExpr)
  6955. {
  6956. DoTypeIntAttr(strideOfExpr->mTypeRef, BfToken_StrideOf);
  6957. }
  6958. void BfExprEvaluator::Visit(BfDefaultExpression* defaultExpr)
  6959. {
  6960. auto autoComplete = GetAutoComplete();
  6961. if (autoComplete != NULL)
  6962. autoComplete->CheckTypeRef(defaultExpr->mTypeRef, false, true);
  6963. BfType* type = NULL;
  6964. if (defaultExpr->mOpenParen == NULL)
  6965. {
  6966. if (mExpectingType)
  6967. {
  6968. type = mExpectingType;
  6969. }
  6970. else
  6971. {
  6972. mModule->Fail("Type cannot be inferred, consider adding explicit type name", defaultExpr);
  6973. return;
  6974. }
  6975. }
  6976. else
  6977. type = mModule->ResolveTypeRef(defaultExpr->mTypeRef);
  6978. if (type == NULL)
  6979. return;
  6980. BfDefaultValueKind defaultKind = BfDefaultValueKind_Const;
  6981. if (type->IsRef())
  6982. {
  6983. mModule->Fail(StrFormat("There is no default value for type '%s'", mModule->TypeToString(type).c_str()), defaultExpr);
  6984. defaultKind = BfDefaultValueKind_Addr;
  6985. }
  6986. mModule->ValidateAllocation(type, defaultExpr->mTypeRef);
  6987. mModule->AddDependency(type, mModule->mCurTypeInstance, BfDependencyMap::DependencyFlag_ExprTypeReference);
  6988. mResult = mModule->GetDefaultTypedValue(type, true, defaultKind);
  6989. }
  6990. void BfExprEvaluator::Visit(BfUninitializedExpression* uninitialziedExpr)
  6991. {
  6992. mModule->Fail("Invalid use of the '?' uninitialized specifier", uninitialziedExpr);
  6993. }
  6994. void BfExprEvaluator::Visit(BfCheckTypeExpression* checkTypeExpr)
  6995. {
  6996. auto targetValue = mModule->CreateValueFromExpression(checkTypeExpr->mTarget);
  6997. if (!targetValue)
  6998. return;
  6999. if (checkTypeExpr->mTypeRef == NULL)
  7000. {
  7001. mModule->AssertErrorState();
  7002. return;
  7003. }
  7004. auto autoComplete = GetAutoComplete();
  7005. if (autoComplete != NULL)
  7006. autoComplete->CheckTypeRef(checkTypeExpr->mTypeRef, false, true);
  7007. auto targetType = mModule->ResolveTypeRefAllowUnboundGenerics(checkTypeExpr->mTypeRef);
  7008. if (!targetType)
  7009. {
  7010. mModule->AssertErrorState();
  7011. return;
  7012. }
  7013. mModule->AddDependency(targetType, mModule->mCurTypeInstance, BfDependencyMap::DependencyFlag_ExprTypeReference);
  7014. auto boolType = mModule->GetPrimitiveType(BfTypeCode_Boolean);
  7015. if (targetValue.mType->IsValueTypeOrValueTypePtr())
  7016. {
  7017. auto typeInstance = targetValue.mType->ToTypeInstance();
  7018. if (targetValue.mType->IsWrappableType())
  7019. typeInstance = mModule->GetWrappedStructType(targetValue.mType);
  7020. bool matches = (targetValue.mType == targetType) || (mModule->mContext->mBfObjectType == targetType);
  7021. if (!matches)
  7022. matches = mModule->TypeIsSubTypeOf(typeInstance, targetType->ToTypeInstance());
  7023. mResult = BfTypedValue(mModule->GetConstValue(matches ? 1 : 0, boolType), boolType);
  7024. return;
  7025. }
  7026. if (targetType->IsValueType())
  7027. {
  7028. if ((targetValue.mType != mModule->mContext->mBfObjectType) && (!targetValue.mType->IsInterface()))
  7029. {
  7030. mResult = BfTypedValue(mModule->GetConstValue(0, boolType), boolType);
  7031. return;
  7032. }
  7033. }
  7034. int wantTypeId = 0;
  7035. if (!targetType->IsGenericParam())
  7036. wantTypeId = targetType->mTypeId;
  7037. auto objectType = mModule->mContext->mBfObjectType;
  7038. mModule->PopulateType(objectType, BfPopulateType_Full);
  7039. targetValue = mModule->LoadValue(targetValue);
  7040. BfTypeInstance* srcTypeInstance = targetValue.mType->ToTypeInstance();
  7041. BfTypeInstance* targetTypeInstance = targetType->ToTypeInstance();
  7042. bool wasGenericParamType = false;
  7043. if ((srcTypeInstance != NULL) && (targetTypeInstance != NULL))
  7044. {
  7045. if (mModule->TypeIsSubTypeOf(srcTypeInstance, targetTypeInstance))
  7046. {
  7047. // We don't give this warning when we have wasGenericParmType set because that indicates we had a generic type constraint,
  7048. // and a type constraint infers that the ACTUAL type used will be equal to or derived from that type and therefore
  7049. // it may be a "necessary cast" indeed
  7050. if ((!wasGenericParamType) && (mModule->mCurMethodState->mMixinState == NULL))
  7051. {
  7052. if (srcTypeInstance == targetType)
  7053. mModule->Warn(BfWarning_BF4203_UnnecessaryDynamicCast, StrFormat("Unnecessary cast, the value is already type '%s'",
  7054. mModule->TypeToString(srcTypeInstance).c_str()), checkTypeExpr->mIsToken);
  7055. else
  7056. mModule->Warn(BfWarning_BF4203_UnnecessaryDynamicCast, StrFormat("Unnecessary cast, '%s' is a subtype of '%s'",
  7057. mModule->TypeToString(srcTypeInstance).c_str(), mModule->TypeToString(targetType).c_str()), checkTypeExpr->mIsToken);
  7058. }
  7059. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConst(BfTypeCode_Boolean, 1), boolType);
  7060. return;
  7061. }
  7062. else if ((!targetType->IsInterface()) && (srcTypeInstance != mModule->mContext->mBfObjectType) && (!mModule->TypeIsSubTypeOf(targetTypeInstance, srcTypeInstance)))
  7063. {
  7064. mModule->Fail(StrFormat("Cannot convert type '%s' to '%s' via any conversion",
  7065. mModule->TypeToString(targetValue.mType).c_str(), mModule->TypeToString(targetTypeInstance).c_str()), checkTypeExpr->mIsToken);
  7066. }
  7067. }
  7068. if (mModule->mCompiler->IsAutocomplete())
  7069. {
  7070. mResult = mModule->GetDefaultTypedValue(boolType, false, BfDefaultValueKind_Addr);
  7071. return;
  7072. }
  7073. auto irb = mModule->mBfIRBuilder;
  7074. auto prevBB = mModule->mBfIRBuilder->GetInsertBlock();
  7075. auto matchBB = mModule->mBfIRBuilder->CreateBlock("is.match");
  7076. auto endBB = mModule->mBfIRBuilder->CreateBlock("is.done");
  7077. BfIRValue boolResult = mModule->CreateAlloca(boolType);
  7078. irb->CreateStore(irb->CreateConst(BfTypeCode_Boolean, 0), boolResult);
  7079. mModule->EmitDynamicCastCheck(targetValue, targetType, matchBB, endBB);
  7080. mModule->AddBasicBlock(matchBB);
  7081. irb->CreateStore(irb->CreateConst(BfTypeCode_Boolean, 1), boolResult);
  7082. irb->CreateBr(endBB);
  7083. mModule->AddBasicBlock(endBB);
  7084. mResult = BfTypedValue(irb->CreateLoad(boolResult), boolType);
  7085. }
  7086. void BfExprEvaluator::Visit(BfDynamicCastExpression* dynCastExpr)
  7087. {
  7088. auto targetValue = mModule->CreateValueFromExpression(dynCastExpr->mTarget);
  7089. auto targetType = mModule->ResolveTypeRefAllowUnboundGenerics(dynCastExpr->mTypeRef, BfPopulateType_Data, false);
  7090. auto autoComplete = GetAutoComplete();
  7091. if (autoComplete != NULL)
  7092. {
  7093. autoComplete->CheckTypeRef(dynCastExpr->mTypeRef, false, true);
  7094. }
  7095. if (!targetValue)
  7096. return;
  7097. if (!targetType)
  7098. {
  7099. mModule->AssertErrorState();
  7100. return;
  7101. }
  7102. bool wasGenericParamType = false;
  7103. if (targetType->IsGenericParam())
  7104. {
  7105. //targetType = mModule->ResolveGenericType(targetType);
  7106. //wasGenericParamType = true;
  7107. }
  7108. if ((targetValue.mType->IsMethodRef()) || (targetType->IsMethodRef()))
  7109. {
  7110. // We can never cast a MethodRef to any class type
  7111. mResult = mModule->GetDefaultTypedValue(targetType);
  7112. return;
  7113. }
  7114. if (mModule->mContext->mResolvingVarField)
  7115. {
  7116. mResult = mModule->GetDefaultTypedValue(targetType);
  7117. return;
  7118. }
  7119. mModule->AddDependency(targetType, mModule->mCurTypeInstance, BfDependencyMap::DependencyFlag_ExprTypeReference);
  7120. if (targetType->IsGenericParam())
  7121. {
  7122. wasGenericParamType = true;
  7123. //wasGenericParamType = false; // "was", not "is"
  7124. auto genericParamType = (BfGenericParamType*) targetType;
  7125. auto genericParam = mModule->GetGenericParamInstance(genericParamType);
  7126. auto typeConstraint = genericParam->mTypeConstraint;
  7127. if ((typeConstraint == NULL) && (genericParam->mGenericParamFlags & BfGenericParamFlag_Class))
  7128. typeConstraint = mModule->mContext->mBfObjectType;
  7129. if ((typeConstraint == NULL) || (!typeConstraint->IsObject()))
  7130. {
  7131. mModule->Fail(StrFormat("The type parameter '%s' cannot be used with the 'as' operator because it does not have a class type constraint nor a 'class' constraint",
  7132. genericParam->GetGenericParamDef()->mName.c_str()), dynCastExpr->mTypeRef);
  7133. return;
  7134. }
  7135. targetType = typeConstraint;
  7136. targetValue = mModule->GetDefaultTypedValue(targetType);
  7137. }
  7138. if ((!targetType->IsObjectOrInterface()) && (!targetType->IsNullable()))
  7139. {
  7140. mModule->Fail(StrFormat("The as operator must be used with a reference type or nullable type ('%s' is a non-nullable value type)",
  7141. mModule->TypeToString(targetType).c_str()), dynCastExpr->mTypeRef);
  7142. return;
  7143. }
  7144. if (targetValue.mType->IsGenericParam())
  7145. {
  7146. auto genericParamType = (BfGenericParamType*)targetValue.mType;
  7147. auto genericParam = mModule->GetGenericParamInstance(genericParamType);
  7148. auto typeConstraint = genericParam->mTypeConstraint;
  7149. if (typeConstraint == NULL)
  7150. typeConstraint = mModule->mContext->mBfObjectType;
  7151. if ((typeConstraint->IsDelegate()) && (typeConstraint == targetType))
  7152. {
  7153. // Delegate constraints may be matched by valueless method references, so this won't always match (don't warn)
  7154. mResult = mModule->GetDefaultTypedValue(targetType);
  7155. return;
  7156. }
  7157. //targetType = typeConstraint;
  7158. targetValue = mModule->GetDefaultTypedValue(typeConstraint);
  7159. }
  7160. auto boolType = mModule->GetPrimitiveType(BfTypeCode_Boolean);
  7161. if (targetValue.mType->IsValueTypeOrValueTypePtr())
  7162. {
  7163. mModule->Warn(0, StrFormat("Type '%s' is not applicable for dynamic casting",
  7164. mModule->TypeToString(targetValue.mType).c_str()), dynCastExpr->mAsToken);
  7165. auto typeInstance = targetValue.mType->ToTypeInstance();
  7166. if (targetValue.mType->IsWrappableType())
  7167. typeInstance = mModule->GetWrappedStructType(targetValue.mType);
  7168. bool matches = (targetValue.mType == targetType) || (mModule->mContext->mBfObjectType == targetType);
  7169. if (targetType->IsNullable())
  7170. {
  7171. auto elementType = targetType->GetUnderlyingType();
  7172. if (elementType == targetValue.mType)
  7173. {
  7174. // We match nullable element
  7175. auto allocaInst = mModule->CreateAlloca(targetType);
  7176. auto hasValueAddr = mModule->mBfIRBuilder->CreateInBoundsGEP(allocaInst, 0, 1); // has_value
  7177. mModule->mBfIRBuilder->CreateStore(mModule->GetConstValue(1, boolType), hasValueAddr);
  7178. hasValueAddr = mModule->mBfIRBuilder->CreateInBoundsGEP(allocaInst, 0, 0); // value
  7179. mModule->mBfIRBuilder->CreateStore(targetValue.mValue, hasValueAddr);
  7180. mResult = BfTypedValue(allocaInst, targetType, true);
  7181. return;
  7182. }
  7183. }
  7184. if (!matches)
  7185. matches = mModule->TypeIsSubTypeOf(typeInstance, targetType->ToTypeInstance());
  7186. if (matches)
  7187. mResult = mModule->Cast(dynCastExpr, targetValue, targetType, BfCastFlags_Explicit);
  7188. else if (targetType->IsNullable())
  7189. {
  7190. auto allocaInst = mModule->CreateAlloca(targetType);
  7191. auto allocaBits = mModule->mBfIRBuilder->CreateBitCast(allocaInst, mModule->mBfIRBuilder->GetPrimitiveType(BfTypeCode_NullPtr));
  7192. mModule->mBfIRBuilder->CreateMemSet(allocaBits, mModule->GetConstValue(0, mModule->GetPrimitiveType(BfTypeCode_Int8)),
  7193. mModule->GetConstValue(targetType->mSize), targetType->mAlign);
  7194. mResult = BfTypedValue(allocaInst, targetType, true);
  7195. }
  7196. else
  7197. mResult = BfTypedValue(mModule->GetDefaultValue(targetType), targetType);
  7198. return;
  7199. }
  7200. if (targetType->IsNullable())
  7201. {
  7202. if (autoComplete != NULL)
  7203. {
  7204. mResult = mModule->GetDefaultTypedValue(targetType);
  7205. return;
  7206. }
  7207. auto elementType = targetType->GetUnderlyingType();
  7208. auto allocaInst = mModule->CreateAlloca(targetType);
  7209. auto hasValueAddr = mModule->mBfIRBuilder->CreateInBoundsGEP(allocaInst, 0, elementType->IsValuelessType() ? 1 : 2); // has_value
  7210. mModule->mBfIRBuilder->CreateStore(mModule->GetConstValue(0, boolType), hasValueAddr);
  7211. auto objectType = mModule->mContext->mBfObjectType;
  7212. auto prevBB = mModule->mBfIRBuilder->GetInsertBlock();
  7213. auto matchBB = mModule->mBfIRBuilder->CreateBlock("as.match");
  7214. auto endBB = mModule->mBfIRBuilder->CreateBlock("as.end");
  7215. mModule->EmitDynamicCastCheck(targetValue, elementType, matchBB, endBB);
  7216. BfBoxedType* boxedType = mModule->CreateBoxedType(elementType);
  7217. mModule->AddBasicBlock(matchBB);
  7218. if (elementType->IsValuelessType())
  7219. {
  7220. auto hasValueAddr = mModule->mBfIRBuilder->CreateInBoundsGEP(allocaInst, 0, 1); // has_value
  7221. mModule->mBfIRBuilder->CreateStore(mModule->GetConstValue(1, boolType), hasValueAddr);
  7222. }
  7223. else
  7224. {
  7225. auto hasValueAddr = mModule->mBfIRBuilder->CreateInBoundsGEP(allocaInst, 0, 2); // has_value
  7226. mModule->mBfIRBuilder->CreateStore(mModule->GetConstValue(1, boolType), hasValueAddr);
  7227. auto nullableValueAddr = mModule->mBfIRBuilder->CreateInBoundsGEP(allocaInst, 0, 1); // value
  7228. auto srcBoxedType = mModule->mBfIRBuilder->CreateBitCast(targetValue.mValue, mModule->mBfIRBuilder->MapType(boxedType, BfIRPopulateType_Full));
  7229. auto boxedValueAddr = mModule->mBfIRBuilder->CreateInBoundsGEP(srcBoxedType, 0, 1); // mValue
  7230. auto boxedValue = mModule->mBfIRBuilder->CreateLoad(boxedValueAddr);
  7231. mModule->mBfIRBuilder->CreateStore(boxedValue, nullableValueAddr);
  7232. }
  7233. mModule->mBfIRBuilder->CreateBr(endBB);
  7234. mModule->AddBasicBlock(endBB);
  7235. mResult = BfTypedValue(allocaInst, targetType, true);
  7236. return;
  7237. }
  7238. targetValue = mModule->LoadValue(targetValue);
  7239. if (targetType->IsValueType())
  7240. {
  7241. mModule->Fail("Invalid dynamic cast type", dynCastExpr->mTypeRef);
  7242. return;
  7243. }
  7244. BfTypeInstance* srcTypeInstance = targetValue.mType->ToTypeInstance();
  7245. BfTypeInstance* targetTypeInstance = targetType->ToTypeInstance();
  7246. if (mModule->TypeIsSubTypeOf(srcTypeInstance, targetTypeInstance))
  7247. {
  7248. // We don't give this warning when we have wasGenericParmType set because that indicates we had a generic type constraint,
  7249. // and a type constraint infers that the ACTUAL type used will be equal to or derived from that type and therefore
  7250. // it may be a "necessary cast" indeed
  7251. if ((!wasGenericParamType) && (mModule->mCurMethodState->mMixinState == NULL))
  7252. {
  7253. if (srcTypeInstance == targetType)
  7254. mModule->Warn(BfWarning_BF4203_UnnecessaryDynamicCast, StrFormat("Unnecessary cast, the value is already type '%s'",
  7255. mModule->TypeToString(srcTypeInstance).c_str()), dynCastExpr->mAsToken);
  7256. else
  7257. mModule->Warn(BfWarning_BF4203_UnnecessaryDynamicCast, StrFormat("Unnecessary cast, '%s' is a subtype of '%s'",
  7258. mModule->TypeToString(srcTypeInstance).c_str(), mModule->TypeToString(targetType).c_str()), dynCastExpr->mAsToken);
  7259. }
  7260. auto castedValue = mModule->mBfIRBuilder->CreateBitCast(targetValue.mValue, mModule->mBfIRBuilder->MapType(targetTypeInstance));
  7261. mResult = BfTypedValue(castedValue, targetTypeInstance);
  7262. return;
  7263. }
  7264. else if ((!targetType->IsInterface()) && (!mModule->TypeIsSubTypeOf(targetTypeInstance, srcTypeInstance)))
  7265. {
  7266. mModule->Fail(StrFormat("Cannot convert type '%s' to '%s' via any conversion",
  7267. mModule->TypeToString(targetValue.mType).c_str(), mModule->TypeToString(targetTypeInstance).c_str()), dynCastExpr->mAsToken);
  7268. }
  7269. if (autoComplete != NULL)
  7270. {
  7271. mResult = mModule->GetDefaultTypedValue(targetType);
  7272. return;
  7273. }
  7274. auto irb = mModule->mBfIRBuilder;
  7275. auto objectType = mModule->mContext->mBfObjectType;
  7276. mModule->PopulateType(objectType, BfPopulateType_Full);
  7277. auto prevBB = mModule->mBfIRBuilder->GetInsertBlock();
  7278. auto endBB = mModule->mBfIRBuilder->CreateBlock("as.end");
  7279. auto matchBlock = irb->CreateBlock("as.match");
  7280. BfIRValue targetVal = mModule->CreateAlloca(targetType);
  7281. irb->CreateStore(irb->CreateConstNull(irb->MapType(targetType)), targetVal);
  7282. mModule->EmitDynamicCastCheck(targetValue, targetType, matchBlock, endBB);
  7283. mModule->AddBasicBlock(matchBlock);
  7284. BfIRValue castedCallResult = mModule->mBfIRBuilder->CreateBitCast(targetValue.mValue, mModule->mBfIRBuilder->MapType(targetType));
  7285. irb->CreateStore(castedCallResult, targetVal);
  7286. irb->CreateBr(endBB);
  7287. mModule->AddBasicBlock(endBB);
  7288. mResult = BfTypedValue(irb->CreateLoad(targetVal), targetType);
  7289. }
  7290. void BfExprEvaluator::Visit(BfCastExpression* castExpr)
  7291. {
  7292. auto autoComplete = GetAutoComplete();
  7293. if ((autoComplete != NULL) && (castExpr->mTypeRef != NULL))
  7294. {
  7295. // 'mayBeIdentifier' because this may be a misidentified cast - it could be a parenthesized expression
  7296. autoComplete->CheckTypeRef(castExpr->mTypeRef, true, true);
  7297. }
  7298. BfType* resolvedType = NULL;
  7299. if ((BfNodeDynCastExact<BfDotTypeReference>(castExpr->mTypeRef) != NULL) && (mExpectingType != NULL))
  7300. {
  7301. //mModule->SetElementType(castExpr->mTypeRef, BfSourceElementType_TypeRef);
  7302. resolvedType = mExpectingType;
  7303. }
  7304. else
  7305. resolvedType = ResolveTypeRef(castExpr->mTypeRef);
  7306. if (resolvedType != NULL)
  7307. mModule->AddDependency(resolvedType, mModule->mCurTypeInstance, BfDependencyMap::DependencyFlag_LocalUsage);
  7308. // If resolvedType is NULL then that's okay- we just leave the following expression uncasted
  7309. if (castExpr->mExpression == NULL)
  7310. {
  7311. mModule->AssertErrorState();
  7312. return;
  7313. }
  7314. mResult = mModule->CreateValueFromExpression(castExpr->mExpression, resolvedType, (BfEvalExprFlags)(BfEvalExprFlags_ExplicitCast));
  7315. }
  7316. bool BfExprEvaluator::IsExactMethodMatch(BfMethodInstance* methodA, BfMethodInstance* methodB, bool ignoreImplicitParams)
  7317. {
  7318. if (methodA->mReturnType != methodB->mReturnType)
  7319. return false;
  7320. int implicitParamCountA = methodA->GetImplicitParamCount();
  7321. int implicitParamCountB = methodB->GetImplicitParamCount();
  7322. if (methodA->GetParamCount() - implicitParamCountA != methodB->GetParamCount() - implicitParamCountB)
  7323. return false;
  7324. for (int i = 0; i < (int)methodA->GetParamCount() - implicitParamCountA; i++)
  7325. {
  7326. auto paramA = methodA->GetParamType(i + implicitParamCountA);
  7327. auto paramB = methodB->GetParamType(i + implicitParamCountB);
  7328. if (paramA != paramB)
  7329. return false;
  7330. }
  7331. return true;
  7332. }
  7333. void BfExprEvaluator::ConstResolve(BfExpression* expr)
  7334. {
  7335. BfConstResolver constResolver(mModule);
  7336. constResolver.Resolve(expr);
  7337. mResult = constResolver.mResult;
  7338. }
  7339. BfTypeInstance* BfExprEvaluator::VerifyBaseDelegateType(BfTypeInstance* baseDelegateType)
  7340. {
  7341. mModule->PopulateType(baseDelegateType, BfPopulateType_DataAndMethods);
  7342. if (baseDelegateType->mFieldInstances.size() != 2)
  7343. {
  7344. mModule->AssertErrorState();
  7345. return NULL;
  7346. }
  7347. return baseDelegateType;
  7348. }
  7349. bool BfExprEvaluator::CanBindDelegate(BfDelegateBindExpression* delegateBindExpr, BfMethodInstance** boundMethod)
  7350. {
  7351. if (mExpectingType == NULL)
  7352. {
  7353. return false;
  7354. }
  7355. auto typeInstance = mExpectingType->ToTypeInstance();
  7356. if ((typeInstance == NULL) || (!typeInstance->mTypeDef->mIsDelegate))
  7357. return false;
  7358. mModule->PopulateType(typeInstance, BfPopulateType_DataAndMethods);
  7359. auto methodInstance = mModule->GetRawMethodInstanceAtIdx(typeInstance, 0, "Invoke");
  7360. if (methodInstance == NULL)
  7361. {
  7362. BF_DBG_FATAL("Invoke not found");
  7363. return false;
  7364. }
  7365. if (delegateBindExpr->mTarget == NULL)
  7366. return false;
  7367. BfAutoParentNodeEntry autoParentNodeEntry(mModule, delegateBindExpr);
  7368. SizedArray<BfTypedValueExpression, 4> typedValueExprs;
  7369. typedValueExprs.resize(methodInstance->GetParamCount());
  7370. SizedArray<BfExpression*, 4> args;
  7371. args.resize(methodInstance->GetParamCount());
  7372. for (int i = 0; i < (int) methodInstance->GetParamCount(); i++)
  7373. {
  7374. auto typedValueExpr = &typedValueExprs[i];
  7375. typedValueExpr->mTypedValue.mValue = BfIRValue(BfIRValueFlags_Value, -1);
  7376. typedValueExpr->mTypedValue.mType = methodInstance->GetParamType(i);
  7377. typedValueExpr->mRefNode = NULL;
  7378. args[i] = typedValueExpr;
  7379. }
  7380. BfSizedArray<ASTREF(BfTypeReference*)>* methodGenericArguments = NULL;
  7381. if (delegateBindExpr->mGenericArgs != NULL)
  7382. methodGenericArguments = &delegateBindExpr->mGenericArgs->mGenericArgs;
  7383. BfFunctionBindResult bindResult;
  7384. bindResult.mSkipMutCheck = true; // Allow operating on copies
  7385. mFunctionBindResult = &bindResult;
  7386. SetAndRestoreValue<bool> ignoreError(mModule->mIgnoreErrors, true);
  7387. DoInvocation(delegateBindExpr->mTarget, delegateBindExpr, args, methodGenericArguments);
  7388. mFunctionBindResult = NULL;
  7389. if (bindResult.mMethodInstance == NULL)
  7390. return false;
  7391. if (boundMethod != NULL)
  7392. *boundMethod = bindResult.mMethodInstance;
  7393. return IsExactMethodMatch(methodInstance, bindResult.mMethodInstance, true);
  7394. }
  7395. BfTypedValue BfExprEvaluator::DoImplicitArgCapture(BfAstNode* refNode, BfIdentifierNode* identifierNode)
  7396. {
  7397. String findName = identifierNode->ToString();
  7398. if (mModule->mCurMethodState != NULL)
  7399. {
  7400. auto rootMethodState = mModule->mCurMethodState->GetRootMethodState();
  7401. auto checkMethodState = mModule->mCurMethodState;
  7402. bool isMixinOuterVariablePass = false;
  7403. while (checkMethodState != NULL)
  7404. {
  7405. BP_ZONE("LookupIdentifier:DoImplicitArgCapture");
  7406. BfTypeInstance* closureTypeInst = NULL;
  7407. BfClosureInstanceInfo* closureInstanceInfo = NULL;
  7408. if ((checkMethodState->mClosureState != NULL) && (checkMethodState->mClosureState->mClosureType != NULL) && (!checkMethodState->mClosureState->mCapturing))
  7409. {
  7410. closureTypeInst = mModule->mCurMethodState->mClosureState->mClosureType;
  7411. }
  7412. BfLocalVarEntry* entry;
  7413. if (checkMethodState->mLocalVarSet.TryGetWith<StringImpl&>(findName, &entry))
  7414. {
  7415. auto varDecl = entry->mLocalVar;
  7416. while (varDecl != NULL)
  7417. {
  7418. // if ((closureTypeInst != NULL) && (wantName == "this"))
  7419. // break;
  7420. if (varDecl->mNameNode == identifierNode)
  7421. {
  7422. BfTypedValue localResult = LoadLocal(varDecl);
  7423. // auto autoComplete = GetAutoComplete();
  7424. // if (identifierNode != NULL)
  7425. // {
  7426. // if (autoComplete != NULL)
  7427. // autoComplete->CheckLocalRef(identifierNode, varDecl);
  7428. // if (((mModule->mCurMethodState->mClosureState == NULL) || (mModule->mCurMethodState->mClosureState->mCapturing)) &&
  7429. // (mModule->mCompiler->mResolvePassData != NULL) && (mModule->mCurMethodInstance != NULL))
  7430. // mModule->mCompiler->mResolvePassData->HandleLocalReference(identifierNode, varDecl->mNameNode, mModule->mCurTypeInstance->mTypeDef, rootMethodState->mMethodInstance->mMethodDef, varDecl->mLocalVarId);
  7431. // }
  7432. //
  7433. if (!isMixinOuterVariablePass)
  7434. {
  7435. mResultLocalVar = varDecl;
  7436. mResultLocalVarRefNode = identifierNode;
  7437. }
  7438. return localResult;
  7439. }
  7440. varDecl = varDecl->mShadowedLocal;
  7441. }
  7442. }
  7443. // Check for the captured locals. It's important we do it here so we get local-first precedence still
  7444. if (closureTypeInst != NULL)
  7445. {
  7446. closureTypeInst->mTypeDef->PopulateMemberSets();
  7447. BfMemberSetEntry* memberSetEntry = NULL;
  7448. if (closureTypeInst->mTypeDef->mFieldSet.TryGetWith(findName, &memberSetEntry))
  7449. {
  7450. auto fieldDef = (BfFieldDef*)memberSetEntry->mMemberDef;
  7451. while (fieldDef != NULL)
  7452. {
  7453. BfIdentifierNode* fieldNameNode = NULL;
  7454. if (fieldDef->mIdx < (int)checkMethodState->mClosureState->mClosureInstanceInfo->mCaptureEntries.size())
  7455. fieldNameNode = checkMethodState->mClosureState->mClosureInstanceInfo->mCaptureEntries[fieldDef->mIdx].mNameNode;
  7456. if (fieldNameNode == identifierNode)
  7457. {
  7458. auto& field = closureTypeInst->mFieldInstances[fieldDef->mIdx];
  7459. if (!field.mResolvedType->IsValuelessType())
  7460. {
  7461. if (mModule->mCurMethodState->mClosureState->mCapturing)
  7462. {
  7463. mModule->mCurMethodState->mClosureState->mReferencedOuterClosureMembers.Add(&field);
  7464. return mModule->GetDefaultTypedValue(field.mResolvedType);
  7465. }
  7466. auto localVar = mModule->mCurMethodState->mLocals[0];
  7467. auto thisValue = localVar->mValue;
  7468. mModule->mBfIRBuilder->PopulateType(localVar->mResolvedType);
  7469. BfTypedValue result = BfTypedValue(mModule->mBfIRBuilder->CreateInBoundsGEP(thisValue, 0, field.mDataIdx), field.mResolvedType, true);
  7470. if (field.mResolvedType->IsRef())
  7471. {
  7472. auto refType = (BfRefType*)field.mResolvedType;
  7473. auto underlyingType = refType->GetUnderlyingType();
  7474. result = BfTypedValue(mModule->mBfIRBuilder->CreateLoad(result.mValue), underlyingType, true);
  7475. }
  7476. else if (fieldDef->mIsReadOnly)
  7477. result = mModule->LoadValue(result);
  7478. mResultLocalVar = localVar;
  7479. mResultLocalVarField = -(field.mMergedDataIdx + 1);
  7480. return result;
  7481. }
  7482. }
  7483. fieldDef = fieldDef->mNextWithSameName;
  7484. }
  7485. }
  7486. }
  7487. if ((checkMethodState->mClosureState != NULL) && (checkMethodState->mClosureState->mCapturing) /*&& (checkMethodState->mClosureState->mIsLocalMethod)*/)
  7488. {
  7489. checkMethodState = checkMethodState->mPrevMethodState;
  7490. continue;
  7491. }
  7492. // Allow local mixin to see outside variables during its processing -- since we don't actually "capture" those into params
  7493. bool isLocalMixinProcessing = false;
  7494. if ((checkMethodState->mClosureState != NULL) && (!checkMethodState->mClosureState->mCapturing) && (closureTypeInst == NULL) &&
  7495. (mModule->mCurMethodInstance->mMethodDef->mMethodType == BfMethodType_Mixin))
  7496. isLocalMixinProcessing = true;
  7497. if (!isLocalMixinProcessing)
  7498. break;
  7499. isMixinOuterVariablePass = true;
  7500. checkMethodState = checkMethodState->mPrevMethodState;
  7501. }
  7502. }
  7503. return BfTypedValue();
  7504. }
  7505. BfTypedValue BfExprEvaluator::DoImplicitArgCapture(BfAstNode* refNode, BfMethodInstance* methodInstance, int paramIdx, bool& failed, BfImplicitParamKind paramKind, const BfTypedValue& methodRefTarget)
  7506. {
  7507. if ((methodRefTarget) && (methodRefTarget.mValue.mId != BfIRValue::ID_IMPLICIT))
  7508. {
  7509. if (methodRefTarget.mType->IsMethodRef())
  7510. {
  7511. BfMethodRefType* methodRefType = (BfMethodRefType*)methodRefTarget.mType;
  7512. BfMethodInstance* methodRefMethodInst = methodRefType->mMethodRef;
  7513. BF_ASSERT(methodRefMethodInst == methodInstance);
  7514. auto paramType = methodInstance->GetParamType(paramIdx);
  7515. int dataIdx = methodRefType->GetDataIdxFromParamIdx(paramIdx);
  7516. if (dataIdx == -1)
  7517. {
  7518. BF_ASSERT(paramType->IsValuelessType());
  7519. return BfTypedValue(mModule->mBfIRBuilder->GetFakeVal(), paramType);
  7520. }
  7521. if (methodRefTarget.IsSplat())
  7522. {
  7523. if (methodRefType->WantsDataPassedAsSplat(dataIdx))
  7524. {
  7525. BF_ASSERT(paramIdx == -1);
  7526. return BfTypedValue(methodRefTarget.mValue, paramType, BfTypedValueKind_SplatHead);
  7527. }
  7528. else
  7529. {
  7530. int splatIdx = dataIdx;
  7531. if (dataIdx > 0)
  7532. {
  7533. if (methodRefType->WantsDataPassedAsSplat(0))
  7534. splatIdx += methodRefType->GetCaptureType(0)->GetSplatCount() - 1;
  7535. }
  7536. bool isAddr = false;
  7537. BfIRValue value = mModule->ExtractSplatValue(methodRefTarget, splatIdx, paramType, &isAddr);
  7538. // We moved the composite load from ExtractSplatValue to here. Hopefully this is correct.
  7539. // 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)
  7540. // if ((paramType->IsComposite()) && (mModule->IsTargetingBeefBackend()))
  7541. // value = mModule->mBfIRBuilder->CreateLoad(value);
  7542. auto lookupVal = BfTypedValue(value, paramType, isAddr);
  7543. if ((isAddr) && (!lookupVal.mType->IsComposite()))
  7544. lookupVal = mModule->LoadValue(lookupVal);
  7545. return lookupVal;
  7546. }
  7547. }
  7548. BF_ASSERT(methodRefTarget.IsAddr());
  7549. if (paramType->IsComposite())
  7550. return BfTypedValue(mModule->mBfIRBuilder->CreateInBoundsGEP(methodRefTarget.mValue, 0, dataIdx), paramType, true);
  7551. return BfTypedValue(mModule->ExtractValue(methodRefTarget, dataIdx), paramType);
  7552. }
  7553. }
  7554. // 'Default' implicit arg lookup, by identifier. May match field (for lambda), or local variable
  7555. if (paramKind == BfImplicitParamKind_General)
  7556. {
  7557. if (paramIdx == -1)
  7558. {
  7559. if (auto delegateBindExpr = BfNodeDynCast<BfDelegateBindExpression>(refNode))
  7560. {
  7561. BfAstNode* thisNode = NULL;
  7562. BfTypedValue thisValue;
  7563. if (auto memberReferenceExpr = BfNodeDynCast<BfMemberReferenceExpression>(delegateBindExpr->mTarget))
  7564. thisNode = memberReferenceExpr->mTarget;
  7565. else if (auto qualifiedNameNode = BfNodeDynCast<BfQualifiedNameNode>(delegateBindExpr->mTarget))
  7566. thisNode = qualifiedNameNode->mLeft;
  7567. else if (auto identifierNode = BfNodeDynCast<BfIdentifierNode>(delegateBindExpr->mTarget))
  7568. {
  7569. // Implicit
  7570. thisValue = mModule->GetThis();
  7571. }
  7572. if (auto thisExpr = BfNodeDynCast<BfExpression>(thisNode))
  7573. {
  7574. thisValue = mModule->CreateValueFromExpression(thisExpr);
  7575. if (!thisValue)
  7576. return BfTypedValue();
  7577. }
  7578. if (thisValue)
  7579. {
  7580. //TODO: handle 'mut', throw error if trying to capture from a non-mut, etc...
  7581. return thisValue;
  7582. }
  7583. }
  7584. }
  7585. String captureName = methodInstance->GetParamName(paramIdx);
  7586. BfIdentifierNode* identifierNode = methodInstance->GetParamNameNode(paramIdx);
  7587. BfTypedValue lookupVal;
  7588. if (identifierNode != NULL)
  7589. {
  7590. lookupVal = DoImplicitArgCapture(refNode, identifierNode);
  7591. }
  7592. else
  7593. {
  7594. lookupVal = LookupIdentifier(NULL, captureName);
  7595. }
  7596. if (lookupVal)
  7597. {
  7598. auto paramType = methodInstance->GetParamType(paramIdx);
  7599. if (paramType->IsRef())
  7600. {
  7601. auto refType = (BfRefType*)paramType;
  7602. if (mResultLocalVar != NULL)
  7603. {
  7604. // When we are capturing, we need to note that we require capturing by reference here
  7605. auto localVar = mResultLocalVar;
  7606. localVar->mWrittenToId = mModule->mCurMethodState->GetRootMethodState()->mCurAccessId++;
  7607. }
  7608. bool isValid = false;
  7609. if ((refType->mRefKind == BfRefType::RefKind_Mut) && (lookupVal.mKind == BfTypedValueKind_MutableValue))
  7610. isValid = true;
  7611. if ((lookupVal.mType->IsRef()) || (lookupVal.IsAddr()))
  7612. isValid = true;
  7613. if (!isValid)
  7614. {
  7615. // Is there another way this can fail than to be in a lambda?
  7616. auto error = mModule->Fail(StrFormat("Method '%s' requires that '%s' be captured by reference. Consider adding by-reference capture specifier [&] to lambda.",
  7617. mModule->MethodToString(methodInstance).c_str(), captureName.c_str()), refNode, true);
  7618. if ((error != NULL) && (methodInstance->mMethodDef->mMethodDeclaration != NULL))
  7619. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("See method declaration"), methodInstance->mMethodDef->GetRefNode());
  7620. failed = true;
  7621. }
  7622. }
  7623. else
  7624. {
  7625. if (lookupVal.mType->IsRef())
  7626. lookupVal = mModule->RemoveRef(lookupVal);
  7627. if (!lookupVal.mType->IsComposite())
  7628. lookupVal = mModule->LoadValue(lookupVal);
  7629. }
  7630. return lookupVal;
  7631. }
  7632. else
  7633. {
  7634. mModule->Fail(StrFormat("Failed to lookup implicit capture '%s'", captureName.c_str()), refNode, true);
  7635. failed = true;
  7636. return BfTypedValue();
  7637. }
  7638. }
  7639. return BfTypedValue();
  7640. }
  7641. void BfExprEvaluator::Visit(BfDelegateBindExpression* delegateBindExpr)
  7642. {
  7643. BfAutoParentNodeEntry autoParentNodeEntry(mModule, delegateBindExpr);
  7644. if (mExpectingType == NULL)
  7645. {
  7646. mModule->Fail("Cannot infer delegate type", delegateBindExpr);
  7647. return;
  7648. }
  7649. BfTokenNode* newToken = NULL;
  7650. BfAllocTarget allocTarget = ResolveAllocTarget(delegateBindExpr->mNewToken, newToken);
  7651. SizedArray<BfTypedValueExpression, 4> typedValueExprs;
  7652. SizedArray<BfExpression*, 4> args;
  7653. BfTypeInstance* delegateTypeInstance = NULL;
  7654. BfMethodInstance* methodInstance = NULL;
  7655. const char* bindTypeName = NULL;
  7656. bool isMethodRefMatch = false;
  7657. if (mExpectingType->IsMethodRef())
  7658. {
  7659. auto methodRefType = (BfMethodRefType*)mExpectingType;
  7660. BF_ASSERT(delegateBindExpr->mNewToken == NULL);
  7661. methodInstance = methodRefType->mMethodRef;
  7662. isMethodRefMatch = true;
  7663. }
  7664. else
  7665. {
  7666. if (mExpectingType->IsGenericParam())
  7667. {
  7668. auto genericParamInstance = mModule->GetGenericParamInstance((BfGenericParamType*)mExpectingType);
  7669. if ((genericParamInstance->mTypeConstraint != NULL) && (genericParamInstance->mTypeConstraint->IsDelegate()))
  7670. {
  7671. delegateTypeInstance = genericParamInstance->mTypeConstraint->ToTypeInstance();
  7672. }
  7673. }
  7674. else
  7675. delegateTypeInstance = mExpectingType->ToTypeInstance();
  7676. if ((delegateTypeInstance == NULL) ||
  7677. ((!delegateTypeInstance->IsDelegate()) && (!delegateTypeInstance->IsFunction())))
  7678. {
  7679. mModule->Fail(StrFormat("Type '%s' cannot be used for method binding. Only delegate or function types are allowed.", mModule->TypeToString(mExpectingType).c_str()), delegateBindExpr);
  7680. return;
  7681. }
  7682. bindTypeName = (delegateTypeInstance->IsDelegate()) ? "delegate" : "function";
  7683. mModule->PopulateType(delegateTypeInstance, BfPopulateType_DataAndMethods);
  7684. methodInstance = mModule->GetRawMethodInstanceAtIdx(delegateTypeInstance, 0, "Invoke");
  7685. if (methodInstance == NULL)
  7686. {
  7687. BF_DBG_FATAL("Invoke not found");
  7688. return;
  7689. }
  7690. if (auto tokenNode = BfNodeDynCast<BfTokenNode>(delegateBindExpr->mNewToken))
  7691. {
  7692. if (delegateTypeInstance->IsFunction())
  7693. mModule->Fail("Function bindings are direct assignments, allocation specifier is not applicable", delegateBindExpr->mNewToken);
  7694. else if (tokenNode->GetToken() == BfToken_Append)
  7695. {
  7696. mModule->Fail("Append allocation on delegate bind not supported", delegateBindExpr->mNewToken);
  7697. }
  7698. }
  7699. }
  7700. typedValueExprs.resize(methodInstance->GetParamCount());
  7701. args.resize(methodInstance->GetParamCount());
  7702. for (int i = 0; i < (int)methodInstance->GetParamCount(); i++)
  7703. {
  7704. auto typedValueExpr = &typedValueExprs[i];
  7705. typedValueExpr->mTypedValue.mValue = BfIRValue(BfIRValueFlags_Value, -1);
  7706. typedValueExpr->mTypedValue.mType = methodInstance->GetParamType(i);
  7707. typedValueExpr->mRefNode = NULL;
  7708. args[i] = typedValueExpr;
  7709. }
  7710. BfSizedArray<ASTREF(BfTypeReference*)>* methodGenericArguments = NULL;
  7711. if (delegateBindExpr->mGenericArgs != NULL)
  7712. methodGenericArguments = &delegateBindExpr->mGenericArgs->mGenericArgs;
  7713. if (delegateBindExpr->mTarget == NULL)
  7714. {
  7715. mModule->AssertErrorState();
  7716. return;
  7717. }
  7718. if (GetAutoComplete() != NULL)
  7719. GetAutoComplete()->CheckNode(delegateBindExpr->mTarget);
  7720. if ((!delegateBindExpr->mTarget->IsA<BfIdentifierNode>()) &&
  7721. (!delegateBindExpr->mTarget->IsA<BfMemberReferenceExpression>()))
  7722. {
  7723. mModule->Fail(StrFormat("Invalid %s binding target, %s can only bind to method references. Consider wrapping expression in a lambda.", bindTypeName, bindTypeName), delegateBindExpr->mTarget);
  7724. mModule->CreateValueFromExpression(delegateBindExpr->mTarget);
  7725. return;
  7726. }
  7727. BfFunctionBindResult bindResult;
  7728. bindResult.mSkipMutCheck = true; // Allow operating on copies
  7729. mFunctionBindResult = &bindResult;
  7730. DoInvocation(delegateBindExpr->mTarget, delegateBindExpr, args, methodGenericArguments);
  7731. mFunctionBindResult = NULL;
  7732. SetMethodElementType(delegateBindExpr->mTarget);
  7733. if (bindResult.mMethodInstance == NULL)
  7734. {
  7735. mResult = BfTypedValue();
  7736. return;
  7737. }
  7738. auto bindMethodInstance = bindResult.mMethodInstance;
  7739. if (isMethodRefMatch)
  7740. {
  7741. // WTF- this was always false, what was it supposed to catch?
  7742. // if (bindMethodInstance != bindResult.mMethodInstance)
  7743. // {
  7744. // mResult = BfTypedValue();
  7745. // return;
  7746. // }
  7747. }
  7748. else
  7749. {
  7750. if (!IsExactMethodMatch(methodInstance, bindMethodInstance, true))
  7751. {
  7752. if (bindResult.mCheckedMultipleMethods)
  7753. {
  7754. mModule->Fail(StrFormat("No overload for '%s' matches %s '%s'", bindMethodInstance->mMethodDef->mName.c_str(), bindTypeName,
  7755. mModule->TypeToString(delegateTypeInstance).c_str()), delegateBindExpr->mTarget);
  7756. }
  7757. else
  7758. {
  7759. mModule->Fail(StrFormat("Method '%s' does not match %s '%s'", mModule->MethodToString(bindMethodInstance).c_str(), bindTypeName,
  7760. mModule->TypeToString(delegateTypeInstance).c_str()), delegateBindExpr->mTarget);
  7761. }
  7762. mResult = BfTypedValue();
  7763. return;
  7764. }
  7765. }
  7766. bool isDirectFunction = false;
  7767. if ((bindResult.mMethodInstance->GetOwner()->IsFunction()) && (bindResult.mFunc))
  7768. isDirectFunction = true;
  7769. if (bindMethodInstance->mIsIntrinsic)
  7770. {
  7771. 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);
  7772. mResult = BfTypedValue();
  7773. return;
  7774. }
  7775. bool hasIncompatibleCallingConventions = !mModule->mSystem->IsCompatibleCallingConvention(methodInstance->mMethodDef->mCallingConvention, bindMethodInstance->mMethodDef->mCallingConvention);
  7776. auto _GetInvokeMethodName = [&]()
  7777. {
  7778. String methodName = "Invoke@";
  7779. methodName += mModule->mCurMethodInstance->mMethodDef->mName;
  7780. int prevSepPos = (int)methodName.LastIndexOf('$');
  7781. if (prevSepPos != -1)
  7782. {
  7783. methodName.RemoveToEnd(prevSepPos);
  7784. }
  7785. auto rootMethodState = mModule->mCurMethodState->GetRootMethodState();
  7786. HashContext hashCtx;
  7787. if (delegateBindExpr->mFatArrowToken != NULL)
  7788. {
  7789. hashCtx.Mixin(delegateBindExpr->mFatArrowToken->GetStartCharId());
  7790. }
  7791. if (rootMethodState->mMethodInstance->mMethodInfoEx != NULL)
  7792. {
  7793. for (auto methodGenericArg : rootMethodState->mMethodInstance->mMethodInfoEx->mMethodGenericArguments)
  7794. {
  7795. StringT<128> genericTypeName;
  7796. BfMangler::Mangle(genericTypeName, mModule->mCompiler->GetMangleKind(), methodGenericArg);
  7797. hashCtx.MixinStr(genericTypeName);
  7798. }
  7799. }
  7800. Val128 hashVal = hashCtx.Finish128();
  7801. methodName += '$';
  7802. methodName += BfTypeUtils::HashEncode64(hashVal.mLow);
  7803. return methodName;
  7804. };
  7805. if ((delegateBindExpr->mNewToken == NULL) || (delegateTypeInstance->IsFunction()))
  7806. {
  7807. if ((mModule->mCurMethodState != NULL) && (mModule->mCurMethodState->mHotDataReferenceBuilder != NULL))
  7808. {
  7809. BF_ASSERT(bindResult.mMethodInstance->mHotMethod != NULL);
  7810. mModule->mCurMethodState->mHotDataReferenceBuilder->mFunctionPtrs.Add(bindResult.mMethodInstance->mHotMethod);
  7811. }
  7812. if (isDirectFunction)
  7813. {
  7814. if (delegateTypeInstance->IsFunction())
  7815. {
  7816. auto intPtrVal = mModule->mBfIRBuilder->CreatePtrToInt(bindResult.mFunc, BfTypeCode_IntPtr);
  7817. mResult = BfTypedValue(intPtrVal, mExpectingType);
  7818. return;
  7819. }
  7820. }
  7821. if (mExpectingType->IsFunction())
  7822. {
  7823. BfIRValue result;
  7824. if ((hasIncompatibleCallingConventions) && (mModule->HasCompiledOutput()))
  7825. {
  7826. //
  7827. {
  7828. SetAndRestoreValue<bool> prevIgnore(mModule->mBfIRBuilder->mIgnoreWrites, true);
  7829. result = mModule->CastToFunction(delegateBindExpr->mTarget, bindResult.mMethodInstance, mExpectingType);
  7830. }
  7831. if (result)
  7832. {
  7833. String methodName = _GetInvokeMethodName();
  7834. SizedArray<BfIRType, 8> irParamTypes;
  7835. BfIRType irReturnType;
  7836. bindMethodInstance->GetIRFunctionInfo(mModule, irReturnType, irParamTypes);
  7837. auto prevActiveFunction = mModule->mBfIRBuilder->GetActiveFunction();
  7838. auto prevInsertBlock = mModule->mBfIRBuilder->GetInsertBlock();
  7839. mModule->mBfIRBuilder->SaveDebugLocation();
  7840. auto funcType = mModule->mBfIRBuilder->CreateFunctionType(irReturnType, irParamTypes);
  7841. auto funcValue = mModule->mBfIRBuilder->CreateFunction(funcType, BfIRLinkageType_External, methodName);
  7842. auto srcCallingConv = mModule->GetCallingConvention(methodInstance->GetOwner(), methodInstance->mMethodDef);
  7843. mModule->mBfIRBuilder->SetFuncCallingConv(funcValue, srcCallingConv);
  7844. mModule->mBfIRBuilder->SetActiveFunction(funcValue);
  7845. auto entryBlock = mModule->mBfIRBuilder->CreateBlock("entry", true);
  7846. mModule->mBfIRBuilder->SetInsertPoint(entryBlock);
  7847. SizedArray<BfIRValue, 8> irArgs;
  7848. for (int paramIdx = 0; paramIdx < irParamTypes.size(); paramIdx++)
  7849. {
  7850. irArgs.push_back(mModule->mBfIRBuilder->GetArgument(paramIdx));
  7851. }
  7852. auto bindFuncVal = bindResult.mFunc;
  7853. if (mModule->mCompiler->mOptions.mAllowHotSwapping)
  7854. bindFuncVal = mModule->mBfIRBuilder->RemapBindFunction(bindFuncVal);
  7855. auto callResult = mModule->mBfIRBuilder->CreateCall(bindFuncVal, irArgs);
  7856. auto destCallingConv = mModule->GetCallingConvention(bindMethodInstance->GetOwner(), bindMethodInstance->mMethodDef);
  7857. if (destCallingConv != BfIRCallingConv_CDecl)
  7858. mModule->mBfIRBuilder->SetCallCallingConv(callResult, destCallingConv);
  7859. if (methodInstance->mReturnType->IsValuelessType())
  7860. mModule->mBfIRBuilder->CreateRetVoid();
  7861. else
  7862. mModule->mBfIRBuilder->CreateRet(callResult);
  7863. mModule->mBfIRBuilder->SetActiveFunction(prevActiveFunction);
  7864. mModule->mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  7865. mModule->mBfIRBuilder->RestoreDebugLocation();
  7866. result = mModule->mBfIRBuilder->CreatePtrToInt(funcValue, BfTypeCode_IntPtr);
  7867. }
  7868. }
  7869. else
  7870. {
  7871. result = mModule->CastToFunction(delegateBindExpr->mTarget, bindResult.mMethodInstance, mExpectingType);
  7872. }
  7873. if (result)
  7874. mResult = BfTypedValue(result, mExpectingType);
  7875. return;
  7876. }
  7877. auto methodRefType = mModule->CreateMethodRefType(bindResult.mMethodInstance);
  7878. mModule->AddDependency(methodRefType, mModule->mCurTypeInstance, BfDependencyMap::DependencyFlag_Calls);
  7879. mModule->AddCallDependency(bindResult.mMethodInstance);
  7880. if ((bindResult.mOrigTarget) && (bindResult.mOrigTarget.mType->IsMethodRef()))
  7881. {
  7882. mResult = bindResult.mOrigTarget;
  7883. }
  7884. else
  7885. {
  7886. if ((bindResult.mMethodInstance->mMethodDef->mIsLocalMethod) || (!bindResult.mTarget))
  7887. mResult = BfTypedValue(BfIRValue(BfIRValueFlags_Value, BfIRValue::ID_IMPLICIT), methodRefType);
  7888. else
  7889. {
  7890. auto methodRefPtr = mModule->CreateAlloca(methodRefType, "bindResult");
  7891. auto elemPtr = mModule->mBfIRBuilder->CreateInBoundsGEP(methodRefPtr, 0, 0);
  7892. BfTypedValue target;
  7893. if (bindResult.mTarget.IsSplat())
  7894. target = mModule->AggregateSplat(bindResult.mTarget, &bindResult.mIRArgs[0]);
  7895. else
  7896. target = mModule->LoadValue(bindResult.mTarget);
  7897. mModule->mBfIRBuilder->CreateStore(target.mValue, elemPtr);
  7898. mResult = BfTypedValue(methodRefPtr, methodRefType, true);
  7899. }
  7900. }
  7901. return;
  7902. }
  7903. int implicitParamCount = bindMethodInstance->GetImplicitParamCount();
  7904. BfTypeInstance* useTypeInstance = delegateTypeInstance;
  7905. BfClosureType* closureTypeInst = NULL;
  7906. auto origTarget = bindResult.mOrigTarget;
  7907. auto target = bindResult.mTarget;
  7908. BfTypedValue methodRefTarget;
  7909. if ((bindResult.mOrigTarget) && (bindResult.mOrigTarget.mType->IsMethodRef()))
  7910. methodRefTarget = bindResult.mOrigTarget;
  7911. bool isStructTarget = (target) && (target.mType->IsStruct());
  7912. bool bindCapturesThis = bindMethodInstance->HasThis() && !isStructTarget;
  7913. bool needsSplat = (isStructTarget) && (!bindMethodInstance->mMethodDef->mIsMutating) && (!bindMethodInstance->mMethodDef->mNoSplat);
  7914. bool captureThisByValue = isStructTarget;
  7915. if (bindMethodInstance->mMethodDef->mIsLocalMethod)
  7916. {
  7917. // Local method captures always capture 'this' by reference
  7918. captureThisByValue = false;
  7919. }
  7920. if ((origTarget.mType != NULL) &&
  7921. ((origTarget.mType->IsRef()) || (origTarget.mType->IsPointer())))
  7922. {
  7923. captureThisByValue = false;
  7924. }
  7925. if (methodRefTarget)
  7926. BF_ASSERT(methodRefTarget.mType->IsMethodRef());
  7927. if (target.IsSplat())
  7928. target = mModule->AggregateSplat(target, &bindResult.mIRArgs[0]);
  7929. bool hasCaptures = false;
  7930. // Do we need a special delegate type for this?
  7931. if (((captureThisByValue) || (needsSplat) || (implicitParamCount > 0) /*|| (hasIncompatibleCallingConventions)*/) &&
  7932. (mModule->HasCompiledOutput()))
  7933. {
  7934. hasCaptures = true;
  7935. auto curProject = mModule->mCurTypeInstance->mTypeDef->mProject;
  7936. if (captureThisByValue)
  7937. target = mModule->LoadValue(target);
  7938. String delegateTypeName = mModule->TypeToString(delegateTypeInstance);
  7939. HashContext hashCtx;
  7940. hashCtx.MixinStr(delegateTypeName);
  7941. // We mix in the project for reasons described in the lambda binding handler
  7942. hashCtx.MixinStr(curProject->mName);
  7943. String structTargetTypeName;
  7944. String structTargetName;
  7945. // Implicit param separator
  7946. for (int implicitParamIdx = bindMethodInstance->HasThis() ? - 1 : 0; implicitParamIdx < implicitParamCount; implicitParamIdx++)
  7947. {
  7948. auto paramType = bindResult.mMethodInstance->GetParamType(implicitParamIdx);
  7949. if ((implicitParamIdx == -1) && (captureThisByValue))
  7950. {
  7951. if (paramType->IsPointer())
  7952. paramType = paramType->GetUnderlyingType();
  7953. }
  7954. structTargetTypeName = mModule->TypeToString(paramType);
  7955. structTargetName = bindResult.mMethodInstance->GetParamName(implicitParamIdx);
  7956. hashCtx.MixinStr(structTargetTypeName);
  7957. hashCtx.MixinStr(structTargetName);
  7958. }
  7959. Val128 hash128 = hashCtx.Finish128();
  7960. BfClosureType* checkClosureType = new BfClosureType(delegateTypeInstance, hash128);
  7961. checkClosureType->mContext = mModule->mContext;
  7962. checkClosureType->mBaseType = delegateTypeInstance;
  7963. BfType* resolvedClosureType = mModule->ResolveType(checkClosureType, BfPopulateType_Identity);
  7964. closureTypeInst = (BfClosureType*)resolvedClosureType;
  7965. if (checkClosureType == resolvedClosureType)
  7966. {
  7967. // This is a new closure type
  7968. closureTypeInst->Init(curProject);
  7969. for (int implicitParamIdx = bindMethodInstance->HasThis() ? -1 : 0; implicitParamIdx < implicitParamCount; implicitParamIdx++)
  7970. {
  7971. String fieldName = bindResult.mMethodInstance->GetParamName(implicitParamIdx);
  7972. BfType* paramType = bindResult.mMethodInstance->GetParamType(implicitParamIdx);
  7973. if ((implicitParamIdx == -1) && (captureThisByValue))
  7974. {
  7975. if (paramType->IsPointer())
  7976. paramType = paramType->GetUnderlyingType();
  7977. }
  7978. if (fieldName == "this")
  7979. fieldName = "__this";
  7980. closureTypeInst->AddField(paramType, fieldName);
  7981. }
  7982. closureTypeInst->Finish();
  7983. mModule->PopulateType(resolvedClosureType, BfPopulateType_Declaration);
  7984. }
  7985. else
  7986. {
  7987. // Already had this entry
  7988. delete checkClosureType;
  7989. }
  7990. useTypeInstance = closureTypeInst;
  7991. }
  7992. mModule->PopulateType(useTypeInstance);
  7993. if (delegateBindExpr->mTarget == NULL)
  7994. {
  7995. mModule->AssertErrorState();
  7996. return;
  7997. }
  7998. mResult = BfTypedValue(mModule->AllocFromType(useTypeInstance, allocTarget, BfIRValue(), BfIRValue(), 0, BfAllocFlags_None), useTypeInstance);
  7999. // Do we need specialized calling code for this?
  8000. BfIRValue funcValue;
  8001. if (((needsSplat) || (implicitParamCount > 0) || (hasIncompatibleCallingConventions)) &&
  8002. (mModule->HasCompiledOutput()))
  8003. {
  8004. int fieldIdx = 0;
  8005. for (int implicitParamIdx = bindMethodInstance->HasThis() ? -1 : 0; implicitParamIdx < implicitParamCount; implicitParamIdx++)
  8006. {
  8007. auto fieldInst = &useTypeInstance->mFieldInstances[fieldIdx];
  8008. int gepIdx = fieldInst->mDataIdx;
  8009. auto fieldPtr = mModule->mBfIRBuilder->CreateInBoundsGEP(mResult.mValue, 0, gepIdx);
  8010. auto fieldType = bindMethodInstance->GetParamType(implicitParamIdx);
  8011. if ((implicitParamIdx == -1) && (captureThisByValue))
  8012. {
  8013. if (fieldType->IsPointer())
  8014. fieldType = fieldType->GetUnderlyingType();
  8015. }
  8016. bool failed = false;
  8017. BfTypedValue lookupVal;
  8018. if (implicitParamIdx == -1)
  8019. lookupVal = target;
  8020. else
  8021. lookupVal = DoImplicitArgCapture(delegateBindExpr->mTarget, bindResult.mMethodInstance, implicitParamIdx, failed, BfImplicitParamKind_General, methodRefTarget);
  8022. if (!lookupVal)
  8023. continue;
  8024. if ((fieldType->IsPointer()) && (lookupVal.mType != fieldType))
  8025. {
  8026. BF_ASSERT(fieldType->GetUnderlyingType() == lookupVal.mType);
  8027. BF_ASSERT(lookupVal.IsAddr());
  8028. }
  8029. else if (!fieldType->IsRef())
  8030. lookupVal = mModule->LoadOrAggregateValue(lookupVal);
  8031. if (lookupVal)
  8032. mModule->mBfIRBuilder->CreateStore(lookupVal.mValue, fieldPtr);
  8033. fieldIdx++;
  8034. }
  8035. String methodName = _GetInvokeMethodName();
  8036. SizedArray<BfIRType, 8> irParamTypes;
  8037. BfIRType irReturnType;
  8038. bool hasThis = false;
  8039. if (hasCaptures)
  8040. {
  8041. hasThis = true;
  8042. methodInstance->GetIRFunctionInfo(mModule, irReturnType, irParamTypes);
  8043. irParamTypes[0] = mModule->mBfIRBuilder->MapType(useTypeInstance);
  8044. }
  8045. else
  8046. {
  8047. BF_ASSERT(hasIncompatibleCallingConventions);
  8048. bindMethodInstance->GetIRFunctionInfo(mModule, irReturnType, irParamTypes);
  8049. hasThis = bindMethodInstance->HasThis();
  8050. }
  8051. auto prevActiveFunction = mModule->mBfIRBuilder->GetActiveFunction();
  8052. auto prevInsertBlock = mModule->mBfIRBuilder->GetInsertBlock();
  8053. mModule->mBfIRBuilder->SaveDebugLocation();
  8054. auto funcType = mModule->mBfIRBuilder->CreateFunctionType(irReturnType, irParamTypes);
  8055. funcValue = mModule->mBfIRBuilder->CreateFunction(funcType, BfIRLinkageType_External, methodName);
  8056. auto srcCallingConv = mModule->GetCallingConvention(methodInstance->GetOwner(), methodInstance->mMethodDef);
  8057. if ((!hasThis) && (methodInstance->mMethodDef->mCallingConvention == BfCallingConvention_Stdcall))
  8058. srcCallingConv = BfIRCallingConv_StdCall;
  8059. mModule->mBfIRBuilder->SetFuncCallingConv(funcValue, srcCallingConv);
  8060. mModule->mBfIRBuilder->SetActiveFunction(funcValue);
  8061. auto entryBlock = mModule->mBfIRBuilder->CreateBlock("entry", true);
  8062. mModule->mBfIRBuilder->SetInsertPoint(entryBlock);
  8063. fieldIdx = 0;
  8064. SizedArray<BfIRValue, 8> irArgs;
  8065. for (int implicitParamIdx = bindMethodInstance->HasThis() ? -1 : 0; implicitParamIdx < implicitParamCount; implicitParamIdx++)
  8066. {
  8067. auto fieldInst = &useTypeInstance->mFieldInstances[fieldIdx];
  8068. int gepIdx = fieldInst->mDataIdx;
  8069. auto fieldType = bindMethodInstance->GetParamType(implicitParamIdx);
  8070. bool disableSplat = false;
  8071. if ((implicitParamIdx == -1) && (captureThisByValue))
  8072. {
  8073. if (fieldType->IsPointer())
  8074. {
  8075. fieldType = fieldType->GetUnderlyingType();
  8076. disableSplat = true;
  8077. }
  8078. }
  8079. auto fieldPtr = mModule->mBfIRBuilder->CreateInBoundsGEP(mModule->mBfIRBuilder->GetArgument(0), 0, gepIdx);
  8080. BfTypedValue typedVal(fieldPtr, fieldType, true);
  8081. PushArg(typedVal, irArgs, disableSplat);
  8082. fieldIdx++;
  8083. }
  8084. int argIdx = hasThis ? 1 : 0;
  8085. for (int paramIdx = 0; paramIdx < methodInstance->GetParamCount(); paramIdx++)
  8086. {
  8087. auto paramType = methodInstance->GetParamType(paramIdx);
  8088. if (paramType->IsSplattable())
  8089. {
  8090. BfTypeUtils::SplatIterate([&](BfType* checkType) { irArgs.push_back(mModule->mBfIRBuilder->GetArgument(argIdx++)); }, paramType);
  8091. }
  8092. else if (!paramType->IsValuelessType())
  8093. {
  8094. irArgs.push_back(mModule->mBfIRBuilder->GetArgument(argIdx++));
  8095. }
  8096. }
  8097. auto bindFuncVal = bindResult.mFunc;
  8098. if (mModule->mCompiler->mOptions.mAllowHotSwapping)
  8099. bindFuncVal = mModule->mBfIRBuilder->RemapBindFunction(bindFuncVal);
  8100. auto result = mModule->mBfIRBuilder->CreateCall(bindFuncVal, irArgs);
  8101. auto destCallingConv = mModule->GetCallingConvention(bindMethodInstance->GetOwner(), bindMethodInstance->mMethodDef);
  8102. if (destCallingConv != BfIRCallingConv_CDecl)
  8103. mModule->mBfIRBuilder->SetCallCallingConv(result, destCallingConv);
  8104. if (methodInstance->mReturnType->IsValuelessType())
  8105. {
  8106. mModule->mBfIRBuilder->CreateRetVoid();
  8107. }
  8108. else
  8109. {
  8110. mModule->mBfIRBuilder->CreateRet(result);
  8111. }
  8112. mModule->mBfIRBuilder->SetActiveFunction(prevActiveFunction);
  8113. mModule->mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  8114. mModule->mBfIRBuilder->RestoreDebugLocation();
  8115. }
  8116. else if ((closureTypeInst != NULL) && (captureThisByValue))
  8117. {
  8118. // 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
  8119. auto fieldPtr = mModule->mBfIRBuilder->CreateInBoundsGEP(mResult.mValue, 0, 1);
  8120. target = mModule->LoadValue(target);
  8121. mModule->mBfIRBuilder->CreateStore(target.mValue, fieldPtr);
  8122. target = BfTypedValue(fieldPtr, target.mType, true);
  8123. }
  8124. BfResolvedArgs resolvedArgs;
  8125. MatchConstructor(delegateBindExpr, delegateBindExpr, mResult, useTypeInstance, resolvedArgs, false, false);
  8126. auto baseDelegateType = VerifyBaseDelegateType(delegateTypeInstance->mBaseType);
  8127. auto baseDelegate = mModule->mBfIRBuilder->CreateBitCast(mResult.mValue, mModule->mBfIRBuilder->MapType(baseDelegateType, BfIRPopulateType_Full));
  8128. // >> delegate.mTarget = bindResult.mTarget
  8129. BfIRValue valPtr;
  8130. if (mModule->HasCompiledOutput())
  8131. {
  8132. if ((implicitParamCount > 0) || (needsSplat)) // Point back to self, it contains capture data
  8133. valPtr = mModule->mBfIRBuilder->CreateBitCast(mResult.mValue, mModule->mBfIRBuilder->GetPrimitiveType(BfTypeCode_NullPtr));
  8134. else if (bindResult.mTarget)
  8135. valPtr = mModule->mBfIRBuilder->CreateBitCast(target.mValue, mModule->mBfIRBuilder->GetPrimitiveType(BfTypeCode_NullPtr));
  8136. else
  8137. valPtr = mModule->GetDefaultValue(mModule->GetPrimitiveType(BfTypeCode_NullPtr));
  8138. auto fieldPtr = mModule->mBfIRBuilder->CreateInBoundsGEP(baseDelegate, 0, 2);
  8139. mModule->mBfIRBuilder->CreateStore(valPtr, fieldPtr);
  8140. }
  8141. if (!funcValue)
  8142. {
  8143. funcValue = bindResult.mFunc;
  8144. if (!funcValue)
  8145. {
  8146. if ((mModule->HasCompiledOutput()) && (!mModule->mBfIRBuilder->mIgnoreWrites))
  8147. mModule->AssertErrorState();
  8148. return;
  8149. }
  8150. if ((mModule->mCompiler->mOptions.mAllowHotSwapping) && (!bindResult.mMethodInstance->mMethodDef->mIsVirtual))
  8151. {
  8152. funcValue = mModule->mBfIRBuilder->RemapBindFunction(funcValue);
  8153. }
  8154. }
  8155. // >> delegate.mFuncPtr = bindResult.mFunc
  8156. auto nullPtrType = mModule->GetPrimitiveType(BfTypeCode_NullPtr);
  8157. valPtr = mModule->mBfIRBuilder->CreateBitCast(funcValue, mModule->mBfIRBuilder->MapType(nullPtrType));
  8158. auto fieldPtr = mModule->mBfIRBuilder->CreateInBoundsGEP(baseDelegate, 0, 1);
  8159. mModule->mBfIRBuilder->CreateStore(valPtr, fieldPtr);
  8160. }
  8161. void BfExprEvaluator::VisitLambdaBodies(BfAstNode* body, BfFieldDtorDeclaration* fieldDtor)
  8162. {
  8163. if (auto blockBody = BfNodeDynCast<BfBlock>(body))
  8164. mModule->VisitChild(blockBody);
  8165. else if (auto bodyExpr = BfNodeDynCast<BfExpression>(body))
  8166. mModule->CreateValueFromExpression(bodyExpr);
  8167. while (fieldDtor != NULL)
  8168. {
  8169. mModule->VisitChild(fieldDtor->mBody);
  8170. fieldDtor = fieldDtor->mNextFieldDtor;
  8171. }
  8172. }
  8173. BfLambdaInstance* BfExprEvaluator::GetLambdaInstance(BfLambdaBindExpression* lambdaBindExpr, BfAllocTarget& allocTarget)
  8174. {
  8175. auto rootMethodState = mModule->mCurMethodState->GetRootMethodState();
  8176. BfLambdaInstance* lambdaInstance = NULL;
  8177. if (rootMethodState->mLambdaCache.TryGetValue(lambdaBindExpr, &lambdaInstance))
  8178. return lambdaInstance;
  8179. static int sBindCount = 0;
  8180. sBindCount++;
  8181. bool isFunctionBind = false;
  8182. BfTypeInstance* delegateTypeInstance = NULL;
  8183. BfMethodInstance* invokeMethodInstance = NULL;
  8184. if (mExpectingType == NULL)
  8185. {
  8186. mModule->Fail("Cannot infer delegate type", lambdaBindExpr);
  8187. delegateTypeInstance = mModule->mContext->mBfObjectType;
  8188. }
  8189. else
  8190. {
  8191. delegateTypeInstance = mExpectingType->ToTypeInstance();
  8192. if ((delegateTypeInstance == NULL) ||
  8193. ((!delegateTypeInstance->mTypeDef->mIsDelegate) && (!delegateTypeInstance->mTypeDef->mIsFunction)))
  8194. {
  8195. if (lambdaBindExpr->mFatArrowToken != NULL)
  8196. mModule->Fail("Can only bind lambdas to delegate types", lambdaBindExpr->mFatArrowToken);
  8197. delegateTypeInstance = mModule->mContext->mBfObjectType;
  8198. }
  8199. else
  8200. {
  8201. invokeMethodInstance = mModule->GetRawMethodInstanceAtIdx(delegateTypeInstance, 0, "Invoke");
  8202. }
  8203. isFunctionBind = delegateTypeInstance->mTypeDef->mIsFunction;
  8204. }
  8205. if (auto tokenNode = BfNodeDynCast<BfTokenNode>(lambdaBindExpr->mNewToken))
  8206. {
  8207. if (isFunctionBind)
  8208. {
  8209. mModule->Fail("Function lambda binding does not require allocation", lambdaBindExpr->mNewToken);
  8210. }
  8211. else if (tokenNode->GetToken() == BfToken_Append)
  8212. {
  8213. mModule->Fail("Append allocation on delegate bind not supported", lambdaBindExpr->mNewToken);
  8214. }
  8215. }
  8216. if (invokeMethodInstance != NULL)
  8217. {
  8218. if ((int)lambdaBindExpr->mParams.size() < invokeMethodInstance->GetParamCount())
  8219. {
  8220. BfAstNode* refNode = lambdaBindExpr->mCloseParen;
  8221. if (refNode == NULL)
  8222. refNode = lambdaBindExpr;
  8223. mModule->Fail(StrFormat("Not enough parameters for delegate type '%s'. Expected %d more.",
  8224. mModule->TypeToString(delegateTypeInstance).c_str(), invokeMethodInstance->GetParamCount() - lambdaBindExpr->mParams.size()), refNode);
  8225. }
  8226. else if ((int)lambdaBindExpr->mParams.size() > invokeMethodInstance->GetParamCount())
  8227. {
  8228. BfAstNode* refNode = lambdaBindExpr->mParams[invokeMethodInstance->GetParamCount()];
  8229. mModule->Fail(StrFormat("Too many parameters for delegate type '%s'. Expected %d fewer.",
  8230. mModule->TypeToString(delegateTypeInstance).c_str(), lambdaBindExpr->mParams.size() - invokeMethodInstance->GetParamCount()), refNode);
  8231. }
  8232. }
  8233. auto autoComplete = GetAutoComplete();
  8234. bool wasCapturingMethodInfo = false;
  8235. if ((autoComplete != NULL) && (invokeMethodInstance != NULL))
  8236. {
  8237. wasCapturingMethodInfo = autoComplete->mIsCapturingMethodMatchInfo;
  8238. autoComplete->CheckInvocation(lambdaBindExpr, lambdaBindExpr->mOpenParen, lambdaBindExpr->mCloseParen, lambdaBindExpr->mCommas);
  8239. if (autoComplete->mIsCapturingMethodMatchInfo)
  8240. {
  8241. autoComplete->mMethodMatchInfo->mInstanceList.Clear();
  8242. auto methodMatchInfo = autoComplete->mMethodMatchInfo;
  8243. BfAutoComplete::MethodMatchEntry methodMatchEntry;
  8244. methodMatchEntry.mTypeInstance = invokeMethodInstance->GetOwner();
  8245. methodMatchEntry.mCurMethodInstance = mModule->mCurMethodInstance;
  8246. methodMatchEntry.mMethodDef = invokeMethodInstance->mMethodDef;
  8247. autoComplete->mMethodMatchInfo->mInstanceList.push_back(methodMatchEntry);
  8248. methodMatchInfo->mBestIdx = 0;
  8249. methodMatchInfo->mMostParamsMatched = 0;
  8250. int cursorIdx = lambdaBindExpr->GetParser()->mCursorIdx;
  8251. if ((lambdaBindExpr->mCloseParen == NULL) || (cursorIdx <= lambdaBindExpr->mCloseParen->GetSrcStart()))
  8252. {
  8253. int paramIdx = 0;
  8254. for (int commaIdx = 0; commaIdx < (int)lambdaBindExpr->mCommas.size(); commaIdx++)
  8255. {
  8256. auto commaNode = lambdaBindExpr->mCommas[commaIdx];
  8257. if ((commaNode != NULL) && (cursorIdx >= commaNode->GetSrcStart()))
  8258. paramIdx = commaIdx + 1;
  8259. }
  8260. bool isEmpty = true;
  8261. if (paramIdx < (int)lambdaBindExpr->mParams.size())
  8262. {
  8263. auto paramNode = lambdaBindExpr->mParams[paramIdx];
  8264. if (paramNode != NULL)
  8265. isEmpty = false;
  8266. }
  8267. if (isEmpty)
  8268. {
  8269. if (paramIdx < (int)invokeMethodInstance->GetParamCount())
  8270. {
  8271. String paramName = invokeMethodInstance->GetParamName(paramIdx);
  8272. autoComplete->mEntriesSet.Clear();
  8273. autoComplete->AddEntry(AutoCompleteEntry("paramName", paramName));
  8274. autoComplete->mInsertStartIdx = cursorIdx;
  8275. autoComplete->mInsertEndIdx = cursorIdx;
  8276. if ((paramIdx == 0) && (lambdaBindExpr->mParams.IsEmpty()))
  8277. {
  8278. String totalNames;
  8279. for (int checkIdx = 0; checkIdx < (int)invokeMethodInstance->GetParamCount(); checkIdx++)
  8280. {
  8281. if (!totalNames.IsEmpty())
  8282. totalNames += ", ";
  8283. totalNames += invokeMethodInstance->GetParamName(checkIdx);
  8284. }
  8285. autoComplete->AddEntry(AutoCompleteEntry("paramNames", totalNames));
  8286. }
  8287. }
  8288. }
  8289. }
  8290. }
  8291. }
  8292. defer
  8293. (
  8294. {
  8295. if (autoComplete != NULL)
  8296. autoComplete->mIsCapturingMethodMatchInfo = (wasCapturingMethodInfo) && (!autoComplete->mIsCapturingMethodMatchInfo);
  8297. }
  8298. );
  8299. if (lambdaBindExpr->mBody == NULL)
  8300. {
  8301. mModule->AssertErrorState();
  8302. return NULL;
  8303. }
  8304. if ((lambdaBindExpr->mNewToken == NULL) || (isFunctionBind))
  8305. {
  8306. if ((lambdaBindExpr->mNewToken != NULL) && (isFunctionBind))
  8307. mModule->Fail("Binds to functions should do not require allocations.", lambdaBindExpr->mNewToken);
  8308. if (lambdaBindExpr->mDtor != NULL)
  8309. {
  8310. mModule->Fail("Valueless method reference cannot contain destructor. Consider either removing destructor or using an allocated lambda.", lambdaBindExpr->mDtor->mTildeToken);
  8311. // Eat it
  8312. auto fieldDtor = lambdaBindExpr->mDtor;
  8313. while (fieldDtor != NULL)
  8314. {
  8315. mModule->VisitEmbeddedStatement(fieldDtor->mBody);
  8316. fieldDtor = fieldDtor->mNextFieldDtor;
  8317. }
  8318. }
  8319. if (invokeMethodInstance != NULL)
  8320. {
  8321. BfLocalMethod* localMethod = new BfLocalMethod();
  8322. localMethod->mMethodName = "anon";
  8323. localMethod->mSystem = mModule->mSystem;
  8324. localMethod->mModule = mModule;
  8325. localMethod->mExpectedFullName = mModule->GetLocalMethodName(localMethod->mMethodName, lambdaBindExpr->mFatArrowToken, mModule->mCurMethodState, mModule->mCurMethodState->mMixinState);
  8326. localMethod->mLambdaInvokeMethodInstance = invokeMethodInstance;
  8327. localMethod->mLambdaBindExpr = lambdaBindExpr;
  8328. localMethod->mDeclMethodState = mModule->mCurMethodState;
  8329. mModule->mContext->mLocalMethodGraveyard.push_back(localMethod);
  8330. auto moduleMethodInstance = mModule->GetLocalMethodInstance(localMethod, BfTypeVector());
  8331. auto methodRefType = mModule->CreateMethodRefType(moduleMethodInstance.mMethodInstance);
  8332. mModule->AddDependency(methodRefType, mModule->mCurTypeInstance, BfDependencyMap::DependencyFlag_Calls);
  8333. mModule->AddCallDependency(moduleMethodInstance.mMethodInstance);
  8334. mResult = BfTypedValue(BfIRValue(BfIRValueFlags_Value, BfIRValue::ID_IMPLICIT), methodRefType);
  8335. return NULL;
  8336. }
  8337. }
  8338. //SetAndRestoreValue<bool> prevIgnoreIRWrites(mModule->mBfIRBuilder->mIgnoreWrites, mModule->mWantsIRIgnoreWrites);
  8339. SetAndRestoreValue<bool> prevIgnoreIRWrites(mModule->mBfIRBuilder->mIgnoreWrites, mModule->mWantsIRIgnoreWrites || mModule->mCurMethodInstance->mIsUnspecialized);
  8340. BfTypeInstance* outerClosure = NULL;
  8341. if ((mModule->mCurMethodState->mClosureState != NULL) && (!mModule->mCurMethodState->mClosureState->mCapturing))
  8342. outerClosure = mModule->mCurMethodState->mClosureState->mClosureType;
  8343. Val128 val128(delegateTypeInstance->mTypeId);
  8344. BfMethodState methodState;
  8345. methodState.mPrevMethodState = mModule->mCurMethodState;
  8346. BfIRFunctionType funcType;
  8347. auto voidType = mModule->GetPrimitiveType(BfTypeCode_None);
  8348. SizedArray<BfIRType, 0> paramTypes;
  8349. funcType = mModule->mBfIRBuilder->CreateFunctionType(mModule->mBfIRBuilder->MapType(voidType), paramTypes, false);
  8350. auto prevInsertBlock = mModule->mBfIRBuilder->GetInsertBlock();
  8351. BF_ASSERT(prevInsertBlock);
  8352. auto prevActiveFunction = mModule->mBfIRBuilder->GetActiveFunction();
  8353. mModule->mBfIRBuilder->SaveDebugLocation();
  8354. SetAndRestoreValue<bool> prevIgnoreWrites(mModule->mBfIRBuilder->mIgnoreWrites, true);
  8355. BfDeferredLocalAssignData deferredLocalAssignData;
  8356. if (mModule->mCurMethodState->mDeferredLocalAssignData != NULL)
  8357. deferredLocalAssignData.ExtendFrom(mModule->mCurMethodState->mDeferredLocalAssignData);
  8358. SetAndRestoreValue<BfMethodState*> prevMethodState(mModule->mCurMethodState, &methodState);
  8359. methodState.mIRHeadBlock = mModule->mBfIRBuilder->CreateBlock("head", true);
  8360. methodState.mIRInitBlock = mModule->mBfIRBuilder->CreateBlock("init", true);
  8361. methodState.mIREntryBlock = mModule->mBfIRBuilder->CreateBlock("entry", true);
  8362. methodState.mCurScope->mDIScope = prevMethodState.mPrevVal->mCurScope->mDIScope;//invokeMethodInstance->mDIFunction;
  8363. methodState.mCurLocalVarId = -1;
  8364. methodState.mIRFunction = prevMethodState.mPrevVal->mIRFunction;
  8365. methodState.mDeferredLocalAssignData = &deferredLocalAssignData;
  8366. mModule->mBfIRBuilder->SetInsertPoint(methodState.mIREntryBlock);
  8367. BfClosureState closureState;
  8368. if (delegateTypeInstance->IsDelegate())
  8369. closureState.mReturnType = mModule->GetDelegateReturnType(delegateTypeInstance);
  8370. else
  8371. closureState.mReturnType = mModule->mContext->mBfObjectType;
  8372. closureState.mCapturing = true;
  8373. closureState.mDeclaringMethodIsMutating = mModule->mCurMethodInstance->mMethodDef->mIsMutating;
  8374. methodState.mClosureState = &closureState;
  8375. closureState.mClosureType = outerClosure;
  8376. BF_ASSERT(methodState.mCurLocalVarId == -1);
  8377. int outerLocalsCount = (int)methodState.mLocals.size();
  8378. // static int sItrCount = 0;
  8379. // ++sItrCount;
  8380. // int itrCount = sItrCount;
  8381. // if ((itrCount == 8) || (itrCount == 10))
  8382. // {
  8383. // NOP;
  8384. // }
  8385. String delegateTypeName = mModule->TypeToString(delegateTypeInstance);
  8386. HashContext hashCtx;
  8387. hashCtx.MixinStr(delegateTypeName);
  8388. BfSource* bfSource = delegateTypeInstance->mTypeDef->mSource;
  8389. BfMethodDef* methodDef = new BfMethodDef();
  8390. methodDef->mDeclaringType = mModule->mCurMethodInstance->mMethodDef->mDeclaringType;
  8391. Val128 closureMethodHash;
  8392. OwnedVector<BfParameterDeclaration> tempParamDecls;
  8393. if ((autoComplete != NULL) && (autoComplete->mMethodMatchInfo != NULL) && (autoComplete->IsAutocompleteNode(lambdaBindExpr->mBody)))
  8394. {
  8395. // Don't show outer method match info when our cursor is inside a lambda expression (being passed as a parameter)
  8396. autoComplete->RemoveMethodMatchInfo();
  8397. }
  8398. if (invokeMethodInstance != NULL)
  8399. {
  8400. for (int paramIdx = 0; paramIdx < (int)invokeMethodInstance->mMethodDef->mParams.size(); paramIdx++)
  8401. {
  8402. auto invokeParamDef = invokeMethodInstance->mMethodDef->mParams[paramIdx];
  8403. BfParameterDef* paramDef = new BfParameterDef();
  8404. paramDef->mParamDeclaration = tempParamDecls.Alloc();
  8405. BfLocalVariable* localVar = new BfLocalVariable();
  8406. if (paramIdx < (int)lambdaBindExpr->mParams.size())
  8407. {
  8408. localVar->mName = lambdaBindExpr->mParams[paramIdx]->ToString();
  8409. localVar->mNameNode = lambdaBindExpr->mParams[paramIdx];
  8410. paramDef->mParamDeclaration->mNameNode = lambdaBindExpr->mParams[paramIdx];
  8411. }
  8412. else
  8413. {
  8414. mModule->AssertErrorState();
  8415. localVar->mName = invokeParamDef->mName;
  8416. paramDef->mParamDeclaration->mNameNode = NULL;
  8417. }
  8418. paramDef->mName = localVar->mName;
  8419. methodDef->mParams.push_back(paramDef);
  8420. localVar->mResolvedType = invokeMethodInstance->GetParamType(paramIdx);
  8421. localVar->mIsAssigned = true;
  8422. localVar->mReadFromId = 0;
  8423. auto rootMethodState = methodState.GetRootMethodState();
  8424. localVar->mLocalVarId = rootMethodState->mCurLocalVarId++;
  8425. mModule->DoAddLocalVariable(localVar);
  8426. if (autoComplete != NULL)
  8427. autoComplete->CheckLocalDef(BfNodeDynCast<BfIdentifierNode>(paramDef->mParamDeclaration->mNameNode), methodState.mLocals.back());
  8428. auto resolvePassData = mModule->mCompiler->mResolvePassData;
  8429. if (resolvePassData != NULL)
  8430. resolvePassData->HandleLocalReference(BfNodeDynCast<BfIdentifierNode>(paramDef->mParamDeclaration->mNameNode), mModule->mCurTypeInstance->mTypeDef,
  8431. mModule->mCurMethodInstance->mMethodDef, localVar->mLocalVarId);
  8432. }
  8433. }
  8434. bool isAutocomplete = mModule->mCompiler->IsAutocomplete();
  8435. methodDef->mIdx = mModule->mCurMethodInstance->mMethodDef->mIdx;
  8436. methodDef->mBody = lambdaBindExpr->mBody;
  8437. ///
  8438. auto varMethodState = methodState.mPrevMethodState;
  8439. bool hasExplicitCaptureNames = false;
  8440. for (auto& captureEntry : allocTarget.mCaptureInfo.mCaptures)
  8441. {
  8442. if (captureEntry.mNameNode == NULL)
  8443. {
  8444. hasExplicitCaptureNames = false;
  8445. break;
  8446. }
  8447. hasExplicitCaptureNames = true;
  8448. }
  8449. auto _SetNotCapturedFlag = [&](bool notCaptured)
  8450. {
  8451. auto varMethodState = methodState.mPrevMethodState;
  8452. while (varMethodState != NULL)
  8453. {
  8454. for (int localIdx = 0; localIdx < varMethodState->mLocals.size(); localIdx++)
  8455. {
  8456. auto localVar = varMethodState->mLocals[localIdx];
  8457. localVar->mNotCaptured = notCaptured;
  8458. }
  8459. varMethodState = varMethodState->mPrevMethodState;
  8460. if (varMethodState == NULL)
  8461. break;
  8462. if (varMethodState->mMixinState != NULL)
  8463. break;
  8464. if (varMethodState->mClosureState != NULL)
  8465. {
  8466. if (!varMethodState->mClosureState->mCapturing)
  8467. break;
  8468. }
  8469. }
  8470. };
  8471. if (hasExplicitCaptureNames)
  8472. {
  8473. _SetNotCapturedFlag(true);
  8474. auto varMethodState = methodState.mPrevMethodState;
  8475. while (varMethodState != NULL)
  8476. {
  8477. for (auto& captureEntry : allocTarget.mCaptureInfo.mCaptures)
  8478. {
  8479. if (captureEntry.mNameNode != NULL)
  8480. {
  8481. StringT<64> captureName;
  8482. captureEntry.mNameNode->ToString(captureName);
  8483. BfLocalVarEntry* entry;
  8484. if (varMethodState->mLocalVarSet.TryGetWith<StringImpl&>(captureName, &entry))
  8485. {
  8486. auto localVar = entry->mLocalVar;
  8487. while (localVar != NULL)
  8488. {
  8489. if (autoComplete != NULL)
  8490. autoComplete->CheckLocalRef(captureEntry.mNameNode, localVar);
  8491. if (((mModule->mCurMethodState->mClosureState == NULL) || (mModule->mCurMethodState->mClosureState->mCapturing)) &&
  8492. (mModule->mCompiler->mResolvePassData != NULL) && (mModule->mCurMethodInstance != NULL))
  8493. mModule->mCompiler->mResolvePassData->HandleLocalReference(captureEntry.mNameNode, localVar->mNameNode, mModule->mCurTypeInstance->mTypeDef, rootMethodState->mMethodInstance->mMethodDef, localVar->mLocalVarId);
  8494. localVar->mNotCaptured = false;
  8495. localVar = localVar->mShadowedLocal;
  8496. }
  8497. }
  8498. }
  8499. }
  8500. varMethodState = varMethodState->mPrevMethodState;
  8501. if (varMethodState == NULL)
  8502. break;
  8503. if (varMethodState->mMixinState != NULL)
  8504. break;
  8505. if (varMethodState->mClosureState != NULL)
  8506. {
  8507. if (!varMethodState->mClosureState->mCapturing)
  8508. break;
  8509. }
  8510. }
  8511. }
  8512. BfClosureInstanceInfo* closureInstanceInfo = new BfClosureInstanceInfo();
  8513. auto checkInsertBlock = mModule->mBfIRBuilder->GetInsertBlock();
  8514. closureState.mCaptureStartAccessId = methodState.mPrevMethodState->GetRootMethodState()->mCurAccessId;
  8515. closureState.mCaptureVisitingBody = true;
  8516. closureState.mClosureInstanceInfo = closureInstanceInfo;
  8517. VisitLambdaBodies(lambdaBindExpr->mBody, lambdaBindExpr->mDtor);
  8518. if (hasExplicitCaptureNames)
  8519. _SetNotCapturedFlag(false);
  8520. // If we ended up being called by a method with a lower captureStartAccessId, propagate that to whoever is calling us, too...
  8521. if ((methodState.mPrevMethodState->mClosureState != NULL) && (methodState.mPrevMethodState->mClosureState->mCapturing))
  8522. {
  8523. auto prevClosureState = methodState.mPrevMethodState->mClosureState;
  8524. if (closureState.mCaptureStartAccessId < prevClosureState->mCaptureStartAccessId)
  8525. prevClosureState->mCaptureStartAccessId = closureState.mCaptureStartAccessId;
  8526. }
  8527. if (mModule->mCurMethodInstance->mIsUnspecialized)
  8528. {
  8529. prevIgnoreWrites.Restore();
  8530. mModule->mBfIRBuilder->RestoreDebugLocation();
  8531. mResult = mModule->GetDefaultTypedValue(delegateTypeInstance);
  8532. mModule->mBfIRBuilder->SetActiveFunction(prevActiveFunction);
  8533. if (!prevInsertBlock.IsFake())
  8534. mModule->mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  8535. delete methodDef;
  8536. delete closureInstanceInfo;
  8537. return NULL;
  8538. }
  8539. closureState.mCaptureVisitingBody = false;
  8540. prevIgnoreWrites.Restore();
  8541. mModule->mBfIRBuilder->RestoreDebugLocation();
  8542. auto _GetCaptureType = [&](const StringImpl& str)
  8543. {
  8544. if (allocTarget.mCaptureInfo.mCaptures.IsEmpty())
  8545. return BfCaptureType_Copy;
  8546. for (auto& captureEntry : allocTarget.mCaptureInfo.mCaptures)
  8547. {
  8548. if ((captureEntry.mNameNode == NULL) || (captureEntry.mNameNode->Equals(str)))
  8549. {
  8550. captureEntry.mUsed = true;
  8551. return captureEntry.mCaptureType;
  8552. }
  8553. }
  8554. return BfCaptureType_None;
  8555. };
  8556. Array<BfClosureCapturedEntry> capturedEntries;
  8557. bool copyOuterCaptures = false;
  8558. //
  8559. {
  8560. auto varMethodState = methodState.mPrevMethodState;
  8561. while (varMethodState != NULL)
  8562. {
  8563. for (int localIdx = 0; localIdx < varMethodState->mLocals.size(); localIdx++)
  8564. {
  8565. auto localVar = varMethodState->mLocals[localIdx];
  8566. if ((localVar->mReadFromId >= closureState.mCaptureStartAccessId) || (localVar->mWrittenToId >= closureState.mCaptureStartAccessId))
  8567. {
  8568. if ((localVar->mIsThis) && (outerClosure != NULL))
  8569. {
  8570. continue;
  8571. }
  8572. auto outerLocal = localVar;
  8573. if ((localVar->mConstValue) || (localVar->mResolvedType->IsValuelessType()))
  8574. {
  8575. closureState.mConstLocals.push_back(*outerLocal);
  8576. continue;
  8577. }
  8578. BfClosureCapturedEntry capturedEntry;
  8579. auto capturedType = outerLocal->mResolvedType;
  8580. bool captureByRef = false;
  8581. auto captureType = _GetCaptureType(localVar->mName);
  8582. if (captureType == BfCaptureType_None)
  8583. {
  8584. continue;
  8585. }
  8586. if (!capturedType->IsRef())
  8587. {
  8588. if (captureType == BfCaptureType_Reference)
  8589. {
  8590. if (outerLocal->mIsThis)
  8591. {
  8592. if ((outerLocal->mResolvedType->IsValueType()) && (mModule->mCurMethodInstance->mMethodDef->HasNoThisSplat()))
  8593. captureByRef = true;
  8594. }
  8595. else if ((!localVar->mIsReadOnly) && (localVar->mWrittenToId >= closureState.mCaptureStartAccessId))
  8596. captureByRef = true;
  8597. }
  8598. }
  8599. else
  8600. {
  8601. if ((captureType != BfCaptureType_Reference) || (localVar->mWrittenToId < closureState.mCaptureStartAccessId))
  8602. {
  8603. capturedType = ((BfRefType*)capturedType)->mElementType;
  8604. }
  8605. }
  8606. if (captureByRef)
  8607. {
  8608. capturedType = mModule->CreateRefType(capturedType);
  8609. }
  8610. capturedEntry.mType = capturedType;
  8611. if (outerLocal->mName == "this")
  8612. capturedEntry.mName = "__this";
  8613. else
  8614. capturedEntry.mName = outerLocal->mName;
  8615. capturedEntry.mNameNode = outerLocal->mNameNode;
  8616. capturedEntries.Add(capturedEntry);
  8617. }
  8618. }
  8619. varMethodState = varMethodState->mPrevMethodState;
  8620. if (varMethodState == NULL)
  8621. break;
  8622. if (varMethodState->mMixinState != NULL)
  8623. break;
  8624. if (varMethodState->mClosureState != NULL)
  8625. {
  8626. if (!varMethodState->mClosureState->mCapturing)
  8627. break;
  8628. }
  8629. }
  8630. }
  8631. for (auto& captureEntry : allocTarget.mCaptureInfo.mCaptures)
  8632. {
  8633. if ((!captureEntry.mUsed) && (captureEntry.mNameNode != NULL))
  8634. mModule->Warn(0, "Capture specifier not used", captureEntry.mNameNode);
  8635. }
  8636. for (auto copyField : closureState.mReferencedOuterClosureMembers)
  8637. {
  8638. auto fieldDef = copyField->GetFieldDef();
  8639. auto captureType = _GetCaptureType(fieldDef->mName);
  8640. BfClosureCapturedEntry capturedEntry;
  8641. capturedEntry.mName = fieldDef->mName;
  8642. capturedEntry.mType = copyField->mResolvedType;
  8643. if ((captureType == BfCaptureType_Reference) && (capturedEntry.mType->IsRef()))
  8644. {
  8645. capturedEntry.mExplicitlyByReference = true;
  8646. }
  8647. else if ((captureType != BfCaptureType_Reference) && (capturedEntry.mType->IsRef()))
  8648. {
  8649. auto refType = (BfRefType*)capturedEntry.mType;
  8650. capturedEntry.mType = refType->mElementType;
  8651. }
  8652. else if ((captureType == BfCaptureType_Reference) && (!capturedEntry.mType->IsRef()) && (!fieldDef->mIsReadOnly))
  8653. {
  8654. capturedEntry.mType = mModule->CreateRefType(capturedEntry.mType);
  8655. }
  8656. }
  8657. std::sort(capturedEntries.begin(), capturedEntries.end());
  8658. bool hasCapture = false;
  8659. BfMethodInstanceGroup methodInstanceGroup;
  8660. methodInstanceGroup.mOwner = mModule->mCurTypeInstance;
  8661. methodInstanceGroup.mOnDemandKind = BfMethodOnDemandKind_AlwaysInclude;
  8662. BfMethodInstance* methodInstance = new BfMethodInstance();
  8663. methodInstance->mMethodInstanceGroup = &methodInstanceGroup;
  8664. methodInstance->GetMethodInfoEx()->mClosureInstanceInfo = closureInstanceInfo;
  8665. if (invokeMethodInstance != NULL)
  8666. methodInstance->mParams = invokeMethodInstance->mParams;
  8667. methodInstance->mIsClosure = true;
  8668. // We want the closure ID to match between hot reloads -- otherwise we wouldn't be able to modify them,
  8669. // so we use the charId from the 'fat arrow' token
  8670. int closureId = 0;
  8671. if (lambdaBindExpr->mFatArrowToken != NULL)
  8672. closureId = lambdaBindExpr->mFatArrowToken->GetStartCharId();
  8673. auto curProject = mModule->mCurTypeInstance->mTypeDef->mProject;
  8674. BF_ASSERT(curProject != NULL);
  8675. // We need to make these per-project even though you'd think we might not because we
  8676. // insert generic type specializations in the generic definition's project,
  8677. // BECAUSE: we would need to scan the captured fields the same way we scan the
  8678. // generic arguments to determine if each project can see it or not in the vdata
  8679. BfTypeInstance* useTypeInstance = delegateTypeInstance;
  8680. BfClosureType* closureTypeInst = NULL;
  8681. if ((capturedEntries.size() != 0) || (lambdaBindExpr->mDtor != NULL) || (copyOuterCaptures))
  8682. {
  8683. hashCtx.MixinStr(curProject->mName);
  8684. if (copyOuterCaptures)
  8685. {
  8686. // String typeName = mModule->DoTypeToString(outerClosure, BfTypeNameFlag_DisambiguateDups);
  8687. // hashCtx.MixinStr(typeName);
  8688. hashCtx.Mixin(outerClosure->mTypeId);
  8689. }
  8690. for (auto& capturedEntry : capturedEntries)
  8691. {
  8692. // String typeName = mModule->DoTypeToString(capturedEntry.mType, BfTypeNameFlag_DisambiguateDups);
  8693. // hashCtx.MixinStr(typeName);
  8694. hashCtx.Mixin(capturedEntry.mType->mTypeId);
  8695. hashCtx.MixinStr(capturedEntry.mName);
  8696. hashCtx.Mixin(capturedEntry.mExplicitlyByReference);
  8697. }
  8698. if (lambdaBindExpr->mDtor != NULL)
  8699. {
  8700. // Has DTOR thunk
  8701. bool hasDtorThunk = true;
  8702. hashCtx.Mixin(hasDtorThunk);
  8703. }
  8704. Val128 hash128 = hashCtx.Finish128();
  8705. BfClosureType* checkClosureType = new BfClosureType(delegateTypeInstance, hash128);
  8706. checkClosureType->mContext = mModule->mContext;
  8707. checkClosureType->mBaseType = delegateTypeInstance;
  8708. BfType* resolvedClosureType = mModule->ResolveType(checkClosureType, BfPopulateType_Identity);
  8709. closureTypeInst = (BfClosureType*)resolvedClosureType;
  8710. if (checkClosureType == resolvedClosureType)
  8711. {
  8712. // This is a new closure type
  8713. closureTypeInst->Init(curProject);
  8714. closureTypeInst->mTypeDef->mProject = curProject;
  8715. if (copyOuterCaptures)
  8716. {
  8717. for (auto& fieldInstance : outerClosure->mFieldInstances)
  8718. {
  8719. BfFieldDef* origFieldDef = fieldInstance.GetFieldDef();
  8720. BfFieldDef* fieldDef = closureTypeInst->AddField(fieldInstance.mResolvedType, origFieldDef->mName);
  8721. fieldDef->mIsReadOnly = origFieldDef->mIsReadOnly;
  8722. }
  8723. }
  8724. for (auto& capturedEntry : capturedEntries)
  8725. {
  8726. BfFieldDef* fieldDef = closureTypeInst->AddField(capturedEntry.mType, capturedEntry.mName);
  8727. if (!capturedEntry.mExplicitlyByReference)
  8728. fieldDef->mIsReadOnly = true;
  8729. }
  8730. if (lambdaBindExpr->mDtor != NULL)
  8731. {
  8732. auto dtorDef = closureTypeInst->AddDtor();
  8733. auto voidType = mModule->GetPrimitiveType(BfTypeCode_None);
  8734. auto voidPtrType = mModule->CreatePointerType(voidType);
  8735. closureTypeInst->AddField(voidPtrType, "__dtorThunk");
  8736. }
  8737. closureTypeInst->Finish();
  8738. }
  8739. else
  8740. {
  8741. // Already had this entry
  8742. delete checkClosureType;
  8743. }
  8744. useTypeInstance = closureTypeInst;
  8745. }
  8746. mModule->mBfIRBuilder->PopulateType(useTypeInstance);
  8747. mModule->PopulateType(useTypeInstance);
  8748. // If we are allowing hot swapping, we need to always mangle the name to non-static because if we add a capture
  8749. // later then we need to have the mangled names match
  8750. methodDef->mIsStatic = (closureTypeInst == NULL) && (!mModule->mCompiler->mOptions.mAllowHotSwapping);
  8751. SizedArray<BfIRType, 3> newTypes;
  8752. SizedArray<BfIRType, 8> origParamTypes;
  8753. BfIRType origReturnType;
  8754. if (!methodDef->mIsStatic)
  8755. newTypes.push_back(mModule->mBfIRBuilder->MapType(useTypeInstance));
  8756. if (invokeMethodInstance != NULL)
  8757. {
  8758. auto invokeFunctionType = mModule->mBfIRBuilder->MapMethod(invokeMethodInstance);
  8759. invokeMethodInstance->GetIRFunctionInfo(mModule, origReturnType, origParamTypes, methodDef->mIsStatic);
  8760. }
  8761. else
  8762. {
  8763. origReturnType = mModule->mBfIRBuilder->MapType(mModule->GetPrimitiveType(BfTypeCode_None));
  8764. }
  8765. for (int i = methodDef->mIsStatic ? 0 : 1; i < (int)origParamTypes.size(); i++)
  8766. newTypes.push_back(origParamTypes[i]);
  8767. auto closureFuncType = mModule->mBfIRBuilder->CreateFunctionType(origReturnType, newTypes, false);
  8768. prevMethodState.Restore();
  8769. mModule->mBfIRBuilder->SetActiveFunction(prevActiveFunction);
  8770. if (!prevInsertBlock.IsFake())
  8771. mModule->mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  8772. // Just a check
  8773. mModule->mBfIRBuilder->GetInsertBlock();
  8774. //auto rootMethodState = mModule->mCurMethodState;
  8775. HashContext closureHashCtx;
  8776. closureHashCtx.Mixin(closureId);
  8777. // When we're a nested lambda, strip off the outer hash and closureTypeInst markers
  8778. methodDef->mName = mModule->mCurMethodInstance->mMethodDef->mName;
  8779. int prevSepPos = (int)methodDef->mName.LastIndexOf('$');
  8780. if (prevSepPos != -1)
  8781. {
  8782. closureHashCtx.Mixin(methodDef->mName.c_str() + prevSepPos, (int)methodDef->mName.length() - prevSepPos);
  8783. methodDef->mName.RemoveToEnd(prevSepPos);
  8784. }
  8785. // if (closureTypeInst != NULL)
  8786. // {
  8787. // StringT<128> typeInstName;
  8788. // BfMangler::Mangle(typeInstName,mModule->mCompiler->GetMangleKind(), closureTypeInst);
  8789. // closureHashCtx.MixinStr(typeInstName);
  8790. // }
  8791. auto checkMethodState = mModule->mCurMethodState;
  8792. while (checkMethodState != NULL)
  8793. {
  8794. if (checkMethodState->mMethodInstance != NULL)
  8795. {
  8796. if (checkMethodState->mMethodInstance->mMethodInfoEx != NULL)
  8797. {
  8798. for (auto methodGenericArg : checkMethodState->mMethodInstance->mMethodInfoEx->mMethodGenericArguments)
  8799. {
  8800. StringT<128> genericTypeName;
  8801. BfMangler::Mangle(genericTypeName, mModule->mCompiler->GetMangleKind(), methodGenericArg);
  8802. closureHashCtx.MixinStr(genericTypeName);
  8803. }
  8804. }
  8805. }
  8806. checkMethodState = checkMethodState->mPrevMethodState;
  8807. }
  8808. uint64 closureHash = closureHashCtx.Finish64();
  8809. methodDef->mName += "$";
  8810. methodDef->mName += BfTypeUtils::HashEncode64(closureHash);
  8811. methodInstance->mMethodDef = methodDef;
  8812. if (invokeMethodInstance != NULL)
  8813. {
  8814. methodInstance->mParams = invokeMethodInstance->mParams;
  8815. methodInstance->mReturnType = invokeMethodInstance->mReturnType;
  8816. }
  8817. else
  8818. methodInstance->mReturnType = mModule->GetPrimitiveType(BfTypeCode_None);
  8819. StringT<128> closureFuncName;
  8820. BfMangler::Mangle(closureFuncName, mModule->mCompiler->GetMangleKind(), methodInstance);
  8821. auto closureFunc = mModule->mBfIRBuilder->CreateFunction(closureFuncType, BfIRLinkageType_External, closureFuncName);
  8822. methodInstance->mIRFunction = closureFunc;
  8823. if (methodInstance->mIsReified)
  8824. mModule->CheckHotMethod(methodInstance, closureFuncName);
  8825. if ((methodInstance->mHotMethod != NULL) && (mModule->mCurMethodState->mHotDataReferenceBuilder))
  8826. mModule->mCurMethodState->mHotDataReferenceBuilder->mInnerMethods.Add(methodInstance->mHotMethod);
  8827. methodState.Reset();
  8828. lambdaInstance = new BfLambdaInstance();
  8829. rootMethodState->mLambdaCache[lambdaBindExpr] = lambdaInstance;
  8830. lambdaInstance->mDelegateTypeInstance = delegateTypeInstance;
  8831. lambdaInstance->mUseTypeInstance = useTypeInstance;
  8832. lambdaInstance->mClosureTypeInstance = closureTypeInst;
  8833. lambdaInstance->mOuterClosure = outerClosure;
  8834. lambdaInstance->mCopyOuterCaptures = copyOuterCaptures;
  8835. lambdaInstance->mIsStatic = methodDef->mIsStatic;
  8836. lambdaInstance->mClosureFunc = closureFunc;
  8837. lambdaInstance->mMethodInstance = methodInstance;
  8838. lambdaInstance->mConstLocals = closureState.mConstLocals;
  8839. lambdaInstance->mParamDecls = tempParamDecls;
  8840. lambdaInstance->mDeclMixinState = mModule->mCurMethodState->mMixinState;
  8841. if (lambdaInstance->mDeclMixinState != NULL)
  8842. lambdaInstance->mDeclMixinState->mHasDeferredUsage = true;
  8843. tempParamDecls.ClearWithoutDeleting();
  8844. closureState.mCapturing = false;
  8845. closureState.mClosureType = useTypeInstance;
  8846. closureInstanceInfo->mThisOverride = useTypeInstance;
  8847. mModule->mIncompleteMethodCount++;
  8848. SetAndRestoreValue<BfClosureState*> prevClosureState(mModule->mCurMethodState->mClosureState, &closureState);
  8849. if (mModule->HasCompiledOutput())
  8850. mModule->SetupIRMethod(methodInstance, methodInstance->mIRFunction, methodInstance->mAlwaysInline);
  8851. // This keeps us from giving errors twice. ProcessMethod can give errors when we capture by value but needed to
  8852. // capture by reference, so we still need to do it for resolve-only
  8853. bool processMethods = (mModule->mCompiler->GetAutoComplete() == NULL) && !mModule->mHadBuildError;
  8854. mModule->mBfIRBuilder->SaveDebugLocation();
  8855. //
  8856. {
  8857. BfGetSymbolReferenceKind prevSymbolRefKind = BfGetSymbolReferenceKind_None;
  8858. if (mModule->mCompiler->mResolvePassData != NULL)
  8859. {
  8860. prevSymbolRefKind = mModule->mCompiler->mResolvePassData->mGetSymbolReferenceKind;
  8861. mModule->mCompiler->mResolvePassData->mGetSymbolReferenceKind = BfGetSymbolReferenceKind_None;
  8862. }
  8863. if (processMethods)
  8864. {
  8865. // If we are in an always-ignored block, we will have mIgnoreWrites set
  8866. // SetAndRestoreValue<bool> prevWantsIgnoreWrite(mModule->mWantsIRIgnoreWrites, mModule->mBfIRBuilder->mIgnoreWrites);
  8867. // mModule->ProcessMethod(methodInstance);
  8868. }
  8869. if (mModule->mCompiler->mResolvePassData != NULL)
  8870. mModule->mCompiler->mResolvePassData->mGetSymbolReferenceKind = prevSymbolRefKind;
  8871. }
  8872. mModule->mBfIRBuilder->RestoreDebugLocation();
  8873. if (mModule->mCompiler->IsSkippingExtraResolveChecks())
  8874. closureFunc = BfIRFunction();
  8875. BfIRFunction dtorFunc;
  8876. if (lambdaBindExpr->mDtor != NULL)
  8877. {
  8878. SizedArray<BfIRType, 1> newTypes;
  8879. newTypes.push_back(mModule->mBfIRBuilder->MapType(useTypeInstance));
  8880. auto voidType = mModule->GetPrimitiveType(BfTypeCode_None);
  8881. auto dtorFuncType = mModule->mBfIRBuilder->CreateFunctionType(mModule->mBfIRBuilder->MapType(voidType), newTypes, false);
  8882. BfMethodDef* dtorMethodDef = new BfMethodDef();
  8883. dtorMethodDef->mDeclaringType = mModule->mCurMethodInstance->mMethodDef->mDeclaringType;
  8884. dtorMethodDef->mName = "~this$";
  8885. dtorMethodDef->mName += methodDef->mName;
  8886. dtorMethodDef->mMethodType = BfMethodType_Normal;
  8887. dtorMethodDef->mBody = lambdaBindExpr->mDtor;
  8888. dtorMethodDef->mIdx = mModule->mCurMethodInstance->mMethodDef->mIdx;
  8889. BfMethodInstance* dtorMethodInstance = new BfMethodInstance();
  8890. dtorMethodInstance->mMethodDef = dtorMethodDef;
  8891. dtorMethodInstance->mReturnType = mModule->GetPrimitiveType(BfTypeCode_None);
  8892. dtorMethodInstance->mMethodInstanceGroup = &methodInstanceGroup;
  8893. StringT<128> dtorMangledName;
  8894. BfMangler::Mangle(dtorMangledName, mModule->mCompiler->GetMangleKind(), dtorMethodInstance);
  8895. dtorFunc = mModule->mBfIRBuilder->CreateFunction(dtorFuncType, BfIRLinkageType_External, dtorMangledName);
  8896. mModule->SetupIRMethod(NULL, dtorFunc, false);
  8897. dtorMethodInstance->mIRFunction = dtorFunc;
  8898. mModule->mIncompleteMethodCount++;
  8899. mModule->mBfIRBuilder->SaveDebugLocation();
  8900. //
  8901. if (processMethods)
  8902. {
  8903. // If we are in an always-ignored block, we will have mIgnoreWrites set
  8904. // SetAndRestoreValue<bool> prevWantsIgnoreWrite(mModule->mWantsIRIgnoreWrites, mModule->mBfIRBuilder->mIgnoreWrites);
  8905. // mModule->ProcessMethod(dtorMethodInstance);
  8906. }
  8907. mModule->mBfIRBuilder->RestoreDebugLocation();
  8908. if (mModule->mCompiler->IsSkippingExtraResolveChecks())
  8909. dtorFunc = BfIRFunction();
  8910. if (dtorMethodInstance->mIsReified)
  8911. mModule->CheckHotMethod(dtorMethodInstance, dtorMangledName);
  8912. if ((dtorMethodInstance->mHotMethod != NULL) && (mModule->mCurMethodState->mHotDataReferenceBuilder))
  8913. mModule->mCurMethodState->mHotDataReferenceBuilder->mInnerMethods.Add(dtorMethodInstance->mHotMethod);
  8914. lambdaInstance->mDtorMethodInstance = dtorMethodInstance;
  8915. lambdaInstance->mDtorFunc = dtorFunc;
  8916. }
  8917. prevClosureState.Restore();
  8918. if (!prevInsertBlock.IsFake())
  8919. mModule->mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  8920. for (auto& capturedEntry : capturedEntries)
  8921. {
  8922. BfLambdaCaptureInfo lambdaCapture;
  8923. if (capturedEntry.mName == "__this")
  8924. lambdaCapture.mName = "this";
  8925. else
  8926. lambdaCapture.mName = capturedEntry.mName;
  8927. // if (capturedEntry.mLocalVarDef != NULL)
  8928. // lambdaCapture.mLocalIdx = capturedEntry.mLocalVarDef->mLocalVarId;
  8929. // lambdaCapture.mCopyField = capturedEntry.mCopyField;
  8930. lambdaInstance->mCaptures.Add(lambdaCapture);
  8931. closureInstanceInfo->mCaptureEntries.Add(capturedEntry);
  8932. }
  8933. if (processMethods)
  8934. rootMethodState->mDeferredLambdaInstances.Add(lambdaInstance);
  8935. methodInstance->mMethodInstanceGroup = NULL;
  8936. return lambdaInstance;
  8937. }
  8938. void BfExprEvaluator::Visit(BfLambdaBindExpression* lambdaBindExpr)
  8939. {
  8940. // if (lambdaBindExpr->ToString() == "new (addr, byteCount, addrType) => { DoCreateMemoryBreakpoint(addr, byteCount, addrType, showOptions); }")
  8941. // {
  8942. // NOP;
  8943. // }
  8944. BfTokenNode* newToken = NULL;
  8945. BfAllocTarget allocTarget = ResolveAllocTarget(lambdaBindExpr->mNewToken, newToken);
  8946. if ((mModule->mCurMethodState != NULL) && (mModule->mCurMethodState->mClosureState != NULL) && (mModule->mCurMethodState->mClosureState->mBlindCapturing))
  8947. {
  8948. // We're just capturing. We just need to visit the bodies here. This helps infinite recursion with local methods containing lambdas calling each other
  8949. if (lambdaBindExpr->mBody != NULL)
  8950. mModule->VisitChild(lambdaBindExpr->mBody);
  8951. if ((lambdaBindExpr->mDtor != NULL) && (lambdaBindExpr->mDtor->mBody != NULL))
  8952. mModule->VisitChild(lambdaBindExpr->mDtor->mBody);
  8953. return;
  8954. }
  8955. BfLambdaInstance* lambdaInstance = GetLambdaInstance(lambdaBindExpr, allocTarget);
  8956. if (lambdaInstance == NULL)
  8957. return;
  8958. BfTypeInstance* delegateTypeInstance = lambdaInstance->mDelegateTypeInstance;
  8959. BfTypeInstance* useTypeInstance = lambdaInstance->mUseTypeInstance;
  8960. BfTypeInstance* closureTypeInst = lambdaInstance->mClosureTypeInstance;
  8961. mResult = BfTypedValue(mModule->AllocFromType(useTypeInstance, allocTarget, BfIRValue(), BfIRValue(), 0, BfAllocFlags_None), useTypeInstance);
  8962. if (!delegateTypeInstance->IsDelegate())
  8963. {
  8964. mModule->AssertErrorState();
  8965. return;
  8966. }
  8967. auto baseDelegateType = VerifyBaseDelegateType(delegateTypeInstance->mBaseType);
  8968. if (baseDelegateType == NULL)
  8969. {
  8970. mModule->Fail("Invalid delegate type", lambdaBindExpr);
  8971. return;
  8972. }
  8973. auto baseDelegate = mModule->mBfIRBuilder->CreateBitCast(mResult.mValue, mModule->mBfIRBuilder->MapType(baseDelegateType));
  8974. // >> delegate.mTarget = bindResult.mTarget
  8975. auto nullPtrType = mModule->GetPrimitiveType(BfTypeCode_NullPtr);
  8976. BfIRValue valPtr;
  8977. if (!lambdaInstance->mIsStatic)
  8978. valPtr = mModule->mBfIRBuilder->CreateBitCast(mResult.mValue, mModule->mBfIRBuilder->MapType(nullPtrType));
  8979. else
  8980. valPtr = mModule->GetDefaultValue(nullPtrType);
  8981. auto fieldPtr = mModule->mBfIRBuilder->CreateInBoundsGEP(baseDelegate, 0, 2);
  8982. mModule->mBfIRBuilder->CreateStore(valPtr, fieldPtr);
  8983. // >> delegate.mFuncPtr = bindResult.mFunc
  8984. if (lambdaInstance->mClosureFunc)
  8985. {
  8986. auto nullPtrType = mModule->GetPrimitiveType(BfTypeCode_NullPtr);
  8987. auto valPtr = mModule->mBfIRBuilder->CreateBitCast(lambdaInstance->mClosureFunc, mModule->mBfIRBuilder->MapType(nullPtrType));
  8988. auto fieldPtr = mModule->mBfIRBuilder->CreateInBoundsGEP(baseDelegate, 0, 1);
  8989. mModule->mBfIRBuilder->CreateStore(valPtr, fieldPtr);
  8990. }
  8991. mModule->AddDependency(useTypeInstance, mModule->mCurTypeInstance, BfDependencyMap::DependencyFlag_Calls);
  8992. // Copy captures into the delegate
  8993. if (lambdaInstance->mClosureTypeInstance != NULL)
  8994. {
  8995. int fieldIdx = 0;
  8996. if (lambdaInstance->mCopyOuterCaptures)
  8997. {
  8998. for (auto& fieldInstance : lambdaInstance->mOuterClosure->mFieldInstances)
  8999. {
  9000. if (!fieldInstance.mResolvedType->IsValuelessType())
  9001. {
  9002. BF_ASSERT(fieldInstance.mDataIdx == fieldIdx + 1);
  9003. auto localVar = mModule->mCurMethodState->mLocals[0];
  9004. auto capturedValue = mModule->mBfIRBuilder->CreateInBoundsGEP(localVar->mValue, 0, fieldInstance.mDataIdx);
  9005. capturedValue = mModule->mBfIRBuilder->CreateLoad(capturedValue);
  9006. auto fieldPtr = mModule->mBfIRBuilder->CreateInBoundsGEP(mResult.mValue, 0, fieldInstance.mDataIdx);
  9007. mModule->mBfIRBuilder->CreateStore(capturedValue, fieldPtr);
  9008. fieldIdx++;
  9009. }
  9010. }
  9011. }
  9012. // for (auto& capturedEntry : capturedEntries)
  9013. // {
  9014. // BfIRValue capturedValue;
  9015. // if (capturedEntry.mLocalVarDef != NULL)
  9016. // {
  9017. // BfTypedValue localResult = LoadLocal(capturedEntry.mLocalVarDef, true);
  9018. //
  9019. // if (!capturedEntry.mType->IsRef())
  9020. // {
  9021. // if (localResult.IsSplat())
  9022. // {
  9023. // auto aggResult = mModule->AggregateSplat(localResult);
  9024. // capturedValue = aggResult.mValue;
  9025. // }
  9026. // else
  9027. // {
  9028. // localResult = mModule->LoadValue(localResult);
  9029. // capturedValue = localResult.mValue;
  9030. // if ((capturedEntry.mLocalVarDef->mResolvedType->IsRef()) && (!capturedEntry.mType->IsRef()))
  9031. // capturedValue = mModule->mBfIRBuilder->CreateLoad(capturedValue);
  9032. // }
  9033. // }
  9034. // else
  9035. // {
  9036. // if (capturedEntry.mLocalVarDef->mResolvedType->IsRef())
  9037. // localResult = mModule->LoadValue(localResult);
  9038. // capturedValue = localResult.mValue;
  9039. // }
  9040. // }
  9041. // else
  9042. // {
  9043. // // Read captured field from outer lambda ('this')
  9044. // auto localVar = mModule->mCurMethodState->mLocals[0];
  9045. // capturedValue = mModule->mBfIRBuilder->CreateInBoundsGEP(localVar->mValue, 0, capturedEntry.mCopyField->mDataIdx);
  9046. // if ((capturedEntry.mCopyField->mResolvedType->IsRef()) || (!capturedEntry.mType->IsRef()))
  9047. // {
  9048. // capturedValue = mModule->mBfIRBuilder->CreateLoad(capturedValue);
  9049. // if ((capturedEntry.mCopyField->mResolvedType->IsRef()) && (!capturedEntry.mType->IsRef()))
  9050. // capturedValue = mModule->mBfIRBuilder->CreateLoad(capturedValue);
  9051. // }
  9052. // }
  9053. // if (capturedValue)
  9054. // {
  9055. // auto fieldPtr = mModule->mBfIRBuilder->CreateInBoundsGEP(mResult.mValue, 0, closureTypeInst->mFieldInstances[fieldIdx].mDataIdx);
  9056. // mModule->mBfIRBuilder->CreateStore(capturedValue, fieldPtr);
  9057. // }
  9058. // fieldIdx++;
  9059. // }
  9060. int captureIdx = 0;
  9061. //for (auto& capturedEntry : lambdaInstance->mCaptures)
  9062. for (int captureIdx = 0; captureIdx < (int)lambdaInstance->mCaptures.size(); captureIdx++)
  9063. {
  9064. auto& capturedEntry = lambdaInstance->mCaptures[captureIdx];
  9065. BfIdentifierNode* identifierNode = lambdaInstance->mMethodInstance->mMethodInfoEx->mClosureInstanceInfo->mCaptureEntries[captureIdx].mNameNode;
  9066. //if (captureIdx < lambdaInstance->mMethodInstance->mClosureInstanceInfo->mCaptureNodes.size)
  9067. BfIRValue capturedValue;
  9068. // if (capturedEntry.mLocalVarDef != NULL)
  9069. // {
  9070. // BfTypedValue localResult = LoadLocal(capturedEntry.mLocalVarDef, true);
  9071. //
  9072. // if (!capturedEntry.mType->IsRef())
  9073. // {
  9074. // if (localResult.IsSplat())
  9075. // {
  9076. // auto aggResult = mModule->AggregateSplat(localResult);
  9077. // capturedValue = aggResult.mValue;
  9078. // }
  9079. // else
  9080. // {
  9081. // localResult = mModule->LoadValue(localResult);
  9082. // capturedValue = localResult.mValue;
  9083. // if ((capturedEntry.mLocalVarDef->mResolvedType->IsRef()) && (!capturedEntry.mType->IsRef()))
  9084. // capturedValue = mModule->mBfIRBuilder->CreateLoad(capturedValue);
  9085. // }
  9086. // }
  9087. // else
  9088. // {
  9089. // if (capturedEntry.mLocalVarDef->mResolvedType->IsRef())
  9090. // localResult = mModule->LoadValue(localResult);
  9091. // capturedValue = localResult.mValue;
  9092. // }
  9093. // }
  9094. // else
  9095. // {
  9096. // // Read captured field from outer lambda ('this')
  9097. // auto localVar = mModule->mCurMethodState->mLocals[0];
  9098. // capturedValue = mModule->mBfIRBuilder->CreateInBoundsGEP(localVar->mValue, 0, capturedEntry.mCopyField->mDataIdx);
  9099. // if ((capturedEntry.mCopyField->mResolvedType->IsRef()) || (!capturedEntry.mType->IsRef()))
  9100. // {
  9101. // capturedValue = mModule->mBfIRBuilder->CreateLoad(capturedValue);
  9102. // if ((capturedEntry.mCopyField->mResolvedType->IsRef()) && (!capturedEntry.mType->IsRef()))
  9103. // capturedValue = mModule->mBfIRBuilder->CreateLoad(capturedValue);
  9104. // }
  9105. // }
  9106. auto fieldInstance = &closureTypeInst->mFieldInstances[fieldIdx];
  9107. BfTypedValue capturedTypedVal;
  9108. if (identifierNode != NULL)
  9109. capturedTypedVal = DoImplicitArgCapture(NULL, identifierNode);
  9110. else
  9111. capturedTypedVal = LookupIdentifier(NULL, capturedEntry.mName);
  9112. if (!fieldInstance->mResolvedType->IsRef())
  9113. capturedTypedVal = mModule->LoadOrAggregateValue(capturedTypedVal);
  9114. else if (!capturedTypedVal.IsAddr())
  9115. {
  9116. mModule->Fail(StrFormat("Unable to capture '%s' by reference", capturedEntry.mName.c_str()), lambdaBindExpr);
  9117. break;
  9118. }
  9119. capturedValue = capturedTypedVal.mValue;
  9120. if (capturedValue)
  9121. {
  9122. auto fieldPtr = mModule->mBfIRBuilder->CreateInBoundsGEP(mResult.mValue, 0, fieldInstance->mDataIdx);
  9123. mModule->mBfIRBuilder->CreateStore(capturedValue, fieldPtr);
  9124. }
  9125. else
  9126. {
  9127. mModule->Fail(StrFormat("Unable to capture '%s'", capturedEntry.mName.c_str()), lambdaBindExpr);
  9128. mModule->AssertErrorState();
  9129. }
  9130. fieldIdx++;
  9131. }
  9132. if (lambdaInstance->mDtorFunc)
  9133. {
  9134. auto fieldPtr = mModule->mBfIRBuilder->CreateInBoundsGEP(mResult.mValue, 0, closureTypeInst->mFieldInstances[fieldIdx].mDataIdx);
  9135. auto voidType = mModule->GetPrimitiveType(BfTypeCode_None);
  9136. auto voidPtrType = mModule->CreatePointerType(voidType);
  9137. auto dtorThunk = mModule->mBfIRBuilder->CreateBitCast(lambdaInstance->mDtorFunc, mModule->mBfIRBuilder->MapType(voidPtrType));
  9138. mModule->mBfIRBuilder->CreateStore(dtorThunk, fieldPtr);
  9139. fieldIdx++;
  9140. }
  9141. }
  9142. }
  9143. void BfExprEvaluator::ProcessArrayInitializer(BfTokenNode* openToken, const BfSizedArray<BfExpression*>& valueExprs, const BfSizedArray<BfTokenNode*>& commas, BfTokenNode* closeToken, int dimensions, SizedArrayImpl<int64>& dimLengths, int dim, bool& hasFailed)
  9144. {
  9145. bool setSize = false;
  9146. if (dim == dimLengths.size())
  9147. {
  9148. dimLengths.push_back((int)valueExprs.size());
  9149. setSize = true;
  9150. }
  9151. else if (dimLengths[dim] == -1)
  9152. {
  9153. dimLengths[dim] = (int)valueExprs.size();
  9154. setSize = true;
  9155. }
  9156. int64 initCountDiff = (int)valueExprs.size() - dimLengths[dim];
  9157. if ((dimLengths[dim] != -1) && (initCountDiff != 0) && (!hasFailed))
  9158. {
  9159. if (initCountDiff > 0)
  9160. {
  9161. mModule->Fail(StrFormat("Too many initializers, expected %d fewer", initCountDiff), valueExprs[(int)dimLengths[dim]]);
  9162. hasFailed = true;
  9163. }
  9164. else
  9165. {
  9166. // If it ends with ", ?) or ",)" then allow unsized
  9167. if (((valueExprs.size() == 0) || (BfNodeDynCast<BfUninitializedExpression>(valueExprs.back()) == NULL)) &&
  9168. (commas.size() < valueExprs.size()))
  9169. {
  9170. BfAstNode* refNode = closeToken;
  9171. if ((refNode == NULL) && (mModule->mParentNodeEntry != NULL))
  9172. refNode = mModule->mParentNodeEntry->mNode;
  9173. mModule->Fail(StrFormat("Too few initializer, expected %d more", -initCountDiff), refNode);
  9174. hasFailed = true;
  9175. }
  9176. }
  9177. }
  9178. for (int i = 0; i < (int)valueExprs.size(); i++)
  9179. {
  9180. BfExpression* expr = valueExprs[i];
  9181. if (auto uninitExpr = BfNodeDynCast<BfUninitializedExpression>(expr))
  9182. {
  9183. continue;
  9184. }
  9185. auto innerInitExpr = BfNodeDynCast<BfCollectionInitializerExpression>(expr);
  9186. if (dim < dimensions - 1)
  9187. {
  9188. if (innerInitExpr == NULL)
  9189. {
  9190. if (auto innerTupleExpr = BfNodeDynCast<BfTupleExpression>(expr))
  9191. {
  9192. ProcessArrayInitializer(innerTupleExpr->mOpenParen, innerTupleExpr->mValues, innerTupleExpr->mCommas, innerTupleExpr->mCloseParen, dimensions, dimLengths, dim + 1, hasFailed);
  9193. }
  9194. else if (auto parenExpr = BfNodeDynCast<BfParenthesizedExpression>(expr))
  9195. {
  9196. SizedArray<BfExpression*, 1> values;
  9197. values.Add(parenExpr->mExpression);
  9198. SizedArray<BfTokenNode*, 1> commas;
  9199. ProcessArrayInitializer(parenExpr->mOpenParen, values, commas, parenExpr->mCloseParen, dimensions, dimLengths, dim + 1, hasFailed);
  9200. }
  9201. else
  9202. {
  9203. hasFailed = true;
  9204. mModule->Fail("A nested array initializer is expected", expr);
  9205. continue;
  9206. }
  9207. }
  9208. else
  9209. ProcessArrayInitializer(innerInitExpr->mOpenBrace, innerInitExpr->mValues, innerInitExpr->mCommas, innerInitExpr->mCloseBrace, dimensions, dimLengths, dim + 1, hasFailed);
  9210. }
  9211. else if (innerInitExpr != NULL)
  9212. {
  9213. hasFailed = true;
  9214. mModule->Fail("Unexpected nested initializer", expr);
  9215. ProcessArrayInitializer(innerInitExpr->mOpenBrace, innerInitExpr->mValues, innerInitExpr->mCommas, innerInitExpr->mCloseBrace, dimensions, dimLengths, dim + 1, hasFailed);
  9216. }
  9217. else
  9218. {
  9219. //mModule->Fail("Expected initializer", )
  9220. }
  9221. }
  9222. }
  9223. void BfExprEvaluator::CheckObjectCreateTypeRef(BfType* expectingType, BfAstNode* afterNode)
  9224. {
  9225. auto autoComplete = GetAutoComplete();
  9226. if ((autoComplete != NULL) && (afterNode != NULL) && (autoComplete->mIsAutoComplete) &&
  9227. (afterNode->IsFromParser(mModule->mCompiler->mResolvePassData->mParser)) &&
  9228. (afterNode->GetParser()->mCursorIdx == afterNode->GetSrcEnd() + 1))
  9229. {
  9230. BfType* expectingType = mExpectingType;
  9231. BfTypeInstance* expectingTypeInst = NULL;
  9232. if (mExpectingType != NULL)
  9233. {
  9234. expectingTypeInst = mExpectingType->ToTypeInstance();
  9235. }
  9236. if ((mExpectingType != NULL) && (((expectingTypeInst == NULL) || (!expectingTypeInst->mTypeDef->mIsDelegate))))
  9237. {
  9238. // Why were we doing this? It floods the autocomplete with every possible type
  9239. //autoComplete->AddTopLevelTypes(NULL);
  9240. autoComplete->mInsertStartIdx = afterNode->GetSourceData()->ToParser()->mCursorIdx;
  9241. BF_ASSERT(autoComplete->mInsertStartIdx != -1);
  9242. auto expectingType = mExpectingType;
  9243. while (expectingType->IsArray())
  9244. {
  9245. auto arrayType = (BfArrayType*)expectingType;
  9246. expectingType = arrayType->mTypeGenericArguments[0];
  9247. }
  9248. auto expectingTypeInst = expectingType->ToTypeInstance();
  9249. if (expectingTypeInst != NULL)
  9250. {
  9251. autoComplete->AddTypeInstanceEntry(expectingTypeInst);
  9252. }
  9253. else
  9254. autoComplete->mDefaultSelection = mModule->TypeToString(expectingType);
  9255. }
  9256. }
  9257. }
  9258. void BfExprEvaluator::Visit(BfObjectCreateExpression* objCreateExpr)
  9259. {
  9260. auto autoComplete = GetAutoComplete();
  9261. if ((autoComplete != NULL) && (objCreateExpr->mTypeRef != NULL))
  9262. {
  9263. autoComplete->CheckTypeRef(objCreateExpr->mTypeRef, false, true);
  9264. }
  9265. //if (objCreateExpr->mArraySizeSpecifier == NULL)
  9266. CheckObjectCreateTypeRef(mExpectingType, objCreateExpr->mNewNode);
  9267. BfTokenNode* newToken = NULL;
  9268. BfAllocTarget allocTarget = ResolveAllocTarget(objCreateExpr->mNewNode, newToken);
  9269. bool isScopeAlloc = newToken->GetToken() == BfToken_Scope;
  9270. bool isAppendAlloc = newToken->GetToken() == BfToken_Append;
  9271. bool isStackAlloc = (newToken->GetToken() == BfToken_Stack) || (isScopeAlloc);
  9272. bool isArrayAlloc = false;// (objCreateExpr->mArraySizeSpecifier != NULL);
  9273. bool isRawArrayAlloc = (objCreateExpr->mStarToken != NULL);
  9274. if (isScopeAlloc)
  9275. {
  9276. if ((mBfEvalExprFlags & BfEvalExprFlags_FieldInitializer) != 0)
  9277. {
  9278. mModule->Warn(0, "This allocation will only be in scope during the constructor. Consider using a longer-term allocation such as 'new'", objCreateExpr->mNewNode);
  9279. }
  9280. if (objCreateExpr->mNewNode == newToken) // Scope, no target specified
  9281. {
  9282. if (mModule->mParentNodeEntry != NULL)
  9283. {
  9284. if (auto assignExpr = BfNodeDynCastExact<BfAssignmentExpression>(mModule->mParentNodeEntry->mNode))
  9285. {
  9286. if (mModule->mCurMethodState->mCurScope->mCloseNode == NULL)
  9287. {
  9288. // 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
  9289. if ((mBfEvalExprFlags & BfEvalExprFlags_PendingPropSet) == 0)
  9290. mModule->Warn(0, "This allocation will immediately go out of scope. Consider specifying a wider scope target such as 'scope::'", objCreateExpr->mNewNode);
  9291. }
  9292. }
  9293. }
  9294. }
  9295. }
  9296. BfAutoParentNodeEntry autoParentNodeEntry(mModule, objCreateExpr);
  9297. SizedArray<BfAstNode*, 2> dimLengthRefs;
  9298. SizedArray<BfIRValue, 2> dimLengthVals;
  9299. BfArrayType* arrayType = NULL;
  9300. BfType* unresolvedTypeRef = NULL;
  9301. BfType* resolvedTypeRef = NULL;
  9302. if (objCreateExpr->mTypeRef == NULL)
  9303. {
  9304. if ((!mExpectingType) || (!mExpectingType->IsArray()))
  9305. {
  9306. mModule->Fail("Cannot imply array type. Explicitly state array type or use array in an assignment to an array type.", objCreateExpr);
  9307. resolvedTypeRef = mModule->mContext->mBfObjectType;
  9308. unresolvedTypeRef = resolvedTypeRef;
  9309. }
  9310. else
  9311. {
  9312. auto arrayType = (BfArrayType*)mExpectingType;
  9313. unresolvedTypeRef = arrayType->GetUnderlyingType();
  9314. resolvedTypeRef = unresolvedTypeRef;
  9315. }
  9316. }
  9317. else
  9318. {
  9319. if ((objCreateExpr->mTypeRef->IsExact<BfDotTypeReference>()) && (mExpectingType != NULL))
  9320. {
  9321. //mModule->SetElementType(objCreateExpr->mTypeRef, BfSourceElementType_TypeRef);
  9322. if (mExpectingType->IsObject())
  9323. {
  9324. unresolvedTypeRef = mExpectingType;
  9325. if (unresolvedTypeRef->IsArray())
  9326. {
  9327. arrayType = (BfArrayType*)unresolvedTypeRef;
  9328. unresolvedTypeRef = unresolvedTypeRef->GetUnderlyingType();
  9329. isArrayAlloc = true;
  9330. }
  9331. }
  9332. else if (mExpectingType->IsPointer())
  9333. {
  9334. unresolvedTypeRef = mExpectingType->GetUnderlyingType();
  9335. }
  9336. }
  9337. if (unresolvedTypeRef == NULL)
  9338. {
  9339. if (auto arrayTypeRef = BfNodeDynCast<BfArrayTypeRef>(objCreateExpr->mTypeRef))
  9340. {
  9341. isArrayAlloc = true;
  9342. if (auto dotTypeRef = BfNodeDynCast<BfDotTypeReference>(arrayTypeRef->mElementType))
  9343. {
  9344. if ((mExpectingType != NULL) &&
  9345. ((mExpectingType->IsArray()) || (mExpectingType->IsSizedArray())))
  9346. unresolvedTypeRef = mExpectingType->GetUnderlyingType();
  9347. }
  9348. if (unresolvedTypeRef == NULL)
  9349. unresolvedTypeRef = mModule->ResolveTypeRef(arrayTypeRef->mElementType);
  9350. if (unresolvedTypeRef == NULL)
  9351. unresolvedTypeRef = mModule->mContext->mBfObjectType;
  9352. int dimensions = 1;
  9353. if (arrayTypeRef->mParams.size() != 0)
  9354. {
  9355. auto intType = mModule->ResolveTypeDef(mModule->mSystem->mTypeIntPtr);
  9356. for (auto arg : arrayTypeRef->mParams)
  9357. {
  9358. if (auto tokenNode = BfNodeDynCastExact<BfTokenNode>(arg))
  9359. {
  9360. if (tokenNode->GetToken() == BfToken_Comma)
  9361. {
  9362. if (isRawArrayAlloc)
  9363. {
  9364. mModule->Fail("Sized arrays cannot be multidimensional.", tokenNode);
  9365. continue;
  9366. }
  9367. dimensions++;
  9368. if (dimensions == 5)
  9369. {
  9370. mModule->Fail("Too many array dimensions, consider using a jagged array.", tokenNode);
  9371. }
  9372. continue;
  9373. }
  9374. }
  9375. auto expr = BfNodeDynCast<BfExpression>(arg);
  9376. if ((isRawArrayAlloc) && (!dimLengthVals.IsEmpty()))
  9377. {
  9378. mModule->CreateValueFromExpression(expr, intType);
  9379. continue;
  9380. }
  9381. dimLengthRefs.Add(expr);
  9382. BfTypedValue dimLength;
  9383. if (expr == NULL)
  9384. {
  9385. // Not specified
  9386. dimLengthVals.push_back(BfIRValue());
  9387. continue;
  9388. }
  9389. if (arg != NULL)
  9390. {
  9391. dimLength = mModule->CreateValueFromExpression(expr, intType, BfEvalExprFlags_NoCast);
  9392. BfCastFlags castFlags = BfCastFlags_None;
  9393. if ((dimLength) && (dimLength.mType->IsInteger()))
  9394. {
  9395. // Allow uint for size - just force to int
  9396. if (!((BfPrimitiveType*)dimLength.mType)->IsSigned())
  9397. castFlags = BfCastFlags_Explicit;
  9398. }
  9399. if (dimLength)
  9400. dimLength = mModule->Cast(expr, dimLength, intType, castFlags);
  9401. }
  9402. if (!dimLength)
  9403. {
  9404. dimLength = mModule->GetDefaultTypedValue(intType);
  9405. }
  9406. dimLengthVals.push_back(dimLength.mValue);
  9407. }
  9408. }
  9409. if ((arrayTypeRef->mParams.size() == 0) && (objCreateExpr->mOpenToken == NULL))
  9410. mModule->Fail("Array size or array initializer expected", arrayTypeRef->mOpenBracket);
  9411. if (dimensions > 4)
  9412. dimensions = 4;
  9413. if (!isRawArrayAlloc)
  9414. arrayType = mModule->CreateArrayType(unresolvedTypeRef, dimensions);
  9415. }
  9416. if (unresolvedTypeRef == NULL)
  9417. {
  9418. unresolvedTypeRef = ResolveTypeRef(objCreateExpr->mTypeRef, BfPopulateType_Declaration, BfResolveTypeRefFlag_NoResolveGenericParam);
  9419. }
  9420. }
  9421. resolvedTypeRef = unresolvedTypeRef;
  9422. if ((resolvedTypeRef != NULL) && (resolvedTypeRef->IsVar()))
  9423. resolvedTypeRef = unresolvedTypeRef;
  9424. }
  9425. if (resolvedTypeRef == NULL)
  9426. return;
  9427. auto resultType = resolvedTypeRef;
  9428. if ((resolvedTypeRef->IsInterface()) && (!isArrayAlloc))
  9429. {
  9430. mModule->Fail("Cannot create an instance of an interface", objCreateExpr->mTypeRef);
  9431. resolvedTypeRef = mModule->mContext->mBfObjectType;
  9432. }
  9433. BfTypeInstance* typeInstance = resolvedTypeRef->ToTypeInstance();
  9434. int elementSize = resolvedTypeRef->mSize;
  9435. int elementAlign = resolvedTypeRef->mAlign;
  9436. BfIRType allocType = mModule->mBfIRBuilder->MapType(resolvedTypeRef);
  9437. if (typeInstance != NULL)
  9438. {
  9439. if (!mModule->mCurTypeInstance->mResolvingVarField)
  9440. mModule->PopulateType(typeInstance);
  9441. if ((typeInstance->mTypeDef->mIsDelegate) && (!isArrayAlloc))
  9442. mModule->Fail("Delegates must be constructed through delegate binding", objCreateExpr->mTypeRef);
  9443. elementSize = BF_MAX(0, typeInstance->mInstSize);
  9444. elementAlign = typeInstance->mInstAlign;
  9445. allocType = mModule->mBfIRBuilder->MapTypeInst(typeInstance);
  9446. }
  9447. if (isAppendAlloc)
  9448. {
  9449. if (!mModule->mCurTypeInstance->IsObject())
  9450. {
  9451. mModule->Fail("Append allocations are only allowed in classes", objCreateExpr->mNewNode);
  9452. isAppendAlloc = false;
  9453. }
  9454. else if ((mBfEvalExprFlags & BfEvalExprFlags_VariableDeclaration) == 0)
  9455. {
  9456. mModule->Fail("Append allocations are only allowed as local variable initializers in constructor body", objCreateExpr->mNewNode);
  9457. isAppendAlloc = false;
  9458. }
  9459. else
  9460. {
  9461. auto methodDef = mModule->mCurMethodInstance->mMethodDef;
  9462. if (methodDef->mMethodType == BfMethodType_CtorCalcAppend)
  9463. {
  9464. mModule->Fail("Append allocations are only allowed as local variable declarations in the main method body", objCreateExpr->mNewNode);
  9465. isAppendAlloc = false;
  9466. }
  9467. else if (!methodDef->mHasAppend)
  9468. {
  9469. mModule->Fail("Append allocations can only be used on constructors with [AllowAppend] specified", objCreateExpr->mNewNode);
  9470. isAppendAlloc = false;
  9471. }
  9472. else if (methodDef->mMethodType != BfMethodType_Ctor)
  9473. {
  9474. mModule->Fail("Append allocations are only allowed in constructors", objCreateExpr->mNewNode);
  9475. isAppendAlloc = false;
  9476. }
  9477. else if (methodDef->mIsStatic)
  9478. {
  9479. mModule->Fail("Append allocations are only allowed in non-static constructors", objCreateExpr->mNewNode);
  9480. isAppendAlloc = false;
  9481. }
  9482. }
  9483. }
  9484. if (isArrayAlloc)
  9485. {
  9486. const int MAX_DIMENSIONS = 2;
  9487. int dimensions = 1;
  9488. if (arrayType != NULL)
  9489. {
  9490. dimensions = arrayType->mDimensions;
  9491. mModule->AddDependency(arrayType, mModule->mCurTypeInstance, BfDependencyMap::DependencyFlag_Calls);
  9492. }
  9493. bool zeroMemory = true;
  9494. if (objCreateExpr->mOpenToken != NULL)
  9495. {
  9496. if ((objCreateExpr->mArguments.size() == 1) &&
  9497. (BfNodeDynCastExact<BfUninitializedExpression>(objCreateExpr->mArguments[0]) != NULL))
  9498. {
  9499. // Special case for a single "{ ? }"
  9500. zeroMemory = false;
  9501. }
  9502. else
  9503. {
  9504. SizedArray<int64, 2> dimLengths;
  9505. if (dimLengthVals.size() != 0)
  9506. {
  9507. for (int dim = 0; dim < dimensions; dim++)
  9508. {
  9509. BfIRValue dimLengthVal;
  9510. if (dim < (int)dimLengthVals.size())
  9511. dimLengthVal = dimLengthVals[dim];
  9512. if (!dimLengthVal)
  9513. {
  9514. dimLengths.push_back(-1);
  9515. continue;
  9516. }
  9517. auto constant = mModule->mBfIRBuilder->GetConstant(dimLengthVal);
  9518. if ((constant != NULL) && (mModule->mBfIRBuilder->IsInt(constant->mTypeCode)))
  9519. {
  9520. int64 dimLength = constant->mInt64;
  9521. dimLengths.push_back(dimLength);
  9522. }
  9523. else
  9524. {
  9525. mModule->Fail("A constant length is required when using an initializer", dimLengthRefs[dim]);
  9526. dimLengths.push_back(-1);
  9527. }
  9528. }
  9529. }
  9530. // Ending in an ", )" means we need to zero-fill ending
  9531. zeroMemory = objCreateExpr->mCommas.size() >= objCreateExpr->mArguments.size();
  9532. bool hasFailed = false;
  9533. ProcessArrayInitializer(objCreateExpr->mOpenToken, objCreateExpr->mArguments, objCreateExpr->mCommas, objCreateExpr->mCloseToken, dimensions, dimLengths, 0, hasFailed);
  9534. dimLengthVals.resize(dimLengths.size());
  9535. for (int i = 0; i < (int)dimLengthVals.size(); i++)
  9536. {
  9537. if (!dimLengthVals[i])
  9538. {
  9539. auto intType = mModule->GetPrimitiveType(BfTypeCode_IntPtr);
  9540. dimLengthVals[i] = mModule->GetConstValue(dimLengths[i], intType);
  9541. }
  9542. }
  9543. }
  9544. }
  9545. while ((int)dimLengthVals.size() < dimensions)
  9546. dimLengthVals.push_back(mModule->GetConstValue(0));
  9547. BfTypedValue arrayValue;
  9548. BfIRValue arraySize;
  9549. for (BfIRValue dimSize : dimLengthVals)
  9550. {
  9551. if (!arraySize)
  9552. arraySize = dimSize;
  9553. else
  9554. arraySize = mModule->mBfIRBuilder->CreateMul(arraySize, dimSize);
  9555. }
  9556. BfAllocFlags allocFlags = BfAllocFlags_None;
  9557. if (isRawArrayAlloc)
  9558. allocFlags = (BfAllocFlags)(allocFlags | BfAllocFlags_RawArray);
  9559. int writeIdx = 0;
  9560. std::function<void(BfIRValue addr, int curDim, const BfSizedArray<BfExpression*>& valueExprs)> _HandleInitExprs = [&](BfIRValue addr, int curDim, const BfSizedArray<BfExpression*>& valueExprs)
  9561. {
  9562. int exprIdx = 0;
  9563. int dimWriteIdx = 0;
  9564. bool isUninit = false;
  9565. int dimLength = -1;
  9566. if (dimLengthVals[curDim].IsConst())
  9567. {
  9568. auto constant = mModule->mBfIRBuilder->GetConstant(dimLengthVals[curDim]);
  9569. dimLength = constant->mInt32;
  9570. }
  9571. while (exprIdx < (int)valueExprs.size())
  9572. {
  9573. auto initExpr = valueExprs[exprIdx];
  9574. exprIdx++;
  9575. if (!initExpr)
  9576. break;
  9577. if (auto unintExpr = BfNodeDynCastExact<BfUninitializedExpression>(initExpr))
  9578. {
  9579. isUninit = true;
  9580. break;
  9581. }
  9582. if (exprIdx > dimLength)
  9583. break;
  9584. if (curDim < dimensions - 1)
  9585. {
  9586. if (auto innerTupleExpr = BfNodeDynCast<BfTupleExpression>(initExpr))
  9587. {
  9588. _HandleInitExprs(addr, curDim + 1, innerTupleExpr->mValues);
  9589. }
  9590. else if (auto parenExpr = BfNodeDynCast<BfParenthesizedExpression>(initExpr))
  9591. {
  9592. SizedArray<BfExpression*, 1> values;
  9593. values.Add(parenExpr->mExpression);
  9594. _HandleInitExprs(addr, curDim + 1, values);
  9595. }
  9596. else if (auto innerInitExpr = BfNodeDynCast<BfCollectionInitializerExpression>(initExpr))
  9597. {
  9598. _HandleInitExprs(addr, curDim + 1, innerInitExpr->mValues);
  9599. }
  9600. dimWriteIdx++;
  9601. continue;
  9602. }
  9603. auto elemAddr = mModule->CreateIndexedValue(resultType, addr, writeIdx);
  9604. writeIdx++;
  9605. dimWriteIdx++;
  9606. BfTypedValue elemPtrTypedVal = BfTypedValue(elemAddr, resultType, BfTypedValueKind_Addr);
  9607. BfExprEvaluator exprEvaluator(mModule);
  9608. exprEvaluator.mExpectingType = resultType;
  9609. exprEvaluator.mReceivingValue = &elemPtrTypedVal;
  9610. exprEvaluator.Evaluate(initExpr);
  9611. exprEvaluator.GetResult();
  9612. if (exprEvaluator.mReceivingValue == NULL)
  9613. {
  9614. // We wrote directly to the array in-place, we're done with this element
  9615. continue;
  9616. }
  9617. auto storeValue = exprEvaluator.mResult;
  9618. if (!storeValue)
  9619. continue;
  9620. storeValue = mModule->Cast(initExpr, storeValue, resultType);
  9621. if (!storeValue)
  9622. continue;
  9623. if (!resultType->IsValuelessType())
  9624. {
  9625. storeValue = mModule->LoadValue(storeValue);
  9626. mModule->mBfIRBuilder->CreateStore(storeValue.mValue, elemAddr);
  9627. }
  9628. }
  9629. int clearFromIdx = writeIdx;
  9630. int sectionElemCount = 1;
  9631. BfIRValue numElemsLeft = arraySize;
  9632. if (dimLength != -1)
  9633. {
  9634. int clearCount = dimLength - dimWriteIdx;
  9635. if (clearCount > 0)
  9636. {
  9637. for (int checkDim = curDim + 1; checkDim < (int)dimLengthVals.size(); checkDim++)
  9638. {
  9639. if (dimLengthVals[checkDim].IsConst())
  9640. {
  9641. auto constant = mModule->mBfIRBuilder->GetConstant(dimLengthVals[checkDim]);
  9642. clearCount *= constant->mInt32;
  9643. sectionElemCount *= constant->mInt32;
  9644. }
  9645. }
  9646. }
  9647. writeIdx += clearCount;
  9648. numElemsLeft = mModule->GetConstValue(clearCount);
  9649. }
  9650. // Actually leave it alone?
  9651. if ((isUninit) && (mModule->IsOptimized()))
  9652. return;
  9653. bool doClear = true;
  9654. if (numElemsLeft.IsConst())
  9655. {
  9656. auto constant = mModule->mBfIRBuilder->GetConstant(numElemsLeft);
  9657. doClear = constant->mInt64 > 0;
  9658. }
  9659. if (doClear)
  9660. {
  9661. // We multiply by GetStride. This relies on the fact that we over-allocate on the array allocation -- the last
  9662. // element doesn't need to be padded out to the element alignment, but we do anyway. Otherwise this would be
  9663. // a more complicated computation
  9664. auto clearBytes = mModule->mBfIRBuilder->CreateMul(numElemsLeft, mModule->GetConstValue(resultType->GetStride()));
  9665. if (isUninit)
  9666. {
  9667. // Limit to a reasonable number of bytes to stomp with 0xCC
  9668. int maxStompBytes = BF_MIN(128, resultType->GetStride() * sectionElemCount);
  9669. if (clearBytes.IsConst())
  9670. {
  9671. auto constant = mModule->mBfIRBuilder->GetConstant(clearBytes);
  9672. if (constant->mInt64 > maxStompBytes)
  9673. clearBytes = mModule->GetConstValue(maxStompBytes);
  9674. }
  9675. else
  9676. {
  9677. auto insertBlock = mModule->mBfIRBuilder->GetInsertBlock();
  9678. auto gtBlock = mModule->mBfIRBuilder->CreateBlock("unint.gt");
  9679. auto contBlock = mModule->mBfIRBuilder->CreateBlock("unint.cont");
  9680. auto cmp = mModule->mBfIRBuilder->CreateCmpLTE(clearBytes, mModule->GetConstValue(maxStompBytes), true);
  9681. mModule->mBfIRBuilder->CreateCondBr(cmp, contBlock, gtBlock);
  9682. mModule->mBfIRBuilder->AddBlock(gtBlock);
  9683. mModule->mBfIRBuilder->SetInsertPoint(gtBlock);
  9684. mModule->mBfIRBuilder->CreateBr(contBlock);
  9685. mModule->mBfIRBuilder->AddBlock(contBlock);
  9686. mModule->mBfIRBuilder->SetInsertPoint(contBlock);
  9687. auto phi = mModule->mBfIRBuilder->CreatePhi(mModule->mBfIRBuilder->MapType(mModule->GetPrimitiveType(BfTypeCode_IntPtr)), 2);
  9688. mModule->mBfIRBuilder->AddPhiIncoming(phi, clearBytes, insertBlock);
  9689. mModule->mBfIRBuilder->AddPhiIncoming(phi, mModule->GetConstValue(maxStompBytes), gtBlock);
  9690. clearBytes = phi;
  9691. }
  9692. }
  9693. mModule->mBfIRBuilder->PopulateType(resultType);
  9694. mModule->mBfIRBuilder->CreateMemSet(mModule->CreateIndexedValue(resultType, addr, clearFromIdx),
  9695. mModule->mBfIRBuilder->CreateConst(BfTypeCode_Int8, isUninit ? 0xCC : 0), clearBytes, resultType->mAlign);
  9696. }
  9697. };
  9698. if (isRawArrayAlloc)
  9699. {
  9700. // 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
  9701. BfType* ptrType = mModule->CreatePointerType(resultType);
  9702. if (isAppendAlloc)
  9703. arrayValue = BfTypedValue(mModule->AppendAllocFromType(resultType, BfIRValue(), 0, arraySize, (int)dimLengthVals.size(), isRawArrayAlloc, false), ptrType);
  9704. else
  9705. {
  9706. arrayValue = BfTypedValue(mModule->AllocFromType(resultType, allocTarget, BfIRValue(), arraySize, (int)dimLengthVals.size(), allocFlags, allocTarget.mAlignOverride), ptrType);
  9707. }
  9708. _HandleInitExprs(arrayValue.mValue, 0, objCreateExpr->mArguments);
  9709. mResult = arrayValue;
  9710. return;
  9711. }
  9712. if (dimLengthVals.size() > 4)
  9713. {
  9714. dimLengthVals.RemoveRange(4, dimLengthVals.size() - 4);
  9715. mModule->Fail("Too many array dimensions, consider using a jagged array.", objCreateExpr);
  9716. }
  9717. if (isAppendAlloc)
  9718. arrayValue = BfTypedValue(mModule->AppendAllocFromType(resultType, BfIRValue(), 0, arraySize, (int)dimLengthVals.size(), isRawArrayAlloc, zeroMemory), arrayType);
  9719. else
  9720. {
  9721. arrayValue = BfTypedValue(mModule->AllocFromType(resultType, allocTarget, BfIRValue(), arraySize, (int)dimLengthVals.size(), allocFlags, allocTarget.mAlignOverride), arrayType);
  9722. if (isScopeAlloc)
  9723. {
  9724. // See notes below on "general" SkipObjectAccessCheck usage on why we can do this
  9725. mModule->SkipObjectAccessCheck(arrayValue);
  9726. }
  9727. }
  9728. //mModule->InitTypeInst(arrayValue, scopeData);
  9729. BfAstNode* refNode = objCreateExpr->mTypeRef;
  9730. while (true)
  9731. {
  9732. if (auto arrayRef = BfNodeDynCast<BfElementedTypeRef>(refNode))
  9733. {
  9734. refNode = arrayRef->mElementType;
  9735. continue;
  9736. }
  9737. break;
  9738. }
  9739. BfResolvedArgs resolvedArgs;
  9740. if (autoComplete != NULL)
  9741. {
  9742. SetAndRestoreValue<bool> prevCapturing(autoComplete->mIsCapturingMethodMatchInfo, false);
  9743. MatchConstructor(refNode, objCreateExpr, arrayValue, arrayType, resolvedArgs, false, false);
  9744. }
  9745. else
  9746. {
  9747. MatchConstructor(refNode, objCreateExpr, arrayValue, arrayType, resolvedArgs, false, false);
  9748. }
  9749. //TODO: Assert 'length' var is at slot 1
  9750. mModule->PopulateType(arrayType->mBaseType, BfPopulateType_DataAndMethods);
  9751. mModule->mBfIRBuilder->PopulateType(arrayType);
  9752. auto arrayBits = mModule->mBfIRBuilder->CreateBitCast(arrayValue.mValue, mModule->mBfIRBuilder->MapTypeInstPtr(arrayType->mBaseType));
  9753. int arrayLengthBitCount = arrayType->GetLengthBitCount();
  9754. if (arrayLengthBitCount == 0)
  9755. {
  9756. mModule->Fail("INTERNAL ERROR: Unable to find array 'length' field", objCreateExpr);
  9757. return;
  9758. }
  9759. auto addr = mModule->mBfIRBuilder->CreateInBoundsGEP(arrayBits, 0, 1/*, "length"*/);
  9760. if (arrayLengthBitCount == 64)
  9761. mModule->mBfIRBuilder->CreateAlignedStore(arraySize, addr, 8);
  9762. else
  9763. {
  9764. auto arraySize32 = mModule->mBfIRBuilder->CreateNumericCast(arraySize, true, BfTypeCode_Int32);
  9765. mModule->mBfIRBuilder->CreateAlignedStore(arraySize32, addr, 4);
  9766. }
  9767. for (int lowerDim = 1; lowerDim < (int)dimLengthVals.size(); lowerDim++)
  9768. {
  9769. addr = mModule->mBfIRBuilder->CreateInBoundsGEP(arrayValue.mValue, 0, lowerDim/*, "dimLength"*/); // mDimLengthX
  9770. auto lowerDimVal = mModule->mBfIRBuilder->CreateNumericCast(dimLengthVals[lowerDim], true, (arrayLengthBitCount == 64) ? BfTypeCode_Int64 : BfTypeCode_Int32);
  9771. mModule->mBfIRBuilder->CreateStore(lowerDimVal, addr);
  9772. }
  9773. if (resultType->IsValuelessType())
  9774. addr = mModule->mBfIRBuilder->GetFakeVal();
  9775. else
  9776. addr = mModule->mBfIRBuilder->CreateInBoundsGEP(arrayValue.mValue, 0, (int)dimLengthVals.size()/*, "elem"*/); // mFirstElement
  9777. _HandleInitExprs(addr, 0, objCreateExpr->mArguments);
  9778. mResult = arrayValue;
  9779. return;
  9780. }
  9781. else
  9782. {
  9783. if ((!resolvedTypeRef->IsObjectOrInterface()) && (!resolvedTypeRef->IsGenericParam()))
  9784. {
  9785. resultType = mModule->CreatePointerType(resolvedTypeRef);
  9786. }
  9787. }
  9788. if ((isStackAlloc) && (mModule->mCurMethodState == NULL))
  9789. {
  9790. mModule->Fail("Cannot use 'stack' here", objCreateExpr->mNewNode);
  9791. isStackAlloc = false;
  9792. isScopeAlloc = false;
  9793. }
  9794. bool isGenericParam = unresolvedTypeRef->IsGenericParam();
  9795. if (resolvedTypeRef->IsGenericParam())
  9796. {
  9797. auto genericConstraint = mModule->GetGenericParamInstance((BfGenericParamType*)resolvedTypeRef);
  9798. if (genericConstraint->mTypeConstraint == NULL)
  9799. {
  9800. if ((genericConstraint->mGenericParamFlags & (BfGenericParamFlag_New | BfGenericParamFlag_Struct)) == 0)
  9801. {
  9802. mModule->Fail(StrFormat("Must add 'where %s : new' constraint to generic parameter to instantiate type", genericConstraint->GetGenericParamDef()->mName.c_str()), objCreateExpr->mTypeRef);
  9803. }
  9804. if (objCreateExpr->mArguments.size() != 0)
  9805. {
  9806. mModule->Fail(StrFormat("Only default parameterless constructors can be called on generic argument '%s'", genericConstraint->GetGenericParamDef()->mName.c_str()), objCreateExpr->mTypeRef);
  9807. }
  9808. }
  9809. resultType = resolvedTypeRef;
  9810. bool isValueType = ((genericConstraint->mGenericParamFlags & BfGenericParamFlag_Struct) != 0);
  9811. if (genericConstraint->mTypeConstraint != NULL)
  9812. isValueType = genericConstraint->mTypeConstraint->IsValueType();
  9813. if (isValueType)
  9814. resultType = mModule->CreatePointerType(resultType);
  9815. mResult.mType = resultType;
  9816. if (typeInstance == NULL)
  9817. {
  9818. mResult = mModule->GetDefaultTypedValue(resultType);
  9819. return;
  9820. }
  9821. }
  9822. else if (resolvedTypeRef->IsSizedArray())
  9823. {
  9824. // Handle the case of "int[3]* val = new .(1, 2, 3)"
  9825. if (auto dotTypeRef = BfNodeDynCastExact<BfDotTypeReference>(objCreateExpr->mTypeRef))
  9826. {
  9827. BfIRValue allocValue;
  9828. if (isAppendAlloc)
  9829. allocValue = mModule->AppendAllocFromType(resolvedTypeRef, BfIRValue(), 0, BfIRValue(), 0, false, false);
  9830. else
  9831. allocValue = mModule->AllocFromType(resolvedTypeRef, allocTarget, BfIRValue(), BfIRValue(), 0, BfAllocFlags_None);
  9832. auto result = BfTypedValue(allocValue, resolvedTypeRef, BfTypedValueKind_Addr);
  9833. InitializedSizedArray((BfSizedArrayType*)resolvedTypeRef, objCreateExpr->mOpenToken, objCreateExpr->mArguments, objCreateExpr->mCommas, objCreateExpr->mCloseToken, &result);
  9834. // Turn from an addr of a sized array to pointer of sized array
  9835. mResult = BfTypedValue(mResult.mValue, resultType);
  9836. return;
  9837. }
  9838. }
  9839. SetAndRestoreValue<bool> prevNoBind(mNoBind, mNoBind || isGenericParam);
  9840. if ((typeInstance != NULL) && (typeInstance->mTypeDef->mIsAbstract))
  9841. {
  9842. mModule->Fail("Cannot create an instance of an abstract class", objCreateExpr->mTypeRef);
  9843. return;
  9844. }
  9845. BfFunctionBindResult bindResult;
  9846. bindResult.mSkipThis = true;
  9847. bindResult.mWantsArgs = true;
  9848. SetAndRestoreValue<BfFunctionBindResult*> prevBindResult(mFunctionBindResult, &bindResult);
  9849. BfIRValue appendSizeValue;
  9850. //BfTypedValue emtpyThis(BfIRValue(), resolvedTypeRef, resolvedTypeRef->IsStruct());
  9851. BfTypedValue emtpyThis(mModule->mBfIRBuilder->GetFakeVal(), resolvedTypeRef, resolvedTypeRef->IsStruct());
  9852. BfResolvedArgs argValues(objCreateExpr->mOpenToken, &objCreateExpr->mArguments, &objCreateExpr->mCommas, objCreateExpr->mCloseToken);
  9853. ResolveArgValues(argValues, BfResolveArgFlag_DeferParamEval); ////
  9854. /*SetAndRestoreValue<BfAttributeState*> prevAttributeState(mModule->mAttributeState, mPrefixedAttributeState);
  9855. if (mPrefixedAttributeState != NULL)
  9856. mPrefixedAttributeState->mUsed = true;*/
  9857. if (typeInstance == NULL)
  9858. {
  9859. // No CTOR needed
  9860. if (objCreateExpr->mArguments.size() != 0)
  9861. {
  9862. mModule->Fail(StrFormat("Only default parameterless constructors can be called on primitive type '%s'", mModule->TypeToString(resolvedTypeRef).c_str()), objCreateExpr->mTypeRef);
  9863. }
  9864. }
  9865. else if ((autoComplete != NULL) && (objCreateExpr->mOpenToken != NULL))
  9866. {
  9867. auto wasCapturingMethodInfo = autoComplete->mIsCapturingMethodMatchInfo;
  9868. autoComplete->CheckInvocation(objCreateExpr, objCreateExpr->mOpenToken, objCreateExpr->mCloseToken, objCreateExpr->mCommas);
  9869. MatchConstructor(objCreateExpr->mTypeRef, objCreateExpr, emtpyThis, typeInstance, argValues, false, true);
  9870. if ((wasCapturingMethodInfo) && (!autoComplete->mIsCapturingMethodMatchInfo))
  9871. {
  9872. autoComplete->mIsCapturingMethodMatchInfo = true;
  9873. BF_ASSERT(autoComplete->mMethodMatchInfo != NULL);
  9874. }
  9875. else
  9876. autoComplete->mIsCapturingMethodMatchInfo = false;
  9877. }
  9878. else
  9879. {
  9880. MatchConstructor(objCreateExpr->mTypeRef, objCreateExpr, emtpyThis, typeInstance, argValues, false, true);
  9881. }
  9882. mModule->ValidateAllocation(typeInstance, objCreateExpr->mTypeRef);
  9883. //prevAttributeState.Restore();
  9884. prevBindResult.Restore();
  9885. /*if ((typeInstance != NULL) && (bindResult.mMethodInstance == NULL))
  9886. {
  9887. mModule->AssertErrorState();
  9888. return;
  9889. }*/
  9890. int allocAlign = resolvedTypeRef->mAlign;
  9891. if (typeInstance != NULL)
  9892. allocAlign = typeInstance->mInstAlign;
  9893. int appendAllocAlign = 0;
  9894. if ((bindResult.mMethodInstance != NULL) && (bindResult.mMethodInstance->mMethodDef->mHasAppend))
  9895. {
  9896. if (!bindResult.mFunc)
  9897. {
  9898. BF_ASSERT((!mModule->HasCompiledOutput()) || (mModule->mBfIRBuilder->mIgnoreWrites));
  9899. appendSizeValue = mModule->GetConstValue(0);
  9900. }
  9901. else
  9902. {
  9903. auto calcAppendMethodModule = mModule->GetMethodInstanceAtIdx(bindResult.mMethodInstance->GetOwner(), bindResult.mMethodInstance->mMethodDef->mIdx + 1, BF_METHODNAME_CALCAPPEND);
  9904. SizedArray<BfIRValue, 2> irArgs;
  9905. if (bindResult.mIRArgs.size() > 1)
  9906. irArgs.Insert(0, &bindResult.mIRArgs[1], bindResult.mIRArgs.size() - 1);
  9907. BfTypedValue appendSizeTypedValue = mModule->TryConstCalcAppend(calcAppendMethodModule.mMethodInstance, irArgs);
  9908. if (!appendSizeTypedValue)
  9909. {
  9910. BF_ASSERT(calcAppendMethodModule.mFunc);
  9911. appendSizeTypedValue = CreateCall(calcAppendMethodModule.mMethodInstance, calcAppendMethodModule.mFunc, false, irArgs);
  9912. BF_ASSERT(appendSizeTypedValue.mType == mModule->GetPrimitiveType(BfTypeCode_IntPtr));
  9913. }
  9914. appendSizeValue = appendSizeTypedValue.mValue;
  9915. allocAlign = BF_MAX(allocAlign, calcAppendMethodModule.mMethodInstance->mAppendAllocAlign);
  9916. appendAllocAlign = calcAppendMethodModule.mMethodInstance->mAppendAllocAlign;
  9917. }
  9918. if (appendAllocAlign != 0)
  9919. {
  9920. int endingAlign = typeInstance->GetEndingInstanceAlignment();
  9921. if (endingAlign % appendAllocAlign != 0)
  9922. {
  9923. int extraSize = appendAllocAlign - (endingAlign % appendAllocAlign);
  9924. appendSizeValue = mModule->mBfIRBuilder->CreateAdd(appendSizeValue, mModule->GetConstValue(extraSize));
  9925. }
  9926. }
  9927. }
  9928. // WTF? I'm not even sure this is correct - add more tests
  9929. appendAllocAlign = BF_MAX(appendAllocAlign, allocAlign);
  9930. BfIRValue allocValue;
  9931. if (isAppendAlloc)
  9932. allocValue = mModule->AppendAllocFromType(resolvedTypeRef, appendSizeValue, appendAllocAlign);
  9933. else
  9934. {
  9935. allocValue = mModule->AllocFromType(resolvedTypeRef, allocTarget, appendSizeValue, BfIRValue(), 0, BfAllocFlags_None, allocAlign);
  9936. }
  9937. mResult = BfTypedValue(allocValue, resultType);
  9938. if (isScopeAlloc)
  9939. {
  9940. // This allows readonly (ie: 'let') local usage to not require an access check. No matter what scope the alloc is tied to, the
  9941. // lifetime of the local variable will be no longer than that of the allocated value
  9942. mModule->SkipObjectAccessCheck(mResult);
  9943. }
  9944. /*if (typeInstance != NULL)
  9945. {
  9946. mModule->InitTypeInst(mResult, scopeData, true);
  9947. }
  9948. if (isStackAlloc)
  9949. {
  9950. mModule->AddStackAlloc(mResult, objCreateExpr, scopeData);
  9951. }*/
  9952. if (mResult)
  9953. {
  9954. if (bindResult.mMethodInstance == NULL)
  9955. {
  9956. // Why did we have this? It was already zeroed right?
  9957. // Zero
  9958. //mModule->mBfIRBuilder->CreateMemSet(mResult.mValue, mModule->GetConstValue8(0), mModule->GetConstValue(resolvedTypeRef->mSize), resolvedTypeRef->mAlign);
  9959. }
  9960. else if (bindResult.mFunc)
  9961. {
  9962. if (typeInstance->IsObject())
  9963. {
  9964. bool wantsCtorClear = true;
  9965. if (mModule->mCompiler->mOptions.mEnableRealtimeLeakCheck)
  9966. {
  9967. // Dbg_ObjectAlloc clears internally so we don't need to call CtorClear for those
  9968. if ((!isStackAlloc) && (!allocTarget.mCustomAllocator) && (allocTarget.mScopedInvocationTarget == NULL))
  9969. wantsCtorClear = false;
  9970. }
  9971. if (wantsCtorClear)
  9972. {
  9973. auto ctorClear = mModule->GetMethodByName(typeInstance, "__BfCtorClear");
  9974. if (!ctorClear)
  9975. {
  9976. mModule->AssertErrorState();
  9977. }
  9978. else
  9979. {
  9980. SizedArray<BfIRValue, 1> irArgs;
  9981. irArgs.push_back(mResult.mValue);
  9982. CreateCall(ctorClear.mMethodInstance, ctorClear.mFunc, false, irArgs);
  9983. }
  9984. }
  9985. if ((isStackAlloc) && (mModule->mCompiler->mOptions.mEnableRealtimeLeakCheck))
  9986. {
  9987. BfMethodInstance* markMethod = mModule->GetRawMethodByName(mModule->mContext->mBfObjectType, "GCMarkMembers");
  9988. BF_ASSERT(markMethod != NULL);
  9989. if (markMethod != NULL)
  9990. {
  9991. auto& vtableEntry = typeInstance->mVirtualMethodTable[markMethod->mVirtualTableIdx];
  9992. if (vtableEntry.mImplementingMethod.mTypeInstance != mModule->mContext->mBfObjectType)
  9993. {
  9994. auto impMethodInstance = (BfMethodInstance*)vtableEntry.mImplementingMethod;
  9995. bool needsCall = false;
  9996. if (impMethodInstance != NULL)
  9997. {
  9998. needsCall = impMethodInstance->mMethodDef->mBody != NULL;
  9999. }
  10000. else
  10001. {
  10002. needsCall = true;
  10003. BF_ASSERT(vtableEntry.mImplementingMethod.mKind == BfMethodRefKind_AmbiguousRef);
  10004. }
  10005. if (needsCall)
  10006. {
  10007. SizedArray<BfIRValue, 1> irArgs;
  10008. irArgs.push_back(mModule->mBfIRBuilder->CreateBitCast(mResult.mValue, mModule->mBfIRBuilder->MapType(mModule->mContext->mBfObjectType)));
  10009. auto gcType = mModule->ResolveTypeDef(mModule->mCompiler->mGCTypeDef);
  10010. BF_ASSERT(gcType != NULL);
  10011. if (gcType != NULL)
  10012. {
  10013. auto addStackObjMethod = mModule->GetMethodByName(gcType->ToTypeInstance(), "AddStackMarkableObject", 1);
  10014. BF_ASSERT(addStackObjMethod);
  10015. if (addStackObjMethod)
  10016. {
  10017. mModule->mBfIRBuilder->CreateCall(addStackObjMethod.mFunc, irArgs);
  10018. }
  10019. auto removeStackObjMethod = mModule->GetMethodByName(gcType->ToTypeInstance(), "RemoveStackMarkableObject", 1);
  10020. BF_ASSERT(removeStackObjMethod);
  10021. if (removeStackObjMethod)
  10022. {
  10023. mModule->AddDeferredCall(removeStackObjMethod, irArgs, allocTarget.mScopeData, objCreateExpr);
  10024. }
  10025. }
  10026. }
  10027. }
  10028. }
  10029. }
  10030. }
  10031. if ((bindResult.mMethodInstance->mMethodDef->mHasAppend) && (mResult.mType->IsObject()))
  10032. {
  10033. BF_ASSERT(bindResult.mIRArgs[0].IsFake());
  10034. auto typeInst = mResult.mType->ToTypeInstance();
  10035. auto intPtrType = mModule->GetPrimitiveType(BfTypeCode_IntPtr);
  10036. auto thisVal = mResult;
  10037. BfIRValue intPtrVal = mModule->CreateAlloca(intPtrType);
  10038. auto intPtrThisVal = mModule->mBfIRBuilder->CreatePtrToInt(thisVal.mValue, (intPtrType->mSize == 4) ? BfTypeCode_Int32 : BfTypeCode_Int64);
  10039. auto curValPtr = mModule->mBfIRBuilder->CreateAdd(intPtrThisVal, mModule->GetConstValue(typeInst->mInstSize, intPtrType));
  10040. mModule->mBfIRBuilder->CreateStore(curValPtr, intPtrVal);
  10041. bindResult.mIRArgs[0] = intPtrVal;
  10042. }
  10043. if (!typeInstance->IsValuelessType())
  10044. bindResult.mIRArgs.Insert(0, mResult.mValue);
  10045. CreateCall(bindResult.mMethodInstance, bindResult.mFunc, false, bindResult.mIRArgs);
  10046. }
  10047. }
  10048. // if ((mResult) && (!isArrayAlloc) && (objCreateExpr->mCollectionInitializer != NULL))
  10049. // {
  10050. // for (BfExpression* initExpr : objCreateExpr->mCollectionInitializer->mValues)
  10051. // {
  10052. // SizedArray<ASTREF(BfExpression*), 1> exprs;
  10053. //
  10054. // if (auto groupExpr = BfNodeDynCast<BfCollectionInitializerExpression>(initExpr))
  10055. // {
  10056. // for (BfExpression* argExpr : groupExpr->mValues)
  10057. // exprs.push_back(argExpr);
  10058. // }
  10059. // else
  10060. // {
  10061. // exprs.push_back(initExpr);
  10062. // }
  10063. //
  10064. // BfExprEvaluator exprEvaluator(mModule);
  10065. // SizedArray<BfExpression*, 8> copiedArgs;
  10066. // for (BfExpression* arg : exprs)
  10067. // copiedArgs.push_back(arg);
  10068. // BfResolvedArgs argValues(copiedArgs);
  10069. // exprEvaluator.ResolveArgValues(argValues);
  10070. // exprEvaluator.MatchMethod(initExpr, NULL, mResult, false, false, "Add", argValues, NULL);
  10071. // }
  10072. // }
  10073. }
  10074. void BfExprEvaluator::Visit(BfBoxExpression* boxExpr)
  10075. {
  10076. /*if ((boxExpr->mAllocNode == NULL) || (boxExpr->mExpression == NULL))
  10077. {
  10078. mModule->AssertErrorState();
  10079. return;
  10080. }*/
  10081. BfTokenNode* newToken = NULL;
  10082. BfAllocTarget allocTarget = ResolveAllocTarget(boxExpr->mAllocNode, newToken);
  10083. if ((boxExpr->mAllocNode != NULL) && (boxExpr->mAllocNode->mToken == BfToken_Scope))
  10084. {
  10085. if ((mBfEvalExprFlags & BfEvalExprFlags_FieldInitializer) != 0)
  10086. {
  10087. mModule->Warn(0, "This allocation will only be in scope during the constructor. Consider using a longer-term allocation such as 'new'", boxExpr->mAllocNode);
  10088. }
  10089. }
  10090. if (boxExpr->mExpression == NULL)
  10091. {
  10092. mModule->AssertErrorState();
  10093. return;
  10094. }
  10095. auto exprValue = mModule->CreateValueFromExpression(boxExpr->mExpression);
  10096. if (exprValue)
  10097. {
  10098. if (exprValue.mType->IsGenericParam())
  10099. {
  10100. BF_ASSERT(mModule->mCurMethodInstance->mIsUnspecialized);
  10101. auto genericParamTarget = (BfGenericParamType*)exprValue.mType;
  10102. auto genericParamInstance = mModule->GetGenericParamInstance(genericParamTarget);
  10103. bool isBoxable = false;
  10104. if (genericParamInstance->mGenericParamFlags & (BfGenericParamFlag_Struct | BfGenericParamFlag_StructPtr))
  10105. isBoxable = true;
  10106. if ((genericParamInstance->mTypeConstraint != NULL) && (exprValue.mType->IsValueTypeOrValueTypePtr()))
  10107. isBoxable = true;
  10108. if (isBoxable)
  10109. {
  10110. mResult = mModule->GetDefaultTypedValue(mModule->mContext->mBfObjectType);
  10111. return;
  10112. }
  10113. }
  10114. if (!exprValue.mType->IsValueTypeOrValueTypePtr())
  10115. {
  10116. 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);
  10117. return;
  10118. }
  10119. //BfType* boxedType = mModule->CreateBoxedType(exprValue.mType);
  10120. //auto scopeData = mModule->FindScope(boxExpr->mAllocNode);
  10121. mResult = mModule->BoxValue(boxExpr->mExpression, exprValue, mModule->mContext->mBfObjectType, allocTarget);
  10122. if (!mResult)
  10123. {
  10124. mModule->Fail(StrFormat("Type '%s' is not boxable", mModule->TypeToString(exprValue.mType).c_str()), boxExpr->mExpression);
  10125. return;
  10126. }
  10127. }
  10128. }
  10129. BfAllocTarget BfExprEvaluator::ResolveAllocTarget(BfAstNode* allocNode, BfTokenNode*& newToken)
  10130. {
  10131. auto autoComplete = GetAutoComplete();
  10132. BfAttributeDirective* attributeDirective = NULL;
  10133. BfAllocTarget allocTarget;
  10134. allocTarget.mRefNode = allocNode;
  10135. newToken = BfNodeDynCast<BfTokenNode>(allocNode);
  10136. if (newToken == NULL)
  10137. {
  10138. if (auto scopeNode = BfNodeDynCast<BfScopeNode>(allocNode))
  10139. {
  10140. newToken = scopeNode->mScopeToken;
  10141. allocTarget.mScopeData = mModule->FindScope(scopeNode->mTargetNode, true);
  10142. if (autoComplete != NULL)
  10143. {
  10144. auto targetIdentifier = BfNodeDynCast<BfIdentifierNode>(scopeNode->mTargetNode);
  10145. if ((scopeNode->mTargetNode == NULL) || (targetIdentifier != NULL))
  10146. autoComplete->CheckLabel(targetIdentifier, scopeNode->mColonToken);
  10147. }
  10148. attributeDirective = scopeNode->mAttributes;
  10149. }
  10150. if (auto newNode = BfNodeDynCast<BfNewNode>(allocNode))
  10151. {
  10152. newToken = newNode->mNewToken;
  10153. if (auto allocExpr = BfNodeDynCast<BfExpression>(newNode->mAllocNode))
  10154. {
  10155. allocTarget.mCustomAllocator = mModule->CreateValueFromExpression(allocExpr);
  10156. allocTarget.mRefNode = allocExpr;
  10157. }
  10158. else if (auto scopedInvocationTarget = BfNodeDynCast<BfScopedInvocationTarget>(newNode->mAllocNode))
  10159. {
  10160. allocTarget.mScopedInvocationTarget = scopedInvocationTarget;
  10161. }
  10162. attributeDirective = newNode->mAttributes;
  10163. }
  10164. }
  10165. else if (newToken->GetToken() == BfToken_Scope)
  10166. {
  10167. if (mModule->mCurMethodState != NULL)
  10168. allocTarget.mScopeData = mModule->mCurMethodState->mCurScope->GetTargetable();
  10169. }
  10170. else if (newToken->GetToken() == BfToken_Stack)
  10171. {
  10172. if (mModule->mCurMethodState != NULL)
  10173. allocTarget.mScopeData = &mModule->mCurMethodState->mHeadScope;
  10174. }
  10175. if (attributeDirective != NULL)
  10176. {
  10177. auto customAttrs = mModule->GetCustomAttributes(attributeDirective, BfAttributeTargets_Alloc, true, &allocTarget.mCaptureInfo);
  10178. if (customAttrs != NULL)
  10179. {
  10180. for (auto& attrib : customAttrs->mAttributes)
  10181. {
  10182. if (attrib.mType->mTypeDef == mModule->mCompiler->mAlignAttributeTypeDef)
  10183. {
  10184. allocTarget.mAlignOverride = 16; // System conservative default
  10185. if (!attrib.mCtorArgs.IsEmpty())
  10186. {
  10187. BfIRConstHolder* constHolder = mModule->mCurTypeInstance->mConstHolder;
  10188. auto constant = constHolder->GetConstant(attrib.mCtorArgs[0]);
  10189. if (constant != NULL)
  10190. {
  10191. int alignOverride = (int)BF_MAX(1, constant->mInt64);
  10192. if ((alignOverride & (alignOverride - 1)) == 0)
  10193. allocTarget.mAlignOverride = alignOverride;
  10194. else
  10195. mModule->Fail("Alignment must be a power of 2", attrib.mRef);
  10196. }
  10197. }
  10198. }
  10199. }
  10200. delete customAttrs;
  10201. }
  10202. }
  10203. return allocTarget;
  10204. }
  10205. BfTypedValue BfExprEvaluator::MakeCallableTarget(BfAstNode* targetSrc, BfTypedValue target)
  10206. {
  10207. if (((target.mType->IsRef()) || (target.mType->IsPointer())) &&
  10208. (target.mType->GetUnderlyingType()->IsStruct()))
  10209. {
  10210. auto pointerType = (BfPointerType*) target.mType;
  10211. target = mModule->LoadValue(target);
  10212. target.mType = pointerType->mElementType;
  10213. target.mKind = BfTypedValueKind_Addr;
  10214. }
  10215. if ((target.mType->IsStruct()) && (!target.IsAddr()))
  10216. {
  10217. target = mModule->MakeAddressable(target);
  10218. }
  10219. if (target.mType->IsVar())
  10220. {
  10221. target.mType = mModule->mContext->mBfObjectType;
  10222. return target;
  10223. }
  10224. if (target.mType->IsWrappableType())
  10225. {
  10226. auto primStructType = mModule->GetWrappedStructType(target.mType);
  10227. if (primStructType != NULL)
  10228. {
  10229. mModule->PopulateType(primStructType);
  10230. target.mType = primStructType;
  10231. if ((primStructType->IsSplattable()) && (!primStructType->IsTypedPrimitive()))
  10232. {
  10233. if (target.IsAddr())
  10234. {
  10235. auto ptrType = mModule->CreatePointerType(primStructType);
  10236. target = BfTypedValue(mModule->mBfIRBuilder->CreateBitCast(target.mValue, mModule->mBfIRBuilder->MapType(ptrType)), primStructType, true);
  10237. }
  10238. else
  10239. target.mKind = BfTypedValueKind_SplatHead;
  10240. }
  10241. }
  10242. return target;
  10243. }
  10244. if (target.mType->IsGenericParam())
  10245. {
  10246. target.mType = mModule->mContext->mBfObjectType;
  10247. return target;
  10248. }
  10249. if ((!target.mType->IsTypeInstance()) && (!target.mType->IsConcreteInterfaceType()))
  10250. {
  10251. mModule->Fail(StrFormat("Invalid target type: '%s'", mModule->TypeToString(target.mType).c_str()), targetSrc);
  10252. return BfTypedValue();
  10253. }
  10254. return target;
  10255. }
  10256. int BfExprEvaluator::GetMixinVariable()
  10257. {
  10258. auto curMethodState = mModule->mCurMethodState;
  10259. for (int localIdx = (int)curMethodState->mLocals.size() - 1; localIdx >= 0; localIdx--)
  10260. {
  10261. auto varDecl = curMethodState->mLocals[localIdx];
  10262. if (varDecl->mName == "mixin")
  10263. return localIdx;
  10264. }
  10265. return -1;
  10266. }
  10267. BfModuleMethodInstance BfExprEvaluator::GetSelectedMethod(BfAstNode* targetSrc, BfTypeInstance* curTypeInst, BfMethodDef* methodDef, BfMethodMatcher& methodMatcher)
  10268. {
  10269. bool failed = false;
  10270. auto resolvedCurTypeInst = curTypeInst;//mModule->ResolveGenericType(curTypeInst)->ToTypeInstance();
  10271. bool hasDifferentResolvedTypes = resolvedCurTypeInst != curTypeInst;
  10272. BfTypeVector resolvedGenericArguments;
  10273. auto rootMethodState = mModule->mCurMethodState->GetRootMethodState();
  10274. int localInferrableGenericArgCount = -1;
  10275. if ((methodMatcher.mBestMethodGenericArguments.size() == 0) && (!methodMatcher.mExplicitMethodGenericArguments.IsEmpty()))
  10276. {
  10277. int uniqueGenericStartIdx = mModule->GetLocalInferrableGenericArgCount(methodDef);
  10278. int64 genericArgCountDiff = (int)methodMatcher.mExplicitMethodGenericArguments.size() + uniqueGenericStartIdx - (int)methodDef->mGenericParams.size();
  10279. BfInvocationExpression* invocationExpr = NULL;
  10280. if (mModule->mParentNodeEntry != NULL)
  10281. {
  10282. invocationExpr = BfNodeDynCast<BfInvocationExpression>(mModule->mParentNodeEntry->mNode);
  10283. }
  10284. if (genericArgCountDiff > 0)
  10285. {
  10286. BfAstNode* errorNode = targetSrc;
  10287. if ((invocationExpr != NULL) && (invocationExpr->mGenericArgs != NULL))
  10288. {
  10289. errorNode = invocationExpr->mGenericArgs->mGenericArgs[(int)methodDef->mGenericParams.size()];
  10290. if (errorNode == NULL)
  10291. errorNode = invocationExpr->mGenericArgs->mCommas[(int)methodDef->mGenericParams.size() - 1];
  10292. }
  10293. mModule->Fail(StrFormat("Too many generic arguments, expected %d fewer", genericArgCountDiff), errorNode);
  10294. }
  10295. else if (genericArgCountDiff < 0)
  10296. {
  10297. BfAstNode* errorNode = targetSrc;
  10298. if ((invocationExpr != NULL) && (invocationExpr->mGenericArgs != NULL) && (invocationExpr->mGenericArgs->mCloseChevron != NULL))
  10299. errorNode = invocationExpr->mGenericArgs->mCloseChevron;
  10300. mModule->Fail(StrFormat("Too few generic arguments, expected %d more", -genericArgCountDiff), errorNode);
  10301. }
  10302. methodMatcher.mBestMethodGenericArguments.resize(methodDef->mGenericParams.size());
  10303. for (int i = 0; i < std::min(methodDef->mGenericParams.size() - uniqueGenericStartIdx, methodMatcher.mExplicitMethodGenericArguments.size()); i++)
  10304. {
  10305. methodMatcher.mBestMethodGenericArguments[i + uniqueGenericStartIdx] = methodMatcher.mExplicitMethodGenericArguments[i];
  10306. }
  10307. }
  10308. BfMethodInstance* unspecializedMethod = NULL;
  10309. for (int checkGenericIdx = 0; checkGenericIdx < (int)methodMatcher.mBestMethodGenericArguments.size(); checkGenericIdx++)
  10310. {
  10311. BfMethodInstance* outerMethodInstance = NULL;
  10312. auto& genericArg = methodMatcher.mBestMethodGenericArguments[checkGenericIdx];
  10313. if (genericArg == NULL)
  10314. {
  10315. if ((methodDef->mIsLocalMethod) && (checkGenericIdx < mModule->mCurMethodInstance->GetNumGenericArguments()))
  10316. {
  10317. // If the root method is generic and we need that param then use that...
  10318. auto rootMethodInstance = rootMethodState->mMethodInstance;
  10319. if (checkGenericIdx < rootMethodInstance->mMethodInfoEx->mMethodGenericArguments.size())
  10320. {
  10321. genericArg = rootMethodInstance->mMethodInfoEx->mMethodGenericArguments[checkGenericIdx];
  10322. }
  10323. else
  10324. {
  10325. if (localInferrableGenericArgCount == -1)
  10326. localInferrableGenericArgCount = mModule->GetLocalInferrableGenericArgCount(methodDef);
  10327. // Otherwise we can only infer generics at the level that the called method was contained
  10328. if (checkGenericIdx < localInferrableGenericArgCount)
  10329. genericArg = mModule->mCurMethodInstance->mMethodInfoEx->mMethodGenericArguments[checkGenericIdx];
  10330. }
  10331. }
  10332. }
  10333. if (genericArg == NULL)
  10334. {
  10335. if (unspecializedMethod == NULL)
  10336. unspecializedMethod = mModule->GetRawMethodInstance(curTypeInst, methodDef);
  10337. auto genericParam = unspecializedMethod->mMethodInfoEx->mGenericParams[checkGenericIdx];
  10338. if ((genericParam->mTypeConstraint != NULL) && (genericParam->mTypeConstraint->IsDelegate()))
  10339. {
  10340. // The only other option was to bind to a MethodRef
  10341. genericArg = genericParam->mTypeConstraint;
  10342. }
  10343. else
  10344. {
  10345. if (((genericParam->mGenericParamFlags & BfGenericParamFlag_Const) != 0) && (genericParam->mTypeConstraint != NULL))
  10346. {
  10347. for (int paramIdx = 0; paramIdx < (int)unspecializedMethod->mDefaultValues.size(); paramIdx++)
  10348. {
  10349. auto defaultVal = unspecializedMethod->mDefaultValues[paramIdx];
  10350. if (!defaultVal)
  10351. continue;
  10352. auto& param = unspecializedMethod->mParams[paramIdx];
  10353. if (param.mResolvedType->IsGenericParam())
  10354. {
  10355. auto genericParamType = (BfGenericParamType*)param.mResolvedType;
  10356. if ((genericParamType->mGenericParamKind == BfGenericParamKind_Method) && (genericParamType->mGenericParamIdx == checkGenericIdx))
  10357. {
  10358. BfTypedValue constExprVal;
  10359. constExprVal.mType = genericParam->mTypeConstraint;
  10360. auto constant = curTypeInst->mConstHolder->GetConstant(defaultVal);
  10361. constExprVal.mValue = mModule->ConstantToCurrent(constant, curTypeInst->mConstHolder, genericParam->mTypeConstraint);
  10362. genericArg = mModule->CreateConstExprValueType(constExprVal);
  10363. }
  10364. }
  10365. }
  10366. }
  10367. if (genericArg == NULL)
  10368. {
  10369. failed = true;
  10370. mModule->Fail(StrFormat("Unable to determine generic argument '%s'", methodDef->mGenericParams[checkGenericIdx]->mName.c_str()).c_str(), targetSrc);
  10371. if ((genericParam->mTypeConstraint != NULL) && (!genericParam->mTypeConstraint->IsUnspecializedType()))
  10372. genericArg = genericParam->mTypeConstraint;
  10373. else
  10374. genericArg = mModule->mContext->mBfObjectType;
  10375. }
  10376. }
  10377. resolvedGenericArguments.push_back(genericArg);
  10378. }
  10379. else
  10380. {
  10381. if (genericArg->IsIntUnknown())
  10382. genericArg = mModule->GetPrimitiveType(BfTypeCode_IntPtr);
  10383. auto resolvedGenericArg = genericArg;//mModule->ResolveGenericType(genericArg);
  10384. if (resolvedGenericArg != genericArg)
  10385. hasDifferentResolvedTypes = true;
  10386. resolvedGenericArguments.push_back(resolvedGenericArg);
  10387. }
  10388. }
  10389. BfTypeInstance* foreignType = NULL;
  10390. BfGetMethodInstanceFlags flags = BfGetMethodInstanceFlag_None;
  10391. if ((mModule->mAttributeState != NULL) && (mModule->mAttributeState->mCustomAttributes != NULL) && (mModule->mAttributeState->mCustomAttributes->Contains(mModule->mCompiler->mInlineAttributeTypeDef)))
  10392. {
  10393. flags = (BfGetMethodInstanceFlags)(flags | BfGetMethodInstanceFlag_ForceInline);
  10394. }
  10395. if ((!mModule->mCurTypeInstance->IsInterface()) && (methodDef->mBody != NULL))
  10396. {
  10397. if ((methodMatcher.mBypassVirtual) && (methodMatcher.mBestMethodTypeInstance->IsInterface()))
  10398. {
  10399. // This is an explicit 'base' call to a default interface method. We pull the methodDef into our own concrete type.
  10400. foreignType = curTypeInst;
  10401. curTypeInst = mModule->mCurTypeInstance;
  10402. flags = (BfGetMethodInstanceFlags)(flags | BfGetMethodInstanceFlag_ForeignMethodDef);
  10403. }
  10404. else if ((methodDef->mIsStatic) && (curTypeInst->IsInterface()))
  10405. {
  10406. if (mModule->TypeIsSubTypeOf(mModule->mCurTypeInstance, curTypeInst))
  10407. {
  10408. // This is an explicit call to a default static interface method. We pull the methodDef into our own concrete type.
  10409. foreignType = curTypeInst;
  10410. curTypeInst = mModule->mCurTypeInstance;
  10411. flags = (BfGetMethodInstanceFlags)(flags | BfGetMethodInstanceFlag_ForeignMethodDef);
  10412. }
  10413. }
  10414. }
  10415. BfModuleMethodInstance methodInstance;
  10416. if (methodMatcher.mBestMethodInstance)
  10417. {
  10418. methodInstance = methodMatcher.mBestMethodInstance;
  10419. }
  10420. else
  10421. {
  10422. methodInstance = mModule->GetMethodInstance(resolvedCurTypeInst, methodDef, resolvedGenericArguments, flags, foreignType);
  10423. }
  10424. if (mModule->mCompiler->IsSkippingExtraResolveChecks())
  10425. {
  10426. //BF_ASSERT(methodInstance.mFunc == NULL);
  10427. }
  10428. if (methodInstance.mMethodInstance == NULL)
  10429. return NULL;
  10430. if (methodDef->IsEmptyPartial())
  10431. return methodInstance;
  10432. for (int checkGenericIdx = 0; checkGenericIdx < (int)methodMatcher.mBestMethodGenericArguments.size(); checkGenericIdx++)
  10433. {
  10434. auto& genericParams = methodInstance.mMethodInstance->mMethodInfoEx->mGenericParams;
  10435. auto genericArg = methodMatcher.mBestMethodGenericArguments[checkGenericIdx];
  10436. if (genericArg->IsVar())
  10437. continue;
  10438. /*if (genericArg->IsPrimitiveType())
  10439. {
  10440. auto primType = (BfPrimitiveType*)genericArg;
  10441. genericArg = mModule->GetPrimitiveStructType(primType->mTypeDef->mTypeCode);
  10442. }*/
  10443. BfAstNode* paramSrc;
  10444. if (methodMatcher.mBestMethodGenericArgumentSrcs.size() == 0)
  10445. {
  10446. paramSrc = targetSrc;
  10447. }
  10448. else
  10449. paramSrc = methodMatcher.mArguments[methodMatcher.mBestMethodGenericArgumentSrcs[checkGenericIdx]].mExpression;
  10450. BfError* error = NULL;
  10451. if ((!failed) && (!mModule->CheckGenericConstraints(BfGenericParamSource(methodInstance.mMethodInstance), genericArg, paramSrc, genericParams[checkGenericIdx], &methodMatcher.mBestMethodGenericArguments, &error)))
  10452. {
  10453. if (methodInstance.mMethodInstance->IsSpecializedGenericMethod())
  10454. {
  10455. // We mark this as failed to make sure we don't try to process a method that doesn't even follow the constraints
  10456. methodInstance.mMethodInstance->mFailedConstraints = true;
  10457. }
  10458. if (methodInstance.mMethodInstance->mMethodDef->mMethodDeclaration != NULL)
  10459. {
  10460. if (error != NULL)
  10461. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("See method declaration"), methodInstance.mMethodInstance->mMethodDef->GetRefNode());
  10462. }
  10463. return BfModuleMethodInstance();
  10464. }
  10465. }
  10466. return methodInstance;
  10467. }
  10468. void BfExprEvaluator::CheckLocalMethods(BfAstNode* targetSrc, BfTypeInstance* typeInstance, const StringImpl& methodName, BfMethodMatcher& methodMatcher, BfMethodType methodType)
  10469. {
  10470. auto _GetNodeId = [&]()
  10471. {
  10472. auto parser = targetSrc->GetSourceData()->ToParserData();
  10473. return ((int64)parser->mDataId << 32) + targetSrc->GetSrcStart();
  10474. };
  10475. BfMethodState* ctxMethodState = NULL;
  10476. BfClosureInstanceInfo* ctxClosureInstanceInfo = NULL;
  10477. if ((mModule->mCurMethodState != NULL) && (mModule->mCurMethodState->mClosureState != NULL))
  10478. {
  10479. ctxClosureInstanceInfo = mModule->mCurMethodState->mClosureState->mClosureInstanceInfo;
  10480. ctxMethodState = mModule->mCurMethodState;
  10481. }
  10482. bool atCtxMethodState = false;
  10483. auto checkMethodState = mModule->mCurMethodState;
  10484. auto rootMethodState = checkMethodState;
  10485. while (checkMethodState != NULL)
  10486. {
  10487. rootMethodState = checkMethodState;
  10488. if (checkMethodState == ctxMethodState)
  10489. atCtxMethodState = true;
  10490. if ((ctxClosureInstanceInfo != NULL) && (!ctxMethodState->mClosureState->mCapturing))
  10491. {
  10492. BfMethodDef* localMethodDef = NULL;
  10493. if (ctxClosureInstanceInfo->mLocalMethodBindings.TryGetValue(_GetNodeId(), &localMethodDef))
  10494. {
  10495. methodMatcher.CheckMethod(mModule->mCurTypeInstance, localMethodDef, true);
  10496. BF_ASSERT(methodMatcher.mBestMethodDef != NULL);
  10497. return;
  10498. }
  10499. }
  10500. else
  10501. {
  10502. BfLocalMethod* matchedLocalMethod = NULL;
  10503. BfLocalMethod* localMethod = NULL;
  10504. if (checkMethodState->mLocalMethodMap.TryGetValue(methodName, &localMethod))
  10505. {
  10506. while (localMethod != NULL)
  10507. {
  10508. auto methodDef = mModule->GetLocalMethodDef(localMethod);
  10509. if (methodDef->mMethodType == methodType)
  10510. {
  10511. methodMatcher.CheckMethod(mModule->mCurTypeInstance, methodDef, true);
  10512. if (methodMatcher.mBestMethodDef == methodDef)
  10513. matchedLocalMethod = localMethod;
  10514. }
  10515. localMethod = localMethod->mNextWithSameName;
  10516. }
  10517. }
  10518. if (matchedLocalMethod != NULL)
  10519. {
  10520. if ((mModule->mCurMethodState != NULL) && (mModule->mCurMethodState->mClosureState != NULL) && (mModule->mCurMethodState->mClosureState->mCapturing))
  10521. {
  10522. BfModuleMethodInstance moduleMethodInstance = GetSelectedMethod(targetSrc, typeInstance, matchedLocalMethod->mMethodDef, methodMatcher);
  10523. auto methodInstance = moduleMethodInstance.mMethodInstance;
  10524. if ((methodInstance->mMethodInfoEx != NULL) && (methodInstance->mMethodInfoEx->mClosureInstanceInfo->mCaptureClosureState != NULL))
  10525. {
  10526. // The called method is calling us from its mLocalMethodRefs set. Stretch our mCaptureStartAccessId back to incorporate its
  10527. // captures as well
  10528. if (methodInstance->mMethodInfoEx->mClosureInstanceInfo->mCaptureClosureState->mCaptureStartAccessId < mModule->mCurMethodState->mClosureState->mCaptureStartAccessId)
  10529. mModule->mCurMethodState->mClosureState->mCaptureStartAccessId = methodInstance->mMethodInfoEx->mClosureInstanceInfo->mCaptureClosureState->mCaptureStartAccessId;
  10530. }
  10531. else
  10532. {
  10533. if (methodInstance->mDisallowCalling) // We need to process the captures from this guy
  10534. {
  10535. if (mModule->mCurMethodState->mClosureState->mLocalMethodRefSet.Add(methodInstance))
  10536. mModule->mCurMethodState->mClosureState->mLocalMethodRefs.Add(methodInstance);
  10537. }
  10538. }
  10539. }
  10540. if (ctxClosureInstanceInfo != NULL)
  10541. {
  10542. BF_ASSERT(mModule->mCurMethodState->mClosureState->mCapturing);
  10543. ctxClosureInstanceInfo->mLocalMethodBindings[_GetNodeId()] = methodMatcher.mBestMethodDef;
  10544. }
  10545. break;
  10546. }
  10547. }
  10548. checkMethodState = checkMethodState->mPrevMethodState;
  10549. }
  10550. }
  10551. void BfExprEvaluator::InjectMixin(BfAstNode* targetSrc, BfTypedValue target, bool allowImplicitThis, const StringImpl& name, const BfSizedArray<BfExpression*>& arguments, BfSizedArray<ASTREF(BfTypeReference*)>* methodGenericArgs)
  10552. {
  10553. BfAstNode* origTargetSrc = targetSrc;
  10554. BfScopedInvocationTarget* scopedInvocationTarget = NULL;
  10555. if (mModule->mParentNodeEntry != NULL)
  10556. {
  10557. if (auto invocationExpr = BfNodeDynCast<BfInvocationExpression>(mModule->mParentNodeEntry->mNode))
  10558. {
  10559. scopedInvocationTarget = BfNodeDynCast<BfScopedInvocationTarget>(invocationExpr->mTarget);
  10560. }
  10561. }
  10562. auto targetNameNode = targetSrc;
  10563. if (scopedInvocationTarget != NULL)
  10564. targetNameNode = scopedInvocationTarget->mTarget;
  10565. BfTypeInstance* mixinClass = NULL;
  10566. if (target.mType != NULL)
  10567. mixinClass = target.mType->ToTypeInstance();
  10568. int inLine = mModule->mCurFilePosition.mCurLine;
  10569. SizedArray<BfResolvedArg, 4> args;
  10570. SizedArray<BfExprEvaluator*, 8> argExprEvaluators;
  10571. defer
  10572. (
  10573. {
  10574. for (auto exprEvaluator : argExprEvaluators)
  10575. delete exprEvaluator;
  10576. }
  10577. );
  10578. auto _AddArg = [&](BfExpression* argExpr)
  10579. {
  10580. BfResolvedArg resolvedArg;
  10581. argExprEvaluators.push_back(new BfExprEvaluator(mModule));
  10582. BfExprEvaluator* exprEvaluator = argExprEvaluators.back();
  10583. exprEvaluator->mResolveGenericParam = false;
  10584. if (argExpr != NULL)
  10585. exprEvaluator->Evaluate(argExpr, false, false, true);
  10586. auto argValue = exprEvaluator->mResult;
  10587. mModule->FixIntUnknown(argValue);
  10588. if (argValue)
  10589. {
  10590. if (argValue.mType->IsRef())
  10591. {
  10592. exprEvaluator->FinishExpressionResult();
  10593. }
  10594. }
  10595. resolvedArg.mTypedValue = argValue;
  10596. resolvedArg.mExpression = argExpr;
  10597. args.push_back(resolvedArg);
  10598. };
  10599. for (BfExpression* argExpr : arguments)
  10600. {
  10601. _AddArg(argExpr);
  10602. }
  10603. auto autoComplete = GetAutoComplete();
  10604. if ((autoComplete != NULL) && (autoComplete->mIsCapturingMethodMatchInfo) && (autoComplete->mMethodMatchInfo->mInstanceList.size() != 0))
  10605. autoComplete->mIsCapturingMethodMatchInfo = false;
  10606. BfMethodMatcher methodMatcher(targetSrc, mModule, name, args, methodGenericArgs);
  10607. methodMatcher.mMethodType = BfMethodType_Mixin;
  10608. methodMatcher.mSkipImplicitParams = true;
  10609. auto curTypeInst = mModule->mCurTypeInstance;
  10610. if (mixinClass != NULL)
  10611. curTypeInst = mixinClass;
  10612. if (target.mType == NULL)
  10613. {
  10614. CheckLocalMethods(targetSrc, curTypeInst, name, methodMatcher, BfMethodType_Mixin);
  10615. }
  10616. if (methodMatcher.mBestMethodDef == NULL)
  10617. methodMatcher.mBestMethodDef = methodMatcher.mBackupMethodDef;
  10618. if (methodMatcher.mBestMethodDef == NULL)
  10619. {
  10620. if (mixinClass != NULL)
  10621. methodMatcher.CheckType(mixinClass, BfTypedValue(), false);
  10622. else
  10623. methodMatcher.CheckType(mModule->mCurTypeInstance, BfTypedValue(), false);
  10624. }
  10625. if ((methodMatcher.mBestMethodDef == NULL) && (mModule->mContext->mCurTypeState != NULL))
  10626. {
  10627. BF_ASSERT(mModule->mCurTypeInstance == mModule->mContext->mCurTypeState->mTypeInstance);
  10628. BfGlobalLookup globalLookup;
  10629. globalLookup.mKind = BfGlobalLookup::Kind_Method;
  10630. globalLookup.mName = name;
  10631. mModule->PopulateGlobalContainersList(globalLookup);
  10632. for (auto& globalContainer : mModule->mContext->mCurTypeState->mGlobalContainers)
  10633. {
  10634. if (globalContainer.mTypeInst == NULL)
  10635. continue;
  10636. methodMatcher.CheckType(globalContainer.mTypeInst, BfTypedValue(), false);
  10637. if (methodMatcher.mBestMethodDef != NULL)
  10638. break;
  10639. }
  10640. }
  10641. if (methodMatcher.mBestMethodDef == NULL)
  10642. {
  10643. mModule->Fail("Cannot find mixin", targetSrc);
  10644. return;
  10645. }
  10646. auto resolvePassData = mModule->mCompiler->mResolvePassData;
  10647. if ((autoComplete != NULL) && (autoComplete->IsAutocompleteNode(targetNameNode)) && (autoComplete->mDefType == NULL))
  10648. {
  10649. autoComplete->mInsertStartIdx = targetNameNode->GetSrcStart();
  10650. autoComplete->mInsertEndIdx = targetNameNode->GetSrcEnd();
  10651. autoComplete->mDefType = methodMatcher.mBestMethodTypeInstance->mTypeDef;
  10652. autoComplete->mDefMethod = methodMatcher.mBestMethodDef;
  10653. autoComplete->SetDefinitionLocation(methodMatcher.mBestMethodDef->GetMethodDeclaration()->mNameNode);
  10654. }
  10655. if ((mModule->mCompiler->mResolvePassData != NULL) && (mModule->mCompiler->mResolvePassData->mGetSymbolReferenceKind == BfGetSymbolReferenceKind_Method))
  10656. {
  10657. targetNameNode->SetSrcEnd(targetNameNode->GetSrcEnd() - 1);
  10658. mModule->mCompiler->mResolvePassData->HandleMethodReference(targetNameNode, methodMatcher.mBestMethodTypeInstance->mTypeDef, methodMatcher.mBestMethodDef);
  10659. targetNameNode->SetSrcEnd(targetNameNode->GetSrcEnd() + 1);
  10660. }
  10661. auto curMethodState = mModule->mCurMethodState;
  10662. //
  10663. {
  10664. bool hasCircularRef = false;
  10665. auto checkMethodState = curMethodState;
  10666. while (checkMethodState != NULL)
  10667. {
  10668. auto curMixinState = checkMethodState->mMixinState;
  10669. while (curMixinState != NULL)
  10670. {
  10671. if (curMixinState->mSource == targetSrc)
  10672. hasCircularRef = true;
  10673. curMixinState = curMixinState->mPrevMixinState;
  10674. }
  10675. if ((checkMethodState->mClosureState != NULL) && (checkMethodState->mClosureState->mActiveDeferredLocalMethod != NULL))
  10676. {
  10677. for (auto& mixinRecord : checkMethodState->mClosureState->mActiveDeferredLocalMethod->mMixinStateRecords)
  10678. {
  10679. if (mixinRecord.mSource == targetSrc)
  10680. hasCircularRef = true;
  10681. }
  10682. }
  10683. checkMethodState = checkMethodState->mPrevMethodState;
  10684. }
  10685. if (hasCircularRef)
  10686. {
  10687. mModule->Fail("Circular reference detected between mixins", targetSrc);
  10688. return;
  10689. }
  10690. }
  10691. auto moduleMethodInstance = GetSelectedMethod(targetSrc, methodMatcher.mBestMethodTypeInstance, methodMatcher.mBestMethodDef, methodMatcher);
  10692. if (!moduleMethodInstance)
  10693. return;
  10694. auto methodInstance = moduleMethodInstance.mMethodInstance;
  10695. // Check circular ref based on methodInstance
  10696. {
  10697. bool hasCircularRef = false;
  10698. auto checkMethodState = curMethodState;
  10699. while (checkMethodState != NULL)
  10700. {
  10701. if (checkMethodState->mMethodInstance == methodInstance)
  10702. hasCircularRef = true;
  10703. auto curMixinState = checkMethodState->mMixinState;
  10704. while (curMixinState != NULL)
  10705. {
  10706. if (curMixinState->mMixinMethodInstance == methodInstance)
  10707. hasCircularRef = true;
  10708. curMixinState = curMixinState->mPrevMixinState;
  10709. }
  10710. checkMethodState = checkMethodState->mPrevMethodState;
  10711. }
  10712. if (hasCircularRef)
  10713. {
  10714. mModule->Fail("Circular reference detected between mixins", targetSrc);
  10715. return;
  10716. }
  10717. }
  10718. AddCallDependencies(methodInstance);
  10719. if (!methodMatcher.mBestMethodDef->mIsStatic)
  10720. {
  10721. if ((!target) && (allowImplicitThis))
  10722. target = mModule->GetThis();
  10723. if (!target)
  10724. {
  10725. mModule->Fail(StrFormat("An instance reference is required to invoke the non-static mixin '%s'",
  10726. mModule->MethodToString(methodInstance).c_str()), targetSrc);
  10727. }
  10728. }
  10729. else
  10730. {
  10731. if (target)
  10732. {
  10733. mModule->Fail(StrFormat("Mixin '%s' cannot be accessed with an instance reference; qualify it with a type name instead",
  10734. mModule->MethodToString(methodInstance).c_str()), targetSrc);
  10735. }
  10736. }
  10737. int methodParamCount = (int)methodInstance->GetParamCount();
  10738. // Implicit params are ignored for calling- they should be resolved at the injection site
  10739. int implicitParamCount = methodInstance->GetImplicitParamCount();
  10740. int explicitParamCount = methodParamCount - implicitParamCount;
  10741. while ((int)args.size() < explicitParamCount)
  10742. {
  10743. int argIdx = (int)args.size();
  10744. BfExpression* expr = methodInstance->GetParamInitializer(argIdx);
  10745. if (expr == NULL)
  10746. break;
  10747. _AddArg(expr);
  10748. }
  10749. if ((int)args.size() < explicitParamCount)
  10750. {
  10751. BfError* error = mModule->Fail(StrFormat("Not enough arguments specified, expected %d more.", explicitParamCount - (int)arguments.size()), targetSrc);
  10752. if ((error != NULL) && (methodInstance->mMethodDef->mMethodDeclaration != NULL))
  10753. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("See method declaration"), methodInstance->mMethodDef->GetRefNode());
  10754. return;
  10755. }
  10756. else if ((int)args.size() > explicitParamCount)
  10757. {
  10758. BfError* error = mModule->Fail(StrFormat("Too many arguments specified, expected %d fewer.", (int)arguments.size() - explicitParamCount), targetSrc);
  10759. if ((error != NULL) && (methodInstance->mMethodDef->mMethodDeclaration != NULL))
  10760. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("See method declaration"), methodInstance->mMethodDef->GetRefNode());
  10761. return;
  10762. }
  10763. int paramIdx = implicitParamCount;
  10764. auto argExprEvaluatorItr = argExprEvaluators.begin();
  10765. for (int argIdx = 0; argIdx < (int)args.size(); argIdx++)
  10766. {
  10767. auto exprEvaluator = *argExprEvaluatorItr;
  10768. //auto paramType = methodInstance->GetParamKind(paramIdx);
  10769. BfType* wantType = methodInstance->mParams[paramIdx].mResolvedType;
  10770. auto& arg = args[argIdx];
  10771. if (wantType->IsGenericParam())
  10772. {
  10773. //
  10774. }
  10775. else if (!wantType->IsVar())
  10776. {
  10777. if (arg.mTypedValue.mType == NULL)
  10778. {
  10779. mModule->AssertErrorState();
  10780. return;
  10781. }
  10782. if (arg.mTypedValue.mType != wantType)
  10783. {
  10784. exprEvaluator->FinishExpressionResult();
  10785. arg.mTypedValue = mModule->LoadValue(arg.mTypedValue);
  10786. arg.mTypedValue = mModule->Cast(arg.mExpression, arg.mTypedValue, wantType);
  10787. /*// Do this to generate default implicit cast error
  10788. mModule->Fail(StrFormat("Mixin argument type '%s' must match parameter type '%s'.",
  10789. mModule->TypeToString(arg.mTypedValue.mType).c_str(),
  10790. mModule->TypeToString(wantType).c_str()), arg.mExpression);
  10791. return;*/
  10792. }
  10793. }
  10794. paramIdx++;
  10795. argExprEvaluatorItr++;
  10796. }
  10797. mModule->AddDependency(methodInstance->GetOwner(), mModule->mCurTypeInstance, BfDependencyMap::DependencyFlag_InlinedCall);
  10798. auto startBlock = mModule->mBfIRBuilder->CreateBlock("mixinStart");
  10799. mModule->mBfIRBuilder->CreateBr(startBlock);
  10800. mModule->mBfIRBuilder->AddBlock(startBlock);
  10801. mModule->mBfIRBuilder->SetInsertPoint(startBlock);
  10802. //auto prevDebugLoc = mModule->mBfIRBuilder->getCurrentDebugLocation();
  10803. // This is so when we debug we can hit a steppoint on the inlined "call line"
  10804. mModule->EmitEnsureInstructionAt();
  10805. auto rootMethodState = mModule->mCurMethodState->GetRootMethodState();
  10806. BfMixinState* mixinState = rootMethodState->mMixinStates.Alloc();
  10807. mixinState->mPrevMixinState = curMethodState->mMixinState;
  10808. mixinState->mLocalsStartIdx = (int)mModule->mCurMethodState->mLocals.size();
  10809. mixinState->mMixinMethodInstance = methodInstance;
  10810. mixinState->mSource = origTargetSrc;
  10811. mixinState->mCallerScope = mModule->mCurMethodState->mCurScope;
  10812. mixinState->mTargetScope = mixinState->mCallerScope;
  10813. mixinState->mResultExpr = NULL;
  10814. mixinState->mHasDeferredUsage = false;
  10815. mixinState->mUsedInvocationScope = false;
  10816. mixinState->mTarget = target;
  10817. auto checkNode = origTargetSrc;
  10818. if (scopedInvocationTarget != NULL)
  10819. {
  10820. auto targetScope = mModule->FindScope(scopedInvocationTarget->mScopeName, curMethodState->mMixinState);
  10821. if (targetScope != NULL)
  10822. mixinState->mTargetScope = targetScope;
  10823. }
  10824. mModule->mBfIRBuilder->SaveDebugLocation();
  10825. SetAndRestoreValue<BfMixinState*> prevMixinState(curMethodState->mMixinState, mixinState);
  10826. BfGetSymbolReferenceKind prevSymbolRefKind = BfGetSymbolReferenceKind_None;
  10827. if (mModule->mCompiler->mResolvePassData != NULL)
  10828. {
  10829. prevSymbolRefKind = mModule->mCompiler->mResolvePassData->mGetSymbolReferenceKind;
  10830. mModule->mCompiler->mResolvePassData->mGetSymbolReferenceKind = BfGetSymbolReferenceKind_None;
  10831. }
  10832. defer
  10833. (
  10834. {
  10835. if (mModule->mCompiler->mResolvePassData != NULL)
  10836. mModule->mCompiler->mResolvePassData->mGetSymbolReferenceKind = prevSymbolRefKind;
  10837. }
  10838. );
  10839. auto methodDef = methodInstance->mMethodDef;
  10840. auto methodDeclaration = methodDef->GetMethodDeclaration();
  10841. BfScopeData scopeData;
  10842. scopeData.mCloseNode = methodDeclaration->mBody;
  10843. if (auto block = BfNodeDynCast<BfBlock>(methodDeclaration->mBody))
  10844. {
  10845. if (block->mCloseBrace != NULL)
  10846. scopeData.mCloseNode = block->mCloseBrace;
  10847. }
  10848. curMethodState->AddScope(&scopeData);
  10849. curMethodState->mCurScope->mMixinDepth++;
  10850. curMethodState->mIsEmbedded = false;
  10851. // We can't flush scope state because we extend params in as arbitrary values
  10852. mModule->NewScopeState(true, false);
  10853. bool wantsDIData = (mModule->mBfIRBuilder->DbgHasInfo()) && (mModule->mHasFullDebugInfo);
  10854. DISubprogram* diFunction = NULL;
  10855. int mixinLocalVarIdx = -1;
  10856. int startLocalIdx = (int)mModule->mCurMethodState->mLocals.size();
  10857. int endLocalIdx = startLocalIdx;
  10858. if (wantsDIData)
  10859. {
  10860. BfIRMDNode diFuncType = mModule->mBfIRBuilder->DbgCreateSubroutineType(SizedArray<BfIRMDNode, 0>());
  10861. //int defLine = mModule->mCurFilePosition.mCurLine;
  10862. int flags = 0;
  10863. curMethodState->mCurScope->mDIInlinedAt = mModule->mBfIRBuilder->DbgGetCurrentLocation();
  10864. // 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
  10865. // definitions, so we need to be consistent and use the actual line
  10866. mModule->UpdateSrcPos(methodDeclaration->mNameNode, BfSrcPosFlag_NoSetDebugLoc);
  10867. int defLine = mModule->mCurFilePosition.mCurLine;
  10868. auto diParentType = mModule->mBfIRBuilder->DbgGetTypeInst(methodInstance->GetOwner());
  10869. if (!mModule->mBfIRBuilder->mIgnoreWrites)
  10870. {
  10871. curMethodState->mCurScope->mDIScope = mModule->mBfIRBuilder->DbgCreateFunction(diParentType, methodDef->mName + "!", "", mModule->mCurFilePosition.mFileInstance->mDIFile,
  10872. defLine + 1, diFuncType, false, true, mModule->mCurFilePosition.mCurLine + 1, flags, false, BfIRValue());
  10873. scopeData.mAltDIFile = mModule->mCurFilePosition.mFileInstance->mDIFile;
  10874. }
  10875. }
  10876. if (methodDef->mBody != NULL)
  10877. mModule->UpdateSrcPos(methodDef->mBody);
  10878. mModule->SetIllegalSrcPos();
  10879. auto _AddLocalVariable = [&](BfLocalVariable* newLocalVar, BfExprEvaluator* exprEvaluator)
  10880. {
  10881. mModule->SetIllegalSrcPos();
  10882. bool hasConstValue = newLocalVar->mConstValue;
  10883. if (hasConstValue)
  10884. {
  10885. auto constant = mModule->mBfIRBuilder->GetConstant(newLocalVar->mConstValue);
  10886. hasConstValue = constant->mConstType < BfConstType_GlobalVar;
  10887. }
  10888. if ((exprEvaluator != NULL) && (exprEvaluator->mResultLocalVar != NULL) && (exprEvaluator->mResultLocalVarField == 0))
  10889. {
  10890. mModule->UpdateSrcPos(methodDeclaration->mNameNode);
  10891. mModule->AddLocalVariableDef(newLocalVar, hasConstValue);
  10892. auto inLocalVar = exprEvaluator->mResultLocalVar;
  10893. newLocalVar->mIsAssigned = inLocalVar->mIsAssigned;
  10894. newLocalVar->mUnassignedFieldFlags = inLocalVar->mUnassignedFieldFlags;
  10895. newLocalVar->mReadFromId = inLocalVar->mReadFromId;
  10896. newLocalVar->mIsReadOnly = inLocalVar->mIsReadOnly;
  10897. if ((!newLocalVar->mIsAssigned) && (mModule->mCurMethodState->mDeferredLocalAssignData != NULL))
  10898. {
  10899. for (auto deferredAssign : mModule->mCurMethodState->mDeferredLocalAssignData->mAssignedLocals)
  10900. {
  10901. if (deferredAssign.mLocalVar == inLocalVar)
  10902. newLocalVar->mIsAssigned = true;
  10903. }
  10904. }
  10905. }
  10906. else
  10907. {
  10908. mModule->AddLocalVariableDef(newLocalVar, hasConstValue);
  10909. }
  10910. if ((wantsDIData) && (!mModule->mBfIRBuilder->mIgnoreWrites))
  10911. {
  10912. mModule->UpdateSrcPos(methodDeclaration->mNameNode);
  10913. if (hasConstValue)
  10914. {
  10915. // Already handled
  10916. }
  10917. else if (mModule->IsTargetingBeefBackend())
  10918. {
  10919. mModule->UpdateSrcPos(methodDeclaration->mNameNode);
  10920. mModule->SetIllegalSrcPos();
  10921. // With the Beef backend we can assign two variables to the same value, but LLVM does not allow this
  10922. // so we have to create a ref to that variable
  10923. auto diType = mModule->mBfIRBuilder->DbgGetType(newLocalVar->mResolvedType);
  10924. auto diVariable = mModule->mBfIRBuilder->DbgCreateAutoVariable(mModule->mCurMethodState->mCurScope->mDIScope,
  10925. newLocalVar->mName, mModule->mCurFilePosition.mFileInstance->mDIFile, mModule->mCurFilePosition.mCurLine, diType);
  10926. if (newLocalVar->mIsSplat)
  10927. {
  10928. //TODO: Implement
  10929. }
  10930. else
  10931. {
  10932. BfIRValue value = newLocalVar->mValue;
  10933. if (newLocalVar->mAddr)
  10934. value = newLocalVar->mAddr;
  10935. else if (newLocalVar->mConstValue)
  10936. value = newLocalVar->mConstValue;
  10937. auto aliasValue = mModule->mBfIRBuilder->CreateAliasValue(value);
  10938. if (mModule->WantsLifetimes())
  10939. scopeData.mDeferredLifetimeEnds.Add(aliasValue);
  10940. if (newLocalVar->mAddr)
  10941. mModule->mBfIRBuilder->DbgInsertDeclare(aliasValue, diVariable);
  10942. else
  10943. {
  10944. mModule->mBfIRBuilder->DbgInsertValueIntrinsic(aliasValue, diVariable);
  10945. //mModule->mBfIRBuilder->DbgInsertValueIntrinsic(newLocalVar->mValue, diVariable);
  10946. }
  10947. }
  10948. }
  10949. else if (newLocalVar->mAddr)
  10950. {
  10951. mModule->UpdateSrcPos(methodDeclaration->mNameNode);
  10952. mModule->SetIllegalSrcPos();
  10953. auto refType = mModule->CreateRefType(newLocalVar->mResolvedType);
  10954. auto allocaVal = mModule->CreateAlloca(refType);
  10955. mModule->mBfIRBuilder->CreateStore(newLocalVar->mAddr, allocaVal);
  10956. if (!mModule->mBfIRBuilder->mIgnoreWrites)
  10957. {
  10958. auto diType = mModule->mBfIRBuilder->DbgGetType(refType);
  10959. auto diVariable = mModule->mBfIRBuilder->DbgCreateAutoVariable(mModule->mCurMethodState->mCurScope->mDIScope,
  10960. newLocalVar->mName, mModule->mCurFilePosition.mFileInstance->mDIFile, mModule->mCurFilePosition.mCurLine, diType);
  10961. mModule->mBfIRBuilder->DbgInsertDeclare(allocaVal, diVariable);
  10962. }
  10963. }
  10964. else if (newLocalVar->mValue)
  10965. {
  10966. mModule->UpdateSrcPos(methodDeclaration->mNameNode);
  10967. mModule->SetIllegalSrcPos();
  10968. auto localVal = LoadLocal(newLocalVar);
  10969. localVal = mModule->LoadValue(localVal);
  10970. localVal = mModule->AggregateSplat(localVal);
  10971. BfType* allocType = localVal.mType;
  10972. auto allocaVal = mModule->CreateAlloca(allocType);
  10973. mModule->mBfIRBuilder->CreateStore(localVal.mValue, allocaVal);
  10974. if (!mModule->mBfIRBuilder->mIgnoreWrites)
  10975. {
  10976. if (newLocalVar->mIsSplat)
  10977. {
  10978. //TODO: Implement
  10979. }
  10980. else
  10981. {
  10982. auto diType = mModule->mBfIRBuilder->DbgGetType(allocType);
  10983. auto diVariable = mModule->mBfIRBuilder->DbgCreateAutoVariable(mModule->mCurMethodState->mCurScope->mDIScope,
  10984. newLocalVar->mName, mModule->mCurFilePosition.mFileInstance->mDIFile, mModule->mCurFilePosition.mCurLine, diType);
  10985. mModule->mBfIRBuilder->DbgInsertDeclare(allocaVal, diVariable);
  10986. }
  10987. }
  10988. }
  10989. }
  10990. newLocalVar->mParamIdx = -3;
  10991. };
  10992. argExprEvaluatorItr = argExprEvaluators.begin();
  10993. for (int argIdx = 0; argIdx < (int)explicitParamCount; argIdx++)
  10994. {
  10995. int paramIdx = argIdx;
  10996. auto exprEvaluator = *argExprEvaluatorItr;
  10997. auto paramDef = methodDef->mParams[paramIdx];
  10998. auto arg = &args[argIdx];
  10999. if (!arg->mTypedValue)
  11000. {
  11001. auto wantType = methodInstance->GetParamType(paramIdx);
  11002. if (wantType->IsVar())
  11003. wantType = mModule->mContext->mBfObjectType;
  11004. arg->mTypedValue = mModule->GetDefaultTypedValue(wantType);
  11005. }
  11006. BfLocalVariable* localVar = new BfLocalVariable();
  11007. localVar->mName = paramDef->mName;
  11008. localVar->mResolvedType = arg->mTypedValue.mType;
  11009. if (arg->mTypedValue.mType->IsRef())
  11010. {
  11011. auto refType = (BfRefType*)localVar->mResolvedType;
  11012. localVar->mAddr = mModule->LoadValue(arg->mTypedValue).mValue;
  11013. localVar->mResolvedType = arg->mTypedValue.mType->GetUnderlyingType();
  11014. localVar->mIsAssigned = refType->mRefKind != BfRefType::RefKind_Out;
  11015. }
  11016. else if (arg->mTypedValue.IsAddr())
  11017. localVar->mAddr = arg->mTypedValue.mValue;
  11018. else
  11019. {
  11020. if (!arg->mTypedValue.mValue)
  11021. {
  11022. // Untyped value
  11023. }
  11024. else if (arg->mTypedValue.mValue.IsConst())
  11025. {
  11026. localVar->mConstValue = arg->mTypedValue.mValue;
  11027. }
  11028. else if (arg->mTypedValue.IsSplat())
  11029. {
  11030. localVar->mValue = arg->mTypedValue.mValue;
  11031. localVar->mIsSplat = true;
  11032. }
  11033. else
  11034. {
  11035. if (arg->mTypedValue.IsAddr())
  11036. localVar->mAddr = arg->mTypedValue.mValue;
  11037. else
  11038. localVar->mValue = arg->mTypedValue.mValue;
  11039. }
  11040. localVar->mIsReadOnly = arg->mTypedValue.IsReadOnly();
  11041. }
  11042. _AddLocalVariable(localVar, exprEvaluator);
  11043. endLocalIdx++;
  11044. ++argExprEvaluatorItr;
  11045. }
  11046. if (auto blockBody = BfNodeDynCast<BfBlock>(methodDef->mBody))
  11047. mModule->VisitCodeBlock(blockBody);
  11048. if (mixinState->mResultExpr != NULL)
  11049. {
  11050. if (auto exprNode = BfNodeDynCast<BfExpression>(mixinState->mResultExpr))
  11051. {
  11052. //if ((exprNode->mTrailingSemicolon == NULL) && (!exprNode->IsA<BfBlock>()))
  11053. if (!exprNode->IsA<BfBlock>())
  11054. {
  11055. // Mixin expression result
  11056. mModule->UpdateSrcPos(exprNode);
  11057. VisitChild(exprNode);
  11058. FinishExpressionResult();
  11059. ResolveGenericType();
  11060. //mResult = mModule->LoadValue(mResult);
  11061. }
  11062. }
  11063. }
  11064. if (!mResult)
  11065. {
  11066. // If we didn't have an expression body then just make the result "void"
  11067. mResult = BfTypedValue(BfIRValue(), mModule->GetPrimitiveType(BfTypeCode_None));
  11068. }
  11069. int localIdx = startLocalIdx;
  11070. if (mixinLocalVarIdx != -1)
  11071. {
  11072. BfLocalVariable* localVar = curMethodState->mLocals[localIdx];
  11073. if (mResultLocalVar != NULL)
  11074. {
  11075. auto inLocalVar = mResultLocalVar;
  11076. if (localVar->mIsAssigned)
  11077. inLocalVar->mIsAssigned = true;
  11078. if (localVar->mReadFromId != -1)
  11079. inLocalVar->mReadFromId = mModule->mCurMethodState->GetRootMethodState()->mCurAccessId++;
  11080. }
  11081. localIdx++;
  11082. }
  11083. argExprEvaluatorItr = argExprEvaluators.begin();
  11084. for ( ; localIdx < endLocalIdx; localIdx++)
  11085. {
  11086. auto exprEvaluator = *argExprEvaluatorItr;
  11087. BfLocalVariable* localVar = curMethodState->mLocals[localIdx];
  11088. //TODO: Merge unassigned flags together
  11089. if ((exprEvaluator != NULL) && (exprEvaluator->mResultLocalVar != NULL))
  11090. {
  11091. auto inLocalVar = exprEvaluator->mResultLocalVar;
  11092. if (localVar->mIsAssigned)
  11093. inLocalVar->mIsAssigned = true;
  11094. if (localVar->mReadFromId != -1)
  11095. inLocalVar->mReadFromId = mModule->mCurMethodState->GetRootMethodState()->mCurAccessId++;
  11096. }
  11097. ++argExprEvaluatorItr;
  11098. }
  11099. if (auto blockBody = BfNodeDynCast<BfBlock>(methodDef->mBody))
  11100. if (blockBody->mCloseBrace != NULL)
  11101. mModule->UpdateSrcPos(blockBody->mCloseBrace);
  11102. mModule->RestoreScopeState();
  11103. prevMixinState.Restore();
  11104. if (mixinState->mHasDeferredUsage)
  11105. {
  11106. // if (target)
  11107. // {
  11108. // if (target.mType->IsValuelessType())
  11109. // mixinState->mTarget = target;
  11110. // else
  11111. // {
  11112. // target = mModule->LoadValue(target);
  11113. // auto savedTarget = BfTypedValue(mModule->CreateAlloca(target.mType, false), target.mType, true);
  11114. // mModule->mBfIRBuilder->CreateStore(target.mValue, savedTarget.mValue);
  11115. // mixinState->mTarget = savedTarget;
  11116. // }
  11117. // }
  11118. mixinState->mTarget = BfTypedValue();
  11119. }
  11120. else
  11121. {
  11122. BF_ASSERT(rootMethodState->mMixinStates.back() == mixinState);
  11123. rootMethodState->mMixinStates.pop_back();
  11124. delete mixinState;
  11125. }
  11126. if ((scopedInvocationTarget != NULL) && (scopedInvocationTarget->mScopeName != NULL) && (!mixinState->mUsedInvocationScope))
  11127. {
  11128. mModule->Warn(0, "Scope specifier was not referenced in mixin", scopedInvocationTarget->mScopeName);
  11129. }
  11130. // It's tempting to do this, but it is really just covering up other issues.
  11131. //mModule->mBfIRBuilder->SetCurrentDebugLocation(prevDebugLoc);
  11132. // But does THIS work?
  11133. mModule->mBfIRBuilder->RestoreDebugLocation();
  11134. }
  11135. void BfExprEvaluator::SetMethodElementType(BfAstNode* target)
  11136. {
  11137. if (auto delegateBindExpr = BfNodeDynCast<BfDelegateBindExpression>(target))
  11138. {
  11139. SetMethodElementType(delegateBindExpr->mTarget);
  11140. return;
  11141. }
  11142. if (auto lambdaBindExpr = BfNodeDynCast<BfLambdaBindExpression>(target))
  11143. {
  11144. return;
  11145. }
  11146. if (auto attributedIdentifierNode = BfNodeDynCast<BfAttributedIdentifierNode>(target))
  11147. {
  11148. if (attributedIdentifierNode->mIdentifier != NULL)
  11149. mModule->SetElementType(attributedIdentifierNode->mIdentifier, BfSourceElementType_Method);
  11150. }
  11151. else if (auto memberReferenceExpr = BfNodeDynCast<BfMemberReferenceExpression>(target))
  11152. {
  11153. if (memberReferenceExpr->mMemberName != NULL)
  11154. SetMethodElementType(memberReferenceExpr->mMemberName);
  11155. }
  11156. else if (auto qualifiedNameNode = BfNodeDynCast<BfQualifiedNameNode>(target))
  11157. SetMethodElementType(qualifiedNameNode->mRight);
  11158. else
  11159. mModule->SetElementType(target, BfSourceElementType_Method);
  11160. }
  11161. void BfExprEvaluator::DoInvocation(BfAstNode* target, BfMethodBoundExpression* methodBoundExpr, const BfSizedArray<BfExpression*>& args, BfSizedArray<ASTREF(BfTypeReference*)>* methodGenericArguments, BfTypedValue* outCascadeValue)
  11162. {
  11163. // Just a check
  11164. mModule->mBfIRBuilder->GetInsertBlock();
  11165. bool wasCapturingMethodInfo = false;
  11166. auto autoComplete = GetAutoComplete();
  11167. if ((autoComplete != NULL) && (methodGenericArguments != NULL))
  11168. {
  11169. for (BfTypeReference* methodGenericArg : *methodGenericArguments)
  11170. autoComplete->CheckTypeRef(methodGenericArg, false, true);
  11171. }
  11172. if ((autoComplete != NULL) && (autoComplete->mIsCapturingMethodMatchInfo))
  11173. {
  11174. // We don't want to capture a call within the target node
  11175. wasCapturingMethodInfo = true;
  11176. autoComplete->mIsCapturingMethodMatchInfo = false;
  11177. }
  11178. bool allowImplicitThis = false;
  11179. BfAstNode* methodNodeSrc = target;
  11180. BfAttributeState attributeState;
  11181. attributeState.mTarget = (BfAttributeTargets)(BfAttributeTargets_Invocation | BfAttributeTargets_MemberAccess);
  11182. if (auto scopedTarget = BfNodeDynCast<BfScopedInvocationTarget>(target))
  11183. {
  11184. target = scopedTarget->mTarget;
  11185. if (autoComplete != NULL)
  11186. {
  11187. if (auto identifier = BfNodeDynCast<BfIdentifierNode>(scopedTarget->mScopeName))
  11188. autoComplete->CheckLabel(identifier, scopedTarget->mColonToken);
  11189. }
  11190. //mModule->FindScope(scopedTarget->mScopeName);
  11191. }
  11192. bool isCascade = false;
  11193. BfAstNode* cascadeOperatorToken = NULL;
  11194. bool bypassVirtual = false;
  11195. bool gaveUnqualifiedDotError = false;
  11196. String targetFunctionName;
  11197. BfTypedValue thisValue;
  11198. //TODO: This may just be a fully qualified static method name, so let's check that also
  11199. if (auto memberRefExpression = BfNodeDynCast<BfMemberReferenceExpression>(target))
  11200. {
  11201. if (autoComplete != NULL)
  11202. {
  11203. if (memberRefExpression->mTarget != NULL)
  11204. autoComplete->CheckMemberReference(memberRefExpression->mTarget, memberRefExpression->mDotToken, memberRefExpression->mMemberName, false, mExpectingType);
  11205. else if (mExpectingType != NULL)
  11206. {
  11207. String filter;
  11208. if ((autoComplete != NULL) && (autoComplete->InitAutocomplete(memberRefExpression->mDotToken, memberRefExpression->mMemberName, filter)))
  11209. {
  11210. auto typeInst = mExpectingType->ToTypeInstance();
  11211. if (typeInst != NULL)
  11212. {
  11213. String filter;
  11214. if ((memberRefExpression->mMemberName != NULL) && (autoComplete->IsAutocompleteNode(memberRefExpression->mMemberName)))
  11215. filter = autoComplete->GetFilter(memberRefExpression->mMemberName);
  11216. bool allowPrivate = typeInst == mModule->mCurTypeInstance;
  11217. autoComplete->AddEnumTypeMembers(typeInst, filter, false, allowPrivate);
  11218. autoComplete->AddSelfResultTypeMembers(typeInst, typeInst, filter, allowPrivate);
  11219. }
  11220. }
  11221. }
  11222. }
  11223. if ((memberRefExpression->mTarget == NULL) && (memberRefExpression->mMemberName == NULL))
  11224. {
  11225. if (mExpectingType != NULL)
  11226. {
  11227. if (mExpectingType->IsSizedArray())
  11228. {
  11229. if (mModule->mParentNodeEntry != NULL)
  11230. {
  11231. if (auto invocationExpr = BfNodeDynCast<BfInvocationExpression>(mModule->mParentNodeEntry->mNode))
  11232. {
  11233. InitializedSizedArray((BfSizedArrayType*)mExpectingType, invocationExpr->mOpenParen, invocationExpr->mArguments, invocationExpr->mCommas, invocationExpr->mCloseParen);
  11234. return;
  11235. }
  11236. }
  11237. }
  11238. else if (mExpectingType->IsStruct())
  11239. {
  11240. if ((wasCapturingMethodInfo) && (autoComplete->mMethodMatchInfo != NULL))
  11241. {
  11242. autoComplete->mIsCapturingMethodMatchInfo = true;
  11243. BF_ASSERT(autoComplete->mMethodMatchInfo != NULL);
  11244. }
  11245. if (mModule->mParentNodeEntry != NULL)
  11246. {
  11247. if (auto invocationExpr = BfNodeDynCast<BfInvocationExpression>(mModule->mParentNodeEntry->mNode))
  11248. {
  11249. BfResolvedArgs argValues(invocationExpr->mOpenParen, &invocationExpr->mArguments, &invocationExpr->mCommas, invocationExpr->mCloseParen);
  11250. BfResolveArgFlags resolveArgsFlags = BfResolveArgFlag_DeferParamEval;
  11251. ResolveArgValues(argValues, resolveArgsFlags);
  11252. if ((mReceivingValue != NULL) && (mReceivingValue->mType == mExpectingType) && (mReceivingValue->IsAddr()))
  11253. {
  11254. mResult = *mReceivingValue;
  11255. mReceivingValue = NULL;
  11256. }
  11257. else
  11258. mResult = BfTypedValue(mModule->CreateAlloca(mExpectingType), mExpectingType, BfTypedValueKind_TempAddr);
  11259. MatchConstructor(target, methodBoundExpr, mResult, mExpectingType->ToTypeInstance(), argValues, false, false);
  11260. mModule->ValidateAllocation(mExpectingType, invocationExpr->mTarget);
  11261. return;
  11262. }
  11263. }
  11264. }
  11265. else
  11266. {
  11267. gaveUnqualifiedDotError = true;
  11268. mModule->Fail(StrFormat("Cannot use inferred constructor on type '%s'", mModule->TypeToString(mExpectingType).c_str()), memberRefExpression->mDotToken);
  11269. }
  11270. }
  11271. }
  11272. if (memberRefExpression->IsA<BfBaseExpression>())
  11273. bypassVirtual = true;
  11274. if (memberRefExpression->mMemberName != NULL)
  11275. methodNodeSrc = memberRefExpression->mMemberName;
  11276. if (auto attrIdentifier = BfNodeDynCast<BfAttributedIdentifierNode>(memberRefExpression->mMemberName))
  11277. {
  11278. if (attrIdentifier->mIdentifier != NULL)
  11279. methodNodeSrc = attrIdentifier->mIdentifier;
  11280. attributeState.mCustomAttributes = mModule->GetCustomAttributes(attrIdentifier->mAttributes, attributeState.mTarget);
  11281. if (attrIdentifier->mIdentifier != NULL)
  11282. targetFunctionName = attrIdentifier->mIdentifier->ToString();
  11283. }
  11284. else if (memberRefExpression->mMemberName != NULL)
  11285. targetFunctionName = memberRefExpression->mMemberName->ToString();
  11286. if (memberRefExpression->mTarget == NULL)
  11287. {
  11288. if (mExpectingType)
  11289. mResult = BfTypedValue(mExpectingType);
  11290. else if (!gaveUnqualifiedDotError)
  11291. mModule->Fail("Unqualified dot syntax can only be used when the result type can be inferred", memberRefExpression->mDotToken);
  11292. }
  11293. else if (auto typeRef = BfNodeDynCast<BfTypeReference>(memberRefExpression->mTarget))
  11294. {
  11295. // Static method
  11296. mResult = BfTypedValue(ResolveTypeRef(typeRef));
  11297. }
  11298. if (auto leftIdentifier = BfNodeDynCast<BfIdentifierNode>(memberRefExpression->mTarget))
  11299. {
  11300. bool hadError = false;
  11301. thisValue = LookupIdentifier(leftIdentifier, true, &hadError);
  11302. CheckResultForReading(thisValue);
  11303. if (mPropDef != NULL)
  11304. thisValue = GetResult(true);
  11305. if (hadError)
  11306. {
  11307. mModule->AssertErrorState();
  11308. thisValue = mModule->GetDefaultTypedValue(mModule->mContext->mBfObjectType);
  11309. }
  11310. if ((!thisValue) && (mPropDef == NULL))
  11311. {
  11312. // Identifier not found. Static method? Just check speculatively don't throw error
  11313. BfType* type;
  11314. {
  11315. SetAndRestoreValue<bool> prevIgnoreErrors(mModule->mIgnoreErrors, true);
  11316. type = mModule->ResolveTypeRef(leftIdentifier, NULL, BfPopulateType_DataAndMethods, BfResolveTypeRefFlag_NoResolveGenericParam);
  11317. }
  11318. if (type != NULL)
  11319. thisValue = BfTypedValue(type);
  11320. else if (auto qualifiedLeft = BfNodeDynCast<BfQualifiedNameNode>(leftIdentifier))
  11321. {
  11322. LookupQualifiedStaticField(qualifiedLeft, true);
  11323. thisValue = mResult;
  11324. mResult = BfTypedValue();
  11325. }
  11326. }
  11327. if (mPropDef != NULL)
  11328. thisValue = GetResult(true);
  11329. if (!thisValue.mType)
  11330. {
  11331. mModule->Fail("Identifier not found", leftIdentifier);
  11332. mModule->CheckTypeRefFixit(leftIdentifier);
  11333. thisValue = mModule->GetDefaultTypedValue(mModule->mContext->mBfObjectType);
  11334. }
  11335. if (mResult)
  11336. CheckResultForReading(mResult);
  11337. mResult = thisValue;
  11338. }
  11339. else if (auto expr = BfNodeDynCast<BfExpression>(memberRefExpression->mTarget))
  11340. {
  11341. BfType* expectingTargetType = NULL;
  11342. if (memberRefExpression->mDotToken->mToken == BfToken_DotDot)
  11343. expectingTargetType = mExpectingType;
  11344. bool handled = false;
  11345. if (auto subMemberRefExpr = BfNodeDynCast<BfMemberReferenceExpression>(expr))
  11346. {
  11347. String findName;
  11348. if (subMemberRefExpr->mMemberName != NULL)
  11349. findName = subMemberRefExpr->mMemberName->ToString();
  11350. if (findName == "base") // Generic IFace<T>.base
  11351. {
  11352. thisValue = mModule->GetThis();
  11353. if (thisValue)
  11354. {
  11355. VisitChild(subMemberRefExpr->mTarget);
  11356. if (mResult.HasType())
  11357. {
  11358. if (mResult.mValue)
  11359. {
  11360. mModule->Fail("Type name expected", subMemberRefExpr->mTarget);
  11361. }
  11362. else
  11363. {
  11364. auto type = mResult.mType;
  11365. if (type != NULL)
  11366. {
  11367. if ((thisValue.mType == type) || (!mModule->TypeIsSubTypeOf(thisValue.mType->ToTypeInstance(), type->ToTypeInstance())))
  11368. {
  11369. mModule->Fail(StrFormat("Type '%s' is not a base type of '%s'",
  11370. mModule->TypeToString(type).c_str(),
  11371. mModule->TypeToString(thisValue.mType).c_str()), subMemberRefExpr->mTarget);
  11372. }
  11373. else
  11374. {
  11375. if (type->IsInterface())
  11376. {
  11377. thisValue.mType = type;
  11378. }
  11379. else
  11380. {
  11381. auto castedThis = mModule->Cast(subMemberRefExpr->mMemberName, thisValue, type, BfCastFlags_Explicit);
  11382. if (castedThis)
  11383. thisValue = castedThis;
  11384. //mModule->Fail("Explicit base types can only be used for specifying default interface members", qualifiedLeft->mLeft);
  11385. }
  11386. }
  11387. handled = true;
  11388. }
  11389. bypassVirtual = true;
  11390. }
  11391. }
  11392. }
  11393. }
  11394. }
  11395. if (!handled)
  11396. {
  11397. SetAndRestoreValue<BfAttributeState*> prevAttributeState(mModule->mAttributeState, &attributeState);
  11398. auto flags = (BfEvalExprFlags)(BfEvalExprFlags_PropogateNullConditional | BfEvalExprFlags_NoCast);
  11399. if (mFunctionBindResult != NULL)
  11400. {
  11401. if (auto paranExpr = BfNodeDynCast<BfParenthesizedExpression>(expr))
  11402. {
  11403. // Allow 'ref' on binding, to indicate we want to capture 'this' by reference
  11404. flags = (BfEvalExprFlags)(flags | BfEvalExprFlags_AllowRefExpr);
  11405. expr = paranExpr->mExpression;
  11406. }
  11407. }
  11408. if (expr != NULL)
  11409. mResult = mModule->CreateValueFromExpression(expr, expectingTargetType, flags);
  11410. }
  11411. }
  11412. isCascade = (memberRefExpression->mDotToken != NULL) && (memberRefExpression->mDotToken->GetToken() == BfToken_DotDot);
  11413. if (isCascade)
  11414. cascadeOperatorToken = memberRefExpression->mDotToken;
  11415. bool isNullCondLookup = (memberRefExpression->mDotToken != NULL) && (memberRefExpression->mDotToken->GetToken() == BfToken_QuestionDot);
  11416. if (isNullCondLookup)
  11417. mResult = SetupNullConditional(mResult, memberRefExpression->mDotToken);
  11418. if ((mResult.mType == NULL) && (memberRefExpression->mTarget != NULL))
  11419. {
  11420. mModule->AssertErrorState();
  11421. mResult = mModule->GetDefaultTypedValue(mModule->mContext->mBfObjectType);
  11422. }
  11423. thisValue = mResult;
  11424. mResult = BfTypedValue();
  11425. }
  11426. else if (auto qualifiedName = BfNodeDynCast<BfQualifiedNameNode>(target))
  11427. {
  11428. if (GetAutoComplete() != NULL)
  11429. GetAutoComplete()->CheckMemberReference(qualifiedName->mLeft, qualifiedName->mDot, qualifiedName->mRight);
  11430. if (qualifiedName->mLeft->GetSrcLength() == 4)
  11431. {
  11432. StringT<16> leftName;
  11433. qualifiedName->mLeft->ToString(leftName);
  11434. if (leftName == "base")
  11435. bypassVirtual = true;
  11436. }
  11437. if (qualifiedName->mRight != NULL)
  11438. methodNodeSrc = qualifiedName->mRight;
  11439. if (auto attrIdentifier = BfNodeDynCast<BfAttributedIdentifierNode>(qualifiedName->mRight))
  11440. {
  11441. if (attrIdentifier->mIdentifier != NULL)
  11442. methodNodeSrc = attrIdentifier->mIdentifier;
  11443. attributeState.mCustomAttributes = mModule->GetCustomAttributes(attrIdentifier->mAttributes, attributeState.mTarget);
  11444. targetFunctionName = attrIdentifier->mIdentifier->ToString();
  11445. }
  11446. else
  11447. targetFunctionName = qualifiedName->mRight->ToString();
  11448. bool hadError = false;
  11449. thisValue = LookupIdentifier(qualifiedName->mLeft, true, &hadError);
  11450. CheckResultForReading(thisValue);
  11451. if (mPropDef != NULL)
  11452. thisValue = GetResult(true);
  11453. if (hadError)
  11454. {
  11455. mModule->AssertErrorState();
  11456. thisValue = mModule->GetDefaultTypedValue(mModule->mContext->mBfObjectType);
  11457. }
  11458. if ((!thisValue) && (mPropDef == NULL))
  11459. {
  11460. // Identifier not found. Static method? Just check speculatively don't throw error
  11461. BfType* type;
  11462. {
  11463. //SetAndRestoreValue<bool> prevIgnoreErrors(mModule->mIgnoreErrors, true);
  11464. type = mModule->ResolveTypeRef(qualifiedName->mLeft, NULL, BfPopulateType_DataAndMethods, (BfResolveTypeRefFlags)(BfResolveTypeRefFlag_NoResolveGenericParam | BfResolveTypeRefFlag_IgnoreLookupError));
  11465. }
  11466. if (type == NULL)
  11467. {
  11468. //SetAndRestoreValue<bool> prevIgnoreErrors(mModule->mIgnoreErrors, true);
  11469. type = mModule->ResolveTypeRef(qualifiedName, methodGenericArguments, BfPopulateType_DataAndMethods, (BfResolveTypeRefFlags)(BfResolveTypeRefFlag_NoResolveGenericParam | BfResolveTypeRefFlag_IgnoreLookupError));
  11470. if (type != NULL)
  11471. {
  11472. // This is a CTOR call, treat it as such
  11473. targetFunctionName.clear();
  11474. }
  11475. }
  11476. if (type != NULL)
  11477. thisValue = BfTypedValue(type);
  11478. else if (auto qualifiedLeft = BfNodeDynCast<BfQualifiedNameNode>(qualifiedName->mLeft))
  11479. {
  11480. String findName = qualifiedLeft->mRight->ToString();
  11481. bool handled = false;
  11482. if (findName == "base")
  11483. {
  11484. auto type = mModule->ResolveTypeRef(qualifiedLeft->mLeft, NULL, BfPopulateType_Data, BfResolveTypeRefFlag_AllowRef);
  11485. mModule->CheckTypeRefFixit(qualifiedLeft->mLeft);
  11486. thisValue = mModule->GetThis();
  11487. if (type != NULL)
  11488. {
  11489. if ((thisValue.mType == type) || (!mModule->TypeIsSubTypeOf(thisValue.mType->ToTypeInstance(), type->ToTypeInstance())))
  11490. {
  11491. mModule->Fail(StrFormat("Type '%s' is not a base type of '%s'",
  11492. mModule->TypeToString(type).c_str(),
  11493. mModule->TypeToString(thisValue.mType).c_str()), qualifiedLeft->mLeft);
  11494. }
  11495. else
  11496. {
  11497. if (type->IsInterface())
  11498. {
  11499. thisValue.mType = type;
  11500. }
  11501. else
  11502. {
  11503. auto castedThis = mModule->Cast(qualifiedLeft->mRight, thisValue, type, BfCastFlags_Explicit);
  11504. if (castedThis)
  11505. thisValue = castedThis;
  11506. //mModule->Fail("Explicit base types can only be used for specifying default interface members", qualifiedLeft->mLeft);
  11507. }
  11508. }
  11509. handled = true;
  11510. }
  11511. bypassVirtual = true;
  11512. }
  11513. if (!handled)
  11514. {
  11515. LookupQualifiedStaticField(qualifiedLeft, true);
  11516. thisValue = mResult;
  11517. mResult = BfTypedValue();
  11518. }
  11519. }
  11520. }
  11521. if (mPropDef != NULL)
  11522. thisValue = GetResult(true);
  11523. if (!thisValue.mType)
  11524. {
  11525. mModule->Fail("Identifier not found", qualifiedName->mLeft);
  11526. mModule->CheckTypeRefFixit(qualifiedName->mLeft);
  11527. mModule->CheckIdentifierFixit(qualifiedName->mLeft);
  11528. thisValue = mModule->GetDefaultTypedValue(mModule->mContext->mBfObjectType);
  11529. }
  11530. if (mResult)
  11531. CheckResultForReading(mResult);
  11532. mResult = BfTypedValue();
  11533. }
  11534. else if (auto identiferExpr = BfNodeDynCast<BfIdentifierNode>(target))
  11535. {
  11536. if (auto attrIdentifier = BfNodeDynCast<BfAttributedIdentifierNode>(target))
  11537. {
  11538. if (attrIdentifier->mIdentifier != NULL)
  11539. methodNodeSrc = attrIdentifier->mIdentifier;
  11540. attributeState.mCustomAttributes = mModule->GetCustomAttributes(attrIdentifier->mAttributes, attributeState.mTarget);
  11541. }
  11542. allowImplicitThis = true;
  11543. if (autoComplete != NULL)
  11544. autoComplete->CheckIdentifier(identiferExpr);
  11545. targetFunctionName = target->ToString();
  11546. if (targetFunctionName == "PrintF") // Just directly call that one
  11547. {
  11548. BfType* charType = mModule->GetPrimitiveType(BfTypeCode_Char8);
  11549. BfType* charPtrType = mModule->CreatePointerType(charType);
  11550. auto func = mModule->GetBuiltInFunc(BfBuiltInFuncType_PrintF);
  11551. SizedArray<BfIRValue, 4> irArgs;
  11552. for (BfExpression* arg : args)
  11553. {
  11554. BfTypedValue value;
  11555. if (arg != NULL)
  11556. value = mModule->CreateValueFromExpression(arg);
  11557. if (!value)
  11558. return;
  11559. auto typeInst = value.mType->ToTypeInstance();
  11560. if ((typeInst != NULL) && (typeInst->mTypeDef == mModule->mCompiler->mStringTypeDef))
  11561. value = mModule->Cast(arg, value, charPtrType);
  11562. if ((value.mType->IsFloat()) && (value.mType->mSize != 8)) // Always cast float to double
  11563. value = mModule->Cast(arg, value, mModule->GetPrimitiveType(BfTypeCode_Double));
  11564. irArgs.push_back(value.mValue);
  11565. }
  11566. if ((targetFunctionName != "PrintF") || (irArgs.size() > 0))
  11567. {
  11568. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateCall(func, irArgs/*, targetFunctionName*/),
  11569. mModule->ResolveTypeDef(mModule->mSystem->mTypeInt32));
  11570. }
  11571. return;
  11572. }
  11573. }
  11574. else if (auto expr = BfNodeDynCast<BfExpression>(target))
  11575. {
  11576. auto innerInvocationResult = mModule->CreateValueFromExpression(expr);
  11577. if (!innerInvocationResult)
  11578. {
  11579. mModule->AssertErrorState();
  11580. innerInvocationResult = mModule->GetDefaultTypedValue(mModule->mContext->mBfObjectType);
  11581. }
  11582. if (innerInvocationResult.mType->IsVar())
  11583. {
  11584. mResult = innerInvocationResult;
  11585. return;
  11586. }
  11587. targetFunctionName = "Invoke";
  11588. if (innerInvocationResult.mType->IsTypeInstance())
  11589. {
  11590. auto invocationTypeInst = innerInvocationResult.mType->ToTypeInstance();
  11591. if (invocationTypeInst->mTypeDef->mIsDelegate)
  11592. {
  11593. thisValue = innerInvocationResult;
  11594. }
  11595. }
  11596. if (!thisValue)
  11597. {
  11598. mModule->Fail(StrFormat("Cannot perform invocation on type '%s'", mModule->TypeToString(innerInvocationResult.mType).c_str()), expr);
  11599. thisValue = mModule->GetDefaultTypedValue(mModule->mContext->mBfObjectType);
  11600. }
  11601. }
  11602. else
  11603. {
  11604. mModule->Fail("Invalid invocation target", target);
  11605. thisValue = mModule->GetDefaultTypedValue(mModule->mContext->mBfObjectType);
  11606. }
  11607. if ((wasCapturingMethodInfo) && (autoComplete->mMethodMatchInfo != NULL))
  11608. {
  11609. autoComplete->mIsCapturingMethodMatchInfo = true;
  11610. BF_ASSERT(autoComplete->mMethodMatchInfo != NULL);
  11611. }
  11612. SetAndRestoreValue<BfAttributeState*> prevAttributeState;
  11613. if (attributeState.mCustomAttributes != NULL)
  11614. prevAttributeState.Init(mModule->mAttributeState, &attributeState);
  11615. if ((targetFunctionName != "") && (targetFunctionName[targetFunctionName.length() - 1] == '!'))
  11616. {
  11617. targetFunctionName = targetFunctionName.Substring(0, targetFunctionName.length() - 1);
  11618. InjectMixin(methodNodeSrc, thisValue, allowImplicitThis, targetFunctionName, args, methodGenericArguments);
  11619. return;
  11620. }
  11621. //TODO: We removed this... Messed up with PrimStruct 'this' non-mut errors
  11622. // 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
  11623. /*if (thisValue)
  11624. {
  11625. if ((!thisValue.mType->IsGenericParam()) && (!thisValue.IsSplat()) && (!thisValue.mType->IsVar()))
  11626. thisValue = MakeCallableTarget(target, thisValue);
  11627. }*/
  11628. int methodCount = 0;
  11629. bool mayBeSkipCall = false;
  11630. if (thisValue.mType != NULL)
  11631. {
  11632. auto checkTypeInst = thisValue.mType->ToTypeInstance();
  11633. while (checkTypeInst != NULL)
  11634. {
  11635. checkTypeInst->mTypeDef->PopulateMemberSets();
  11636. BfMemberSetEntry* memberSetEntry;
  11637. if (checkTypeInst->mTypeDef->mMethodSet.TryGetWith(targetFunctionName, &memberSetEntry))
  11638. {
  11639. BfMethodDef* methodDef = (BfMethodDef*)memberSetEntry->mMemberDef;
  11640. while (methodDef != NULL)
  11641. {
  11642. if (methodDef->mIsSkipCall)
  11643. mayBeSkipCall = true;
  11644. methodDef = methodDef->mNextWithSameName;
  11645. }
  11646. }
  11647. checkTypeInst = checkTypeInst->mBaseType;
  11648. }
  11649. }
  11650. SizedArray<BfExpression*, 8> copiedArgs;
  11651. for (BfExpression* arg : args)
  11652. copiedArgs.push_back(arg);
  11653. BfSizedArray<BfExpression*> sizedCopiedArgs(copiedArgs);
  11654. BfResolvedArgs argValues(&sizedCopiedArgs);
  11655. if (mModule->mParentNodeEntry != NULL)
  11656. {
  11657. if (auto invocationExpr = BfNodeDynCast<BfInvocationExpression>(mModule->mParentNodeEntry->mNode))
  11658. {
  11659. argValues.mOpenToken = invocationExpr->mOpenParen;
  11660. argValues.mCommas = &invocationExpr->mCommas;
  11661. argValues.mCloseToken = invocationExpr->mCloseParen;
  11662. }
  11663. }
  11664. BfResolveArgFlags resolveArgsFlags = (BfResolveArgFlags)(BfResolveArgFlag_DeferFixits | BfResolveArgFlag_AllowUnresolvedTypes);
  11665. resolveArgsFlags = (BfResolveArgFlags)(resolveArgsFlags | BfResolveArgFlag_DeferParamEval);
  11666. if (mayBeSkipCall)
  11667. resolveArgsFlags = (BfResolveArgFlags)(resolveArgsFlags | BfResolveArgFlag_DeferParamValues);
  11668. static int sCallIdx = 0;
  11669. sCallIdx++;
  11670. int callIdx = sCallIdx;
  11671. if (callIdx == 1557)
  11672. {
  11673. NOP;
  11674. }
  11675. BfCheckedKind checkedKind = BfCheckedKind_NotSet;
  11676. if (attributeState.mCustomAttributes != NULL)
  11677. {
  11678. if (attributeState.mCustomAttributes->Contains(mModule->mCompiler->mCheckedAttributeTypeDef))
  11679. checkedKind = BfCheckedKind_Checked;
  11680. if (attributeState.mCustomAttributes->Contains(mModule->mCompiler->mUncheckedAttributeTypeDef))
  11681. checkedKind = BfCheckedKind_Unchecked;
  11682. }
  11683. SetAndRestoreValue<bool> prevUsedAsStatement(mUsedAsStatement, mUsedAsStatement || isCascade);
  11684. ResolveArgValues(argValues, resolveArgsFlags);
  11685. mResult = MatchMethod(methodNodeSrc, methodBoundExpr, thisValue, allowImplicitThis, bypassVirtual, targetFunctionName, argValues, methodGenericArguments, checkedKind);
  11686. argValues.HandleFixits(mModule);
  11687. if (isCascade)
  11688. {
  11689. if (outCascadeValue != NULL)
  11690. {
  11691. *outCascadeValue = thisValue;
  11692. }
  11693. else
  11694. {
  11695. mModule->Fail("Invalid use of cascade operator", cascadeOperatorToken);
  11696. }
  11697. }
  11698. }
  11699. void BfExprEvaluator::Visit(BfInvocationExpression* invocationExpr)
  11700. {
  11701. BfAutoParentNodeEntry autoParentNodeEntry(mModule, invocationExpr);
  11702. // We need to check for sized array constructor like "uint8[2](1, 2)"
  11703. if (BfNodeDynCastExact<BfIndexerExpression>(invocationExpr->mTarget) != NULL)
  11704. {
  11705. auto checkTarget = invocationExpr->mTarget;
  11706. while (auto indexerExpr = BfNodeDynCastExact<BfIndexerExpression>(checkTarget))
  11707. {
  11708. checkTarget = indexerExpr->mTarget;
  11709. }
  11710. SetAndRestoreValue<bool> prevIgnoreError(mModule->mIgnoreErrors, true);
  11711. auto resolvedType = mModule->ResolveTypeRef(checkTarget, NULL, BfPopulateType_Identity);
  11712. prevIgnoreError.Restore();
  11713. if (resolvedType != NULL)
  11714. {
  11715. BfType* curType = resolvedType;
  11716. auto checkTarget = invocationExpr->mTarget;
  11717. while (auto indexerExpr = BfNodeDynCastExact<BfIndexerExpression>(checkTarget))
  11718. {
  11719. checkTarget = indexerExpr->mTarget;
  11720. if (indexerExpr->mCommas.size() != 0)
  11721. 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]);
  11722. int arrSize = 0;
  11723. if (indexerExpr->mArguments.size() != 0)
  11724. {
  11725. BfConstResolver constResolver(mModule);
  11726. auto arg = indexerExpr->mArguments[0];
  11727. if (arg != NULL)
  11728. constResolver.Resolve(arg);
  11729. if (constResolver.mResult.mValue.IsConst())
  11730. {
  11731. auto constant = mModule->mBfIRBuilder->GetConstant(constResolver.mResult.mValue);
  11732. if ((mModule->mBfIRBuilder->IsInt(constant->mTypeCode)) && (constant->mInt64 >= 0))
  11733. {
  11734. arrSize = constant->mInt32;
  11735. }
  11736. else
  11737. mModule->Fail("Non-negative integer expected", indexerExpr->mArguments[0]);
  11738. }
  11739. }
  11740. else
  11741. arrSize = invocationExpr->mArguments.size();
  11742. curType = mModule->CreateSizedArrayType(curType, arrSize);
  11743. }
  11744. InitializedSizedArray((BfSizedArrayType*)curType, invocationExpr->mOpenParen, invocationExpr->mArguments, invocationExpr->mCommas, invocationExpr->mCloseParen, NULL);
  11745. return;
  11746. }
  11747. }
  11748. auto autoComplete = GetAutoComplete();
  11749. auto wasCapturingMethodInfo = (autoComplete != NULL) && (autoComplete->mIsCapturingMethodMatchInfo);
  11750. if (autoComplete != NULL)
  11751. autoComplete->CheckInvocation(invocationExpr, invocationExpr->mOpenParen, invocationExpr->mCloseParen, invocationExpr->mCommas);
  11752. mModule->UpdateExprSrcPos(invocationExpr);
  11753. BfSizedArray<ASTREF(BfTypeReference*)>* methodGenericArguments = NULL;
  11754. if (invocationExpr->mGenericArgs != NULL)
  11755. methodGenericArguments = &invocationExpr->mGenericArgs->mGenericArgs;
  11756. SizedArray<BfExpression*, 8> copiedArgs;
  11757. for (BfExpression* arg : invocationExpr->mArguments)
  11758. copiedArgs.push_back(arg);
  11759. BfTypedValue cascadeValue;
  11760. DoInvocation(invocationExpr->mTarget, invocationExpr, copiedArgs, methodGenericArguments, &cascadeValue);
  11761. if (autoComplete != NULL)
  11762. {
  11763. if ((wasCapturingMethodInfo) && (!autoComplete->mIsCapturingMethodMatchInfo))
  11764. {
  11765. if (autoComplete->mMethodMatchInfo != NULL)
  11766. autoComplete->mIsCapturingMethodMatchInfo = true;
  11767. else
  11768. autoComplete->mIsCapturingMethodMatchInfo = false;
  11769. //BF_ASSERT(autoComplete->mMethodMatchInfo != NULL);
  11770. }
  11771. else
  11772. autoComplete->mIsCapturingMethodMatchInfo = false;
  11773. }
  11774. /// Previous check for discard
  11775. if (cascadeValue)
  11776. mResult = cascadeValue;
  11777. }
  11778. BfMethodDef* BfExprEvaluator::GetPropertyMethodDef(BfPropertyDef* propDef, BfMethodType methodType, BfCheckedKind checkedKind)
  11779. {
  11780. BfMethodDef* matchedMethod = NULL;
  11781. BfMethodDef* backupMethod = NULL;
  11782. for (auto methodDef : propDef->mMethods)
  11783. {
  11784. if (methodDef->mMethodType != methodType)
  11785. continue;
  11786. if (methodDef->mCheckedKind == checkedKind)
  11787. {
  11788. matchedMethod = methodDef;
  11789. break;
  11790. }
  11791. if ((checkedKind == BfCheckedKind_NotSet) && (methodDef->mCheckedKind == mModule->GetDefaultCheckedKind()))
  11792. matchedMethod = methodDef;
  11793. else
  11794. backupMethod = methodDef;
  11795. }
  11796. if (matchedMethod == NULL)
  11797. matchedMethod = backupMethod;
  11798. return matchedMethod;
  11799. }
  11800. BfModuleMethodInstance BfExprEvaluator::GetPropertyMethodInstance(BfMethodDef* methodDef)
  11801. {
  11802. if (mPropDefBypassVirtual)
  11803. {
  11804. if (mPropTarget.mType->IsInterface())
  11805. {
  11806. auto curTypeInst = mPropTarget.mType->ToTypeInstance();
  11807. if (mModule->TypeIsSubTypeOf(mModule->mCurTypeInstance, curTypeInst))
  11808. {
  11809. // This is an explicit call to a default static interface method. We pull the methodDef into our own concrete type.
  11810. mPropTarget = mModule->GetThis();
  11811. return mModule->GetMethodInstance(mModule->mCurTypeInstance, methodDef, BfTypeVector(), BfGetMethodInstanceFlag_ForeignMethodDef, curTypeInst);
  11812. }
  11813. else
  11814. {
  11815. mModule->Fail("Property is not implemented by this type", mPropSrc);
  11816. return BfModuleMethodInstance();
  11817. }
  11818. }
  11819. else
  11820. {
  11821. auto propTypeInst = mPropTarget.mType->ToTypeInstance();
  11822. auto rawMethodInstance = mModule->GetRawMethodInstance(propTypeInst, methodDef);
  11823. auto useTypeInst = mOrigPropTarget.mType->ToTypeInstance();
  11824. auto virtualMethod = (BfMethodInstance*)useTypeInst->mVirtualMethodTable[rawMethodInstance->mVirtualTableIdx].mImplementingMethod;
  11825. return mModule->ReferenceExternalMethodInstance(virtualMethod);
  11826. }
  11827. }
  11828. if ((mOrigPropTarget) && (mOrigPropTarget.mType != mPropTarget.mType) &&
  11829. ((!mOrigPropTarget.mType->IsGenericParam()) && (mPropTarget.mType->IsInterface())))
  11830. {
  11831. auto checkType = mOrigPropTarget.mType;
  11832. if (checkType->IsPointer())
  11833. checkType = ((BfPointerType*)checkType)->mElementType;
  11834. if (checkType->IsWrappableType())
  11835. checkType = mModule->GetWrappedStructType(checkType);
  11836. if ((checkType != NULL) && (checkType->IsTypeInstance()))
  11837. {
  11838. auto activeTypeDef = mModule->GetActiveTypeDef();
  11839. BfTypeInterfaceEntry* bestIFaceEntry = NULL;
  11840. bool checkedUnderlying = false;
  11841. auto checkTypeInst = checkType->ToTypeInstance();
  11842. while (checkTypeInst != NULL)
  11843. {
  11844. mModule->PopulateType(checkTypeInst, BfPopulateType_DataAndMethods);
  11845. for (auto& iface : checkTypeInst->mInterfaces)
  11846. {
  11847. if (!checkTypeInst->IsTypeMemberAccessible(iface.mDeclaringType, activeTypeDef))
  11848. continue;
  11849. if (iface.mInterfaceType == mPropTarget.mType)
  11850. {
  11851. if (bestIFaceEntry == NULL)
  11852. {
  11853. bestIFaceEntry = &iface;
  11854. continue;
  11855. }
  11856. bool isBetter;
  11857. bool isWorse;
  11858. mModule->CompareDeclTypes(iface.mDeclaringType, bestIFaceEntry->mDeclaringType, isBetter, isWorse);
  11859. if (isBetter == isWorse)
  11860. {
  11861. // Failed
  11862. }
  11863. else
  11864. {
  11865. if (isBetter)
  11866. bestIFaceEntry = &iface;
  11867. }
  11868. }
  11869. }
  11870. if (bestIFaceEntry != NULL)
  11871. break;
  11872. checkTypeInst = checkTypeInst->mBaseType;
  11873. if (checkTypeInst == NULL)
  11874. {
  11875. if (!checkedUnderlying)
  11876. {
  11877. checkedUnderlying = true;
  11878. if (checkType->HasWrappedRepresentation())
  11879. {
  11880. auto underlyingType = checkType->GetUnderlyingType();
  11881. if (underlyingType != NULL)
  11882. checkTypeInst = mModule->GetWrappedStructType(underlyingType);
  11883. }
  11884. }
  11885. }
  11886. }
  11887. if (bestIFaceEntry != NULL)
  11888. {
  11889. auto ifaceMethodEntry = checkTypeInst->mInterfaceMethodTable[bestIFaceEntry->mStartInterfaceTableIdx + methodDef->mIdx];
  11890. BfMethodInstance* bestMethodInstance = ifaceMethodEntry.mMethodRef;
  11891. if (bestMethodInstance != NULL)
  11892. {
  11893. mPropTarget = mOrigPropTarget;
  11894. mPropTarget.mType = checkTypeInst;
  11895. return mModule->GetMethodInstanceAtIdx(ifaceMethodEntry.mMethodRef.mTypeInstance, ifaceMethodEntry.mMethodRef.mMethodNum);
  11896. }
  11897. }
  11898. }
  11899. mModule->AssertErrorState();
  11900. return BfModuleMethodInstance();
  11901. }
  11902. auto propTypeInst = mPropTarget.mType->ToTypeInstance();
  11903. if (propTypeInst == NULL)
  11904. {
  11905. propTypeInst = mModule->GetWrappedStructType(mPropTarget.mType);
  11906. }
  11907. if (propTypeInst == NULL)
  11908. {
  11909. mModule->Fail("INTERNAL ERROR: Invalid property target", mPropSrc);
  11910. return BfModuleMethodInstance();
  11911. }
  11912. return mModule->GetMethodInstance(propTypeInst, methodDef, BfTypeVector(), mPropGetMethodFlags);
  11913. }
  11914. void BfExprEvaluator::CheckPropFail(BfMethodDef* propMethodDef, BfMethodInstance* methodInstance)
  11915. {
  11916. auto propTypeInst = mPropTarget.mType->ToTypeInstance();
  11917. // If mExplicitInterface is null then we are implicitly calling through an interface
  11918. if ((propTypeInst != NULL) && (methodInstance->GetExplicitInterface() == NULL) && (!mModule->CheckAccessMemberProtection(propMethodDef->mProtection, propTypeInst)))
  11919. mModule->Fail(StrFormat("'%s' is inaccessible due to its protection level", mModule->MethodToString(methodInstance).c_str()), mPropSrc);
  11920. else if (mPropCheckedKind != methodInstance->mMethodDef->mCheckedKind)
  11921. {
  11922. bool passes = true;
  11923. if (mPropCheckedKind != BfCheckedKind_NotSet)
  11924. {
  11925. passes = false;
  11926. }
  11927. else
  11928. {
  11929. auto defaultCheckedKind = mModule->GetDefaultCheckedKind();
  11930. if (defaultCheckedKind != methodInstance->mMethodDef->mCheckedKind)
  11931. passes = false;
  11932. }
  11933. if (!passes)
  11934. {
  11935. 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);
  11936. if (error != NULL)
  11937. {
  11938. if ((error != NULL) && (methodInstance->mMethodDef->mMethodDeclaration != NULL))
  11939. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("See method declaration"), methodInstance->mMethodDef->GetRefNode());
  11940. }
  11941. }
  11942. }
  11943. }
  11944. BfTypedValue BfExprEvaluator::GetResult(bool clearResult, bool resolveGenericType)
  11945. {
  11946. if ((!mResult) && (mPropDef != NULL))
  11947. {
  11948. BfMethodDef* matchedMethod = GetPropertyMethodDef(mPropDef, BfMethodType_PropertyGetter, mPropCheckedKind);
  11949. if (matchedMethod == NULL)
  11950. {
  11951. mModule->Fail("Property has no getter", mPropSrc);
  11952. return mResult;
  11953. }
  11954. auto methodInstance = GetPropertyMethodInstance(matchedMethod);
  11955. if (methodInstance.mMethodInstance == NULL)
  11956. return mResult;
  11957. if (!mModule->mBfIRBuilder->mIgnoreWrites)
  11958. {
  11959. BF_ASSERT(!methodInstance.mFunc.IsFake());
  11960. }
  11961. if (mPropSrc != NULL)
  11962. mModule->UpdateExprSrcPos(mPropSrc);
  11963. CheckPropFail(matchedMethod, methodInstance.mMethodInstance);
  11964. PerformCallChecks(methodInstance.mMethodInstance, mPropSrc);
  11965. if (methodInstance.mMethodInstance->IsSkipCall())
  11966. {
  11967. mResult = mModule->GetDefaultTypedValue(methodInstance.mMethodInstance->mReturnType);
  11968. }
  11969. else
  11970. {
  11971. SizedArray<BfIRValue, 4> args;
  11972. if (!matchedMethod->mIsStatic)
  11973. {
  11974. if ((mPropDefBypassVirtual) && (mPropTarget.mType != methodInstance.mMethodInstance->GetOwner()))
  11975. mPropTarget = mModule->Cast(mPropSrc, mOrigPropTarget, methodInstance.mMethodInstance->GetOwner());
  11976. mModule->EmitObjectAccessCheck(mPropTarget);
  11977. PushThis(mPropSrc, mPropTarget, methodInstance.mMethodInstance, args);
  11978. }
  11979. bool failed = false;
  11980. for (int paramIdx = 0; paramIdx < (int)mIndexerValues.size(); paramIdx++)
  11981. {
  11982. auto val = mModule->Cast(mPropSrc, mIndexerValues[paramIdx].mTypedValue, methodInstance.mMethodInstance->GetParamType(paramIdx));
  11983. if (!val)
  11984. failed = true;
  11985. else
  11986. PushArg(val, args);
  11987. }
  11988. if (mPropDefBypassVirtual)
  11989. {
  11990. auto methodDef = methodInstance.mMethodInstance->mMethodDef;
  11991. if ((methodDef->mIsAbstract) && (mPropDefBypassVirtual))
  11992. {
  11993. mModule->Fail(StrFormat("Abstract base property method '%s' cannot be invoked", mModule->MethodToString(methodInstance.mMethodInstance).c_str()), mPropSrc);
  11994. }
  11995. }
  11996. if (failed)
  11997. mResult = mModule->GetDefaultTypedValue(methodInstance.mMethodInstance->mReturnType);
  11998. else
  11999. mResult = CreateCall(methodInstance.mMethodInstance, methodInstance.mFunc, mPropDefBypassVirtual, args);
  12000. if (mResult.mType != NULL)
  12001. {
  12002. if ((mResult.mType->IsVar()) && (mModule->mCompiler->mIsResolveOnly))
  12003. mModule->Fail("Property type reference failed to resolve", mPropSrc);
  12004. BF_ASSERT(!mResult.mType->IsRef());
  12005. }
  12006. }
  12007. mPropDef = NULL;
  12008. mPropDefBypassVirtual = false;
  12009. mIndexerValues.clear();
  12010. mResultLocalVar = NULL;
  12011. }
  12012. if (resolveGenericType)
  12013. ResolveGenericType();
  12014. BfTypedValue result = mResult;
  12015. if (clearResult)
  12016. mResult = BfTypedValue();
  12017. return result;
  12018. }
  12019. void BfExprEvaluator::CheckResultForReading(BfTypedValue& typedValue)
  12020. {
  12021. if (mModule->mCurMethodState == NULL)
  12022. return;
  12023. if ((mModule->mCurMethodState->mTempKind != BfMethodState::TempKind_None) || (mModule->mCurMethodState->mAllowUinitReads))
  12024. return;
  12025. if ((mModule->mCurTypeInstance->mResolvingVarField) || (mModule->mCurTypeInstance->mResolvingConstField))
  12026. return;
  12027. if ((typedValue) && (typedValue.IsAddr()))
  12028. {
  12029. if ((mResultLocalVar != NULL) && (mResultLocalVarRefNode != NULL))
  12030. {
  12031. SetAndRestoreValue<bool> prevIgnoreError(mModule->mIgnoreErrors);
  12032. if ((mModule->mCurMethodState->mClosureState != NULL) && (mModule->mCurMethodState->mClosureState->mCapturing))
  12033. {
  12034. // These errors can only be detected during capture time, so we don't ignore them on this pass
  12035. mModule->mIgnoreErrors = false;
  12036. }
  12037. int fieldIdx = mResultLocalVarField - 1;
  12038. auto localVar = mResultLocalVar;
  12039. if (localVar->mCompositeCount > 0)
  12040. {
  12041. mModule->Fail(StrFormat("Cannot read from composite '%s', it can only be used in an argument list", localVar->mName.c_str()), mResultLocalVarRefNode);
  12042. typedValue = BfTypedValue();
  12043. return;
  12044. }
  12045. if (!localVar->mIsAssigned)
  12046. {
  12047. mModule->TryLocalVariableInit(localVar);
  12048. }
  12049. if (!localVar->mIsAssigned)
  12050. {
  12051. auto methodStateForLocal = mModule->mCurMethodState->GetMethodStateForLocal(localVar);
  12052. bool isAssigned = false;
  12053. int64 undefinedFieldFlags = localVar->mUnassignedFieldFlags;
  12054. auto deferredLocalAssignData = methodStateForLocal->mDeferredLocalAssignData;
  12055. while ((deferredLocalAssignData != NULL) && (deferredLocalAssignData->mIsChained))
  12056. deferredLocalAssignData = deferredLocalAssignData->mChainedAssignData;
  12057. if (deferredLocalAssignData != NULL)
  12058. {
  12059. for (auto& assignedVar : deferredLocalAssignData->mAssignedLocals)
  12060. {
  12061. auto assignedLocal = assignedVar.mLocalVar;
  12062. if (assignedLocal == localVar)
  12063. {
  12064. int assignedFieldIdx = (assignedVar.mLocalVarField) - 1;
  12065. if (assignedFieldIdx >= 0)
  12066. undefinedFieldFlags &= ~((int64)1 << assignedFieldIdx);
  12067. else
  12068. undefinedFieldFlags = 0;
  12069. }
  12070. }
  12071. }
  12072. if (fieldIdx == -1)
  12073. {
  12074. if (undefinedFieldFlags == 0)
  12075. isAssigned = true;
  12076. }
  12077. else
  12078. {
  12079. isAssigned = true;
  12080. for (int i = 0; i < mResultLocalVarFieldCount; i++)
  12081. if ((undefinedFieldFlags & (1LL << (fieldIdx + i))) != 0)
  12082. isAssigned = false;
  12083. }
  12084. if (!isAssigned)
  12085. {
  12086. if ((localVar->mIsThis) && (fieldIdx != -1))
  12087. {
  12088. // When we have initializers for fields, they won't all be processed in the autocomplte case
  12089. if (!mModule->mCompiler->IsAutocomplete())
  12090. {
  12091. auto bfError = mModule->Fail(StrFormat("Use of possibly unassigned field '%s'", mResultLocalVarRefNode->ToString().c_str()), mResultLocalVarRefNode, true);
  12092. }
  12093. }
  12094. else
  12095. {
  12096. mModule->Fail(StrFormat("Use of unassigned local variable '%s'", localVar->mName.c_str()), mResultLocalVarRefNode);
  12097. }
  12098. }
  12099. }
  12100. localVar->mReadFromId = mModule->mCurMethodState->GetRootMethodState()->mCurAccessId++;
  12101. }
  12102. }
  12103. }
  12104. void BfExprEvaluator::FinishExpressionResult()
  12105. {
  12106. CheckResultForReading(mResult);
  12107. mResultLocalVar = NULL;
  12108. }
  12109. bool BfExprEvaluator::CheckAllowValue(const BfTypedValue& typedValue, BfAstNode* refNode)
  12110. {
  12111. return true;
  12112. }
  12113. void BfExprEvaluator::MarkResultUsed()
  12114. {
  12115. if (mResultLocalVar != NULL)
  12116. {
  12117. mResultLocalVar->mReadFromId = mModule->mCurMethodState->GetRootMethodState()->mCurAccessId++;
  12118. }
  12119. }
  12120. void BfExprEvaluator::MarkResultAssigned()
  12121. {
  12122. if (mResultLocalVar != NULL)
  12123. {
  12124. //int localIdx = mResultLocalVarIdx;
  12125. //if (localIdx == 0x7FFF)
  12126. //return;
  12127. auto localVar = mResultLocalVar;
  12128. int fieldIdx = mResultLocalVarField - 1;
  12129. int count = mResultLocalVarFieldCount;
  12130. if (fieldIdx == -1)
  12131. count = 1;
  12132. for (int i = 0; i < count; i++)
  12133. mModule->mCurMethodState->GetMethodStateForLocal(localVar)->LocalDefined(localVar, fieldIdx + i);
  12134. //if (localIdx != 0x7FFF)
  12135. {
  12136. if (localVar->mCompositeCount > 0)
  12137. {
  12138. mModule->Fail(StrFormat("Cannot write to composite '%s', it can only be used in an argument list", localVar->mName.c_str()), mResultLocalVarRefNode);
  12139. }
  12140. }
  12141. }
  12142. }
  12143. void BfExprEvaluator::MakeResultAsValue()
  12144. {
  12145. // Expressions like parens will turn a variable reference into a simple value
  12146. mResultLocalVar = NULL;
  12147. }
  12148. bool BfExprEvaluator::CheckModifyResult(BfTypedValue typedVal, BfAstNode* refNode, const char* modifyType, bool onlyNeedsMut)
  12149. {
  12150. BfLocalVariable* localVar = NULL;
  12151. bool isCapturedLocal = false;
  12152. if (mResultLocalVar != NULL)
  12153. {
  12154. localVar = mResultLocalVar;
  12155. localVar->mWrittenToId = mModule->mCurMethodState->GetRootMethodState()->mCurAccessId++;
  12156. }
  12157. else if (typedVal.IsThis())
  12158. {
  12159. localVar = mModule->GetThisVariable();
  12160. }
  12161. else if (typedVal.IsSplat())
  12162. {
  12163. for (auto checkLocal : mModule->mCurMethodState->mLocals)
  12164. {
  12165. if (checkLocal->mAddr == typedVal.mValue)
  12166. {
  12167. localVar = checkLocal;
  12168. break;
  12169. }
  12170. }
  12171. }
  12172. else if (typedVal.mValue.IsArg())
  12173. {
  12174. auto methodState = mModule->mCurMethodState->GetNonCaptureState();
  12175. localVar = methodState->mLocals[typedVal.mValue.mId];
  12176. }
  12177. if ((typedVal.mKind == BfTypedValueKind_MutableValue) && (onlyNeedsMut))
  12178. {
  12179. return true;
  12180. }
  12181. if (localVar != NULL)
  12182. {
  12183. if (((!typedVal.IsAddr()) && (!typedVal.mType->IsValuelessType())) ||
  12184. (typedVal.IsReadOnly()))
  12185. {
  12186. BfError* error = NULL;
  12187. if (localVar->mIsThis)
  12188. {
  12189. bool isClosure = false;
  12190. BfTypeInstance* checkTypeInst = localVar->mResolvedType->ToTypeInstance();
  12191. int fieldIdx = mResultLocalVarField - 1;
  12192. if ((!isCapturedLocal) && (mModule->mCurMethodState != NULL) && (mModule->mCurMethodState->mClosureState != NULL) && (mModule->mCurMethodState->mClosureState->mClosureType != NULL))
  12193. {
  12194. isClosure = true;
  12195. auto closureThis = mModule->mCurMethodState->mClosureState->mClosureType;
  12196. closureThis = checkTypeInst->mFieldInstances[0].mResolvedType->ToTypeInstance();
  12197. if (fieldIdx >= -1)
  12198. {
  12199. checkTypeInst = closureThis;
  12200. }
  12201. else
  12202. {
  12203. fieldIdx = -fieldIdx - 2;
  12204. isCapturedLocal = true;
  12205. }
  12206. }
  12207. if (fieldIdx < 0)
  12208. {
  12209. if (isClosure)
  12210. {
  12211. if (!mModule->mCurMethodState->mClosureState->mDeclaringMethodIsMutating)
  12212. error = mModule->Fail(StrFormat("Cannot %s 'this' within struct lambda. Consider adding 'mut' specifier to this method.", modifyType), refNode);
  12213. else
  12214. error = mModule->Fail(StrFormat("Cannot %s 'this' within struct lambda. Consider adding by-reference capture specifier [&] to lambda.", modifyType), refNode);
  12215. }
  12216. else
  12217. {
  12218. error = mModule->Fail(StrFormat("Cannot %s 'this' within struct method '%s'. Consider adding 'mut' specifier to this method.", modifyType,
  12219. mModule->MethodToString(mModule->mCurMethodInstance).c_str()), refNode);
  12220. }
  12221. return false;
  12222. }
  12223. else
  12224. {
  12225. while (checkTypeInst != NULL)
  12226. {
  12227. for (auto& checkFieldInstance : checkTypeInst->mFieldInstances)
  12228. {
  12229. if (checkFieldInstance.mMergedDataIdx == fieldIdx)
  12230. {
  12231. if (isCapturedLocal)
  12232. {
  12233. error = mModule->Fail(StrFormat("Cannot %s read-only captured local variable '%s'. Consider adding by-reference capture specifier [&] to lambda and ensuring that captured value is not read-only.", modifyType,
  12234. checkFieldInstance.GetFieldDef()->mName.c_str()), refNode);
  12235. }
  12236. else if (isClosure)
  12237. {
  12238. if (!mModule->mCurMethodState->mClosureState->mDeclaringMethodIsMutating)
  12239. error = mModule->Fail(StrFormat("Cannot %s field '%s.%s' within struct lambda. Consider adding 'mut' specifier to this method.", modifyType,
  12240. mModule->TypeToString(checkFieldInstance.mOwner).c_str(), checkFieldInstance.GetFieldDef()->mName.c_str()), refNode);
  12241. else
  12242. error = mModule->Fail(StrFormat("Cannot %s field '%s.%s' within struct lambda. Consider adding by-reference capture specifier [&] to lambda.", modifyType,
  12243. mModule->TypeToString(checkFieldInstance.mOwner).c_str(), checkFieldInstance.GetFieldDef()->mName.c_str()), refNode);
  12244. }
  12245. else
  12246. {
  12247. error = mModule->Fail(StrFormat("Cannot %s field '%s.%s' within struct method '%s'. Consider adding 'mut' specifier to this method.", modifyType,
  12248. mModule->TypeToString(checkFieldInstance.mOwner).c_str(), checkFieldInstance.GetFieldDef()->mName.c_str(),
  12249. mModule->MethodToString(mModule->mCurMethodInstance).c_str()), refNode);
  12250. }
  12251. return false;
  12252. }
  12253. }
  12254. checkTypeInst = checkTypeInst->mBaseType;
  12255. }
  12256. }
  12257. }
  12258. else if (localVar->IsParam())
  12259. {
  12260. if (!mModule->mCurMethodInstance->IsMixin())
  12261. {
  12262. if ((localVar->mResolvedType->IsGenericParam()) && (onlyNeedsMut))
  12263. error = mModule->Fail(StrFormat("Cannot %s parameter '%s'. Consider adding 'mut' or 'ref' specifier to parameter or copying to a local variable.", modifyType,
  12264. localVar->mName.c_str(), mModule->MethodToString(mModule->mCurMethodInstance).c_str()), refNode);
  12265. else
  12266. error = mModule->Fail(StrFormat("Cannot %s parameter '%s'. Consider adding 'ref' specifier to parameter or copying to a local variable.", modifyType,
  12267. localVar->mName.c_str(), mModule->MethodToString(mModule->mCurMethodInstance).c_str()), refNode);
  12268. return false;
  12269. }
  12270. }
  12271. else
  12272. {
  12273. error = mModule->Fail(StrFormat("Cannot %s read-only local variable '%s'.", modifyType,
  12274. localVar->mName.c_str()), refNode);
  12275. return false;
  12276. }
  12277. }
  12278. else
  12279. {
  12280. // When we are capturing, we need to note that we require capturing by reference here
  12281. localVar->mWrittenToId = mModule->mCurMethodState->GetRootMethodState()->mCurAccessId++;
  12282. }
  12283. }
  12284. return mModule->CheckModifyValue(typedVal, refNode, modifyType);
  12285. }
  12286. void BfExprEvaluator::Visit(BfConditionalExpression* condExpr)
  12287. {
  12288. static int sCallCount = 0;
  12289. sCallCount++;
  12290. auto condResult = mModule->CreateValueFromExpression(condExpr->mConditionExpression, mModule->GetPrimitiveType(BfTypeCode_Boolean));
  12291. if (!condResult)
  12292. return;
  12293. if (condExpr->mTrueExpression == NULL)
  12294. {
  12295. mModule->AssertErrorState();
  12296. return;
  12297. }
  12298. if (condExpr->mFalseExpression == NULL)
  12299. {
  12300. mModule->CreateValueFromExpression(condExpr->mTrueExpression, mExpectingType, BfEvalExprFlags_NoCast);
  12301. mModule->AssertErrorState();
  12302. return;
  12303. }
  12304. bool isConstBranch = false;
  12305. bool constResult = false;
  12306. bool constResultUndef = false;
  12307. if (condResult.mValue.IsConst())
  12308. {
  12309. auto constValue = mModule->mBfIRBuilder->GetConstant(condResult.mValue);
  12310. if (constValue->mTypeCode == BfTypeCode_Boolean)
  12311. {
  12312. isConstBranch = true;
  12313. constResult = constValue->mBool;
  12314. }
  12315. else if (constValue->mConstType == BfConstType_Undef)
  12316. {
  12317. isConstBranch = true;
  12318. constResultUndef = true;
  12319. }
  12320. }
  12321. if (isConstBranch)
  12322. {
  12323. BfExpression* actualExpr = (constResult) ? condExpr->mTrueExpression : condExpr->mFalseExpression;
  12324. BfExpression* ignoredExpr = (constResult) ? condExpr->mFalseExpression : condExpr->mTrueExpression;
  12325. BfTypedValue actualValue = mModule->CreateValueFromExpression(actualExpr, mExpectingType, BfEvalExprFlags_NoCast);
  12326. BfTypedValue ignoredValue;
  12327. //
  12328. {
  12329. auto curBlock = mModule->mBfIRBuilder->GetInsertBlock();
  12330. SetAndRestoreValue<bool> ignoreWrites(mModule->mBfIRBuilder->mIgnoreWrites, true);
  12331. ignoredValue = mModule->CreateValueFromExpression(ignoredExpr, mExpectingType, BfEvalExprFlags_NoCast);
  12332. mModule->mBfIRBuilder->SetInsertPoint(curBlock);
  12333. }
  12334. if (!actualValue)
  12335. return;
  12336. if ((ignoredValue) && (ignoredValue.mType != actualValue.mType))
  12337. {
  12338. // Cast to more specific 'ignored' type if applicable
  12339. if (mModule->CanImplicitlyCast(actualValue, ignoredValue.mType))
  12340. {
  12341. actualValue = mModule->Cast(actualExpr, actualValue, ignoredValue.mType);
  12342. }
  12343. else if (!mModule->CanImplicitlyCast(ignoredValue, actualValue.mType))
  12344. {
  12345. mModule->Fail(StrFormat("Type of conditional expression cannot be determined because there is no implicit conversion between '%s' and '%s'",
  12346. mModule->TypeToString(actualValue.mType).c_str(), mModule->TypeToString(ignoredValue.mType).c_str()), condExpr);
  12347. }
  12348. }
  12349. mResult = actualValue;
  12350. if (constResultUndef)
  12351. mResult = mModule->GetDefaultTypedValue(mResult.mType, false, BfDefaultValueKind_Undef);
  12352. return;
  12353. }
  12354. auto trueBB = mModule->mBfIRBuilder->CreateBlock("cond.then");
  12355. auto falseBB = mModule->mBfIRBuilder->CreateBlock("cond.else");
  12356. auto endBB = mModule->mBfIRBuilder->CreateBlock("cond.end");
  12357. auto contBB = mModule->mBfIRBuilder->CreateBlock("cond.cont");
  12358. mModule->mBfIRBuilder->CreateCondBr(condResult.mValue, trueBB, falseBB);
  12359. mModule->AddBasicBlock(trueBB);
  12360. auto trueValue = mModule->CreateValueFromExpression(condExpr->mTrueExpression, mExpectingType, (BfEvalExprFlags)(BfEvalExprFlags_NoCast | BfEvalExprFlags_CreateConditionalScope));
  12361. if ((mExpectingType != NULL) && (trueValue) && (trueValue.mType != mExpectingType))
  12362. {
  12363. // In some cases like typed primitives - we CAN individually cast each value which it's a constant still, but not after the merging
  12364. // IE: Color c = isOver ? 0xFF000000 : 0xFFFFFFFF;
  12365. // Otherwise the resulting value would just be 'int' which cannot implicitly convert to Color, but each of those ints can be
  12366. // a uint32 if converted separately
  12367. auto checkTrueValue = mModule->Cast(condExpr->mTrueExpression, trueValue, mExpectingType, BfCastFlags_SilentFail);
  12368. if (checkTrueValue)
  12369. trueValue = checkTrueValue;
  12370. }
  12371. auto trueBlockPos = mModule->mBfIRBuilder->GetInsertBlock();
  12372. mModule->AddBasicBlock(falseBB);
  12373. auto falseValue = mModule->CreateValueFromExpression(condExpr->mFalseExpression, mExpectingType, (BfEvalExprFlags)(BfEvalExprFlags_NoCast | BfEvalExprFlags_CreateConditionalScope));
  12374. auto falseBlockPos = mModule->mBfIRBuilder->GetInsertBlock();
  12375. if ((mExpectingType != NULL) && (falseValue) && (falseValue.mType != mExpectingType))
  12376. {
  12377. auto checkFalseValue = mModule->Cast(condExpr->mFalseExpression, falseValue, mExpectingType, BfCastFlags_SilentFail);
  12378. if (checkFalseValue)
  12379. falseValue = checkFalseValue;
  12380. }
  12381. bool isValid = trueValue && falseValue;
  12382. if (isValid)
  12383. {
  12384. BfTypedValue falseToTrue;
  12385. {
  12386. SetAndRestoreValue<bool> prevIgnoreError(mModule->mIgnoreErrors, true);
  12387. mModule->mBfIRBuilder->SetInsertPoint(falseBlockPos);
  12388. falseToTrue = mModule->Cast(condExpr->mFalseExpression, falseValue, trueValue.mType);
  12389. }
  12390. if (falseToTrue)
  12391. {
  12392. falseValue = falseToTrue;
  12393. }
  12394. else
  12395. {
  12396. BfTypedValue trueToFalse;
  12397. {
  12398. SetAndRestoreValue<bool> prevIgnoreError(mModule->mIgnoreErrors, true);
  12399. mModule->mBfIRBuilder->SetInsertPoint(trueBlockPos);
  12400. trueToFalse = mModule->Cast(condExpr->mTrueExpression, trueValue, falseValue.mType);
  12401. }
  12402. if (!trueToFalse)
  12403. {
  12404. mModule->Fail(StrFormat("Type of conditional expression cannot be determined because there is no implicit conversion between '%s' and '%s'",
  12405. mModule->TypeToString(trueValue.mType).c_str(), mModule->TypeToString(falseValue.mType).c_str()), condExpr);
  12406. //return;
  12407. isValid = false;
  12408. }
  12409. else
  12410. trueValue = trueToFalse;
  12411. }
  12412. }
  12413. mModule->mBfIRBuilder->SetInsertPoint(trueBlockPos);
  12414. if (isValid)
  12415. trueValue = mModule->LoadValue(trueValue);
  12416. mModule->mBfIRBuilder->CreateBr(endBB);
  12417. mModule->mBfIRBuilder->SetInsertPoint(falseBlockPos);
  12418. if (isValid)
  12419. falseValue = mModule->LoadValue(falseValue);
  12420. mModule->mBfIRBuilder->CreateBr(endBB);
  12421. mModule->AddBasicBlock(endBB, false);
  12422. if (!isValid)
  12423. return;
  12424. mModule->mBfIRBuilder->SetInsertPoint(endBB);
  12425. BfIRValue phi;
  12426. if (!trueValue.mType->IsValuelessType())
  12427. {
  12428. phi = mModule->mBfIRBuilder->CreatePhi(mModule->mBfIRBuilder->MapType(trueValue.mType), 2);
  12429. mModule->mBfIRBuilder->AddPhiIncoming(phi, trueValue.mValue, trueBlockPos);
  12430. mModule->mBfIRBuilder->AddPhiIncoming(phi, falseValue.mValue, falseBlockPos);
  12431. }
  12432. mModule->mBfIRBuilder->CreateBr(contBB);
  12433. mModule->AddBasicBlock(contBB);
  12434. mResult = BfTypedValue(phi, trueValue.mType);
  12435. }
  12436. void BfExprEvaluator::PopulateDeferrredTupleAssignData(BfTupleExpression* tupleExpr, DeferredTupleAssignData& deferredTupleAssignData)
  12437. {
  12438. BfTypeVector fieldTypes;
  12439. Array<String> fieldNames;
  12440. // We need to evaluate each LHS tuple component in a separate BfExprEvaluator because each one
  12441. // could be a property and the 'mPropDef' target info is tied to a single evaluator
  12442. for (int valueIdx = 0; valueIdx < (int)tupleExpr->mValues.size(); valueIdx++)
  12443. {
  12444. DeferredTupleAssignData::Entry entry;
  12445. entry.mExprEvaluator = NULL;
  12446. entry.mInnerTuple = NULL;
  12447. BfExpression* valueExpr = tupleExpr->mValues[valueIdx];
  12448. entry.mExpr = valueExpr;
  12449. BfType* fieldType = NULL;
  12450. BfType* resultType = NULL;
  12451. if (auto innerTupleExpr = BfNodeDynCast<BfTupleExpression>(valueExpr))
  12452. {
  12453. entry.mInnerTuple = new DeferredTupleAssignData();
  12454. PopulateDeferrredTupleAssignData(innerTupleExpr, *entry.mInnerTuple);
  12455. resultType = entry.mInnerTuple->mTupleType;
  12456. }
  12457. else
  12458. {
  12459. BfExprEvaluator* exprEvaluator = new BfExprEvaluator(mModule);
  12460. entry.mExprEvaluator = exprEvaluator;
  12461. if (valueExpr->IsA<BfUninitializedExpression>())
  12462. {
  12463. resultType = mModule->GetPrimitiveType(BfTypeCode_None);
  12464. }
  12465. if (auto varDecl = BfNodeDynCast<BfVariableDeclaration>(valueExpr))
  12466. {
  12467. if ((varDecl->mTypeRef->IsA<BfLetTypeReference>()) || (varDecl->mTypeRef->IsA<BfVarTypeReference>()))
  12468. {
  12469. resultType = mModule->GetPrimitiveType(BfTypeCode_Var);
  12470. }
  12471. else
  12472. {
  12473. resultType = ResolveTypeRef(varDecl->mTypeRef);
  12474. if (resultType == NULL)
  12475. resultType = mModule->GetPrimitiveType(BfTypeCode_Var);
  12476. }
  12477. }
  12478. if (resultType == NULL)
  12479. {
  12480. exprEvaluator->VisitChild(valueExpr);
  12481. if ((!exprEvaluator->mResult) && (exprEvaluator->mPropDef == NULL))
  12482. exprEvaluator->mResult = mModule->GetDefaultTypedValue(mModule->GetPrimitiveType(BfTypeCode_None));
  12483. resultType = exprEvaluator->mResult.mType;
  12484. }
  12485. if ((resultType == NULL) && (exprEvaluator->mPropDef != NULL) && (exprEvaluator->mPropTarget.mType != NULL))
  12486. {
  12487. auto propTypeInst = exprEvaluator->mPropTarget.mType->ToTypeInstance();
  12488. if ((propTypeInst == NULL) && (exprEvaluator->mPropTarget.mType->IsPointer()))
  12489. {
  12490. BfPointerType* pointerType = (BfPointerType*)exprEvaluator->mPropTarget.mType;
  12491. propTypeInst = pointerType->mElementType->ToTypeInstance();
  12492. }
  12493. auto setMethod = GetPropertyMethodDef(exprEvaluator->mPropDef, BfMethodType_PropertySetter, mPropCheckedKind);
  12494. if (setMethod != NULL)
  12495. {
  12496. auto methodInstance = mModule->GetMethodInstance(propTypeInst, setMethod, BfTypeVector());
  12497. resultType = methodInstance.mMethodInstance->GetParamType(0);
  12498. }
  12499. else
  12500. {
  12501. auto getMethod = GetPropertyMethodDef(exprEvaluator->mPropDef, BfMethodType_PropertyGetter, mPropCheckedKind);
  12502. if (getMethod != NULL)
  12503. {
  12504. auto methodInstance = mModule->GetMethodInstance(propTypeInst, getMethod, BfTypeVector());
  12505. auto retType = methodInstance.mMethodInstance->mReturnType;
  12506. if (retType->IsRef())
  12507. resultType = retType->GetUnderlyingType();
  12508. }
  12509. }
  12510. }
  12511. }
  12512. if (resultType == NULL)
  12513. resultType = mModule->GetPrimitiveType(BfTypeCode_None);
  12514. deferredTupleAssignData.mChildren.push_back(entry);
  12515. fieldTypes.push_back(resultType);
  12516. }
  12517. for (BfTupleNameNode* requestedName : tupleExpr->mNames)
  12518. {
  12519. if (requestedName == NULL)
  12520. fieldNames.push_back("");
  12521. else
  12522. fieldNames.push_back(requestedName->mNameNode->ToString());
  12523. }
  12524. BfTupleType* tupleType = mModule->CreateTupleType(fieldTypes, fieldNames);
  12525. deferredTupleAssignData.mTupleType = tupleType;
  12526. }
  12527. void BfExprEvaluator::AssignDeferrredTupleAssignData(BfAssignmentExpression* assignExpr, DeferredTupleAssignData& deferredTupleAssignData, BfTypedValue rightValue)
  12528. {
  12529. BF_ASSERT(rightValue.mType->IsTuple());
  12530. auto tupleType = (BfTupleType*)rightValue.mType;
  12531. for (int valueIdx = 0; valueIdx < (int)deferredTupleAssignData.mChildren.size(); valueIdx++)
  12532. {
  12533. auto& child = deferredTupleAssignData.mChildren[valueIdx];
  12534. BfFieldInstance* fieldInstance = &tupleType->mFieldInstances[valueIdx];
  12535. BfTypedValue elementValue;
  12536. if (fieldInstance->mDataIdx >= 0)
  12537. {
  12538. auto extractedValue = mModule->mBfIRBuilder->CreateExtractValue(rightValue.mValue, fieldInstance->mDataIdx);
  12539. elementValue = BfTypedValue(extractedValue, fieldInstance->GetResolvedType());
  12540. if (child.mInnerTuple != NULL)
  12541. {
  12542. AssignDeferrredTupleAssignData(assignExpr, *child.mInnerTuple, elementValue);
  12543. delete child.mInnerTuple;
  12544. }
  12545. else
  12546. {
  12547. child.mExprEvaluator->PerformAssignment(assignExpr, true, elementValue);
  12548. }
  12549. }
  12550. if (auto varDecl = BfNodeDynCast<BfVariableDeclaration>(child.mExpr))
  12551. {
  12552. if (!elementValue)
  12553. elementValue = mModule->GetDefaultTypedValue(fieldInstance->GetResolvedType());
  12554. mModule->HandleVariableDeclaration(varDecl, elementValue);
  12555. }
  12556. }
  12557. }
  12558. void BfExprEvaluator::DoTupleAssignment(BfAssignmentExpression* assignExpr)
  12559. {
  12560. auto tupleExpr = BfNodeDynCast<BfTupleExpression>(assignExpr->mLeft);
  12561. DeferredTupleAssignData deferredTupleAssignData;
  12562. PopulateDeferrredTupleAssignData(tupleExpr, deferredTupleAssignData);
  12563. BfTupleType* tupleType = deferredTupleAssignData.mTupleType;
  12564. BfTypedValue rightValue;
  12565. if (assignExpr->mRight != NULL)
  12566. {
  12567. rightValue = mModule->CreateValueFromExpression(assignExpr->mRight, tupleType);
  12568. }
  12569. if (!rightValue)
  12570. {
  12571. tupleType = mModule->SantizeTupleType(tupleType);
  12572. rightValue = mModule->GetDefaultTypedValue(tupleType);
  12573. }
  12574. rightValue = mModule->LoadValue(rightValue);
  12575. AssignDeferrredTupleAssignData(assignExpr, deferredTupleAssignData, rightValue);
  12576. mResult = rightValue;
  12577. }
  12578. void BfExprEvaluator::PerformAssignment(BfAssignmentExpression* assignExpr, bool evaluatedLeft, BfTypedValue rightValue, BfTypedValue* outCascadeValue)
  12579. {
  12580. auto binaryOp = BfAssignOpToBinaryOp(assignExpr->mOp);
  12581. BfExpression* targetNode = assignExpr->mLeft;
  12582. if ((BfNodeIsA<BfMixinExpression>(targetNode)) && (!mModule->mCurMethodInstance->mIsUnspecialized))
  12583. {
  12584. // If we have a "mixin = <X>" but there's no mixin target then ignore the assignment
  12585. int mixinVar = GetMixinVariable();
  12586. if (mixinVar == -1)
  12587. {
  12588. mResult = mModule->GetDefaultTypedValue(mModule->GetPrimitiveType(BfTypeCode_None));
  12589. return;
  12590. }
  12591. }
  12592. BfAutoComplete* autoComplete = GetAutoComplete();
  12593. bool deferredFixits = false;
  12594. if ((autoComplete != NULL) && (autoComplete->mResolveType == BfResolveType_GetFixits))
  12595. {
  12596. SetAndRestoreValue<bool> ignoreFixits(autoComplete->mIgnoreFixits, true);
  12597. VisitChild(targetNode);
  12598. deferredFixits = true;
  12599. }
  12600. else if (!evaluatedLeft)
  12601. {
  12602. if (auto memberReferenceExpr = BfNodeDynCast<BfMemberReferenceExpression>(targetNode))
  12603. {
  12604. DoMemberReference(memberReferenceExpr, outCascadeValue);
  12605. }
  12606. else
  12607. VisitChild(targetNode);
  12608. }
  12609. if ((!mResult) && (mPropDef == NULL))
  12610. {
  12611. if (assignExpr->mRight != NULL)
  12612. {
  12613. auto result = mModule->CreateValueFromExpression(assignExpr->mRight);
  12614. if (deferredFixits)
  12615. {
  12616. SetAndRestoreValue<bool> ignoreErrors(mModule->mIgnoreErrors, true);
  12617. mExpectingType = result.mType;
  12618. VisitChild(targetNode);
  12619. mResult = BfTypedValue();
  12620. }
  12621. }
  12622. return;
  12623. }
  12624. ResolveGenericType();
  12625. auto ptr = mResult;
  12626. mResult = BfTypedValue();
  12627. if (mPropDef == NULL)
  12628. {
  12629. if (!CheckModifyResult(ptr, assignExpr->mOpToken, "assign to"))
  12630. {
  12631. if (assignExpr->mRight != NULL)
  12632. mModule->CreateValueFromExpression(assignExpr->mRight, ptr.mType, BfEvalExprFlags_NoCast);
  12633. return;
  12634. }
  12635. }
  12636. if (mPropDef != NULL)
  12637. {
  12638. bool hasLeftVal = false;
  12639. auto propDef = mPropDef;
  12640. auto propTarget = mPropTarget;
  12641. auto setMethod = GetPropertyMethodDef(mPropDef, BfMethodType_PropertySetter, mPropCheckedKind);
  12642. if (setMethod == NULL)
  12643. {
  12644. // Allow for a ref return on the getter to be used if a setter is not available
  12645. GetResult();
  12646. if ((mResult) && (mResult.mKind == BfTypedValueKind_Addr))
  12647. {
  12648. ptr = mResult;
  12649. mResult = BfTypedValue();
  12650. hasLeftVal = true;
  12651. }
  12652. else
  12653. {
  12654. mModule->Fail("Property has no setter", mPropSrc);
  12655. if (assignExpr->mRight != NULL)
  12656. mModule->CreateValueFromExpression(assignExpr->mRight, ptr.mType, BfEvalExprFlags_NoCast);
  12657. return;
  12658. }
  12659. }
  12660. if (!hasLeftVal)
  12661. {
  12662. auto methodInstance = GetPropertyMethodInstance(setMethod);
  12663. if (methodInstance.mMethodInstance == NULL)
  12664. return;
  12665. BF_ASSERT(methodInstance.mMethodInstance->mMethodDef == setMethod);
  12666. CheckPropFail(setMethod, methodInstance.mMethodInstance);
  12667. BfTypedValue convVal;
  12668. if (binaryOp != BfBinaryOp_None)
  12669. {
  12670. PerformBinaryOperation(assignExpr->mLeft, assignExpr->mRight, binaryOp, assignExpr->mOpToken, BfBinOpFlag_ForceLeftType);
  12671. if (!mResult)
  12672. return;
  12673. convVal = mResult;
  12674. mResult = BfTypedValue();
  12675. if (!convVal)
  12676. return;
  12677. }
  12678. else
  12679. {
  12680. auto wantType = methodInstance.mMethodInstance->GetParamType(methodInstance.mMethodInstance->GetParamCount() - 1);
  12681. if (rightValue)
  12682. {
  12683. convVal = mModule->Cast(assignExpr->mRight, rightValue, wantType);
  12684. }
  12685. else
  12686. {
  12687. if (assignExpr->mRight == NULL)
  12688. {
  12689. mModule->AssertErrorState();
  12690. return;
  12691. }
  12692. convVal = mModule->CreateValueFromExpression(assignExpr->mRight, wantType, (BfEvalExprFlags)(BfEvalExprFlags_AllowSplat | BfEvalExprFlags_PendingPropSet));
  12693. }
  12694. if (!convVal)
  12695. {
  12696. mPropDef = NULL;
  12697. return;
  12698. }
  12699. }
  12700. if (mPropSrc != NULL)
  12701. mModule->UpdateExprSrcPos(mPropSrc);
  12702. SizedArray<BfIRValue, 4> args;
  12703. if (!setMethod->mIsStatic)
  12704. {
  12705. mModule->EmitObjectAccessCheck(mPropTarget);
  12706. PushThis(mPropSrc, mPropTarget, methodInstance.mMethodInstance, args);
  12707. }
  12708. for (int paramIdx = 0; paramIdx < (int)mIndexerValues.size(); paramIdx++)
  12709. {
  12710. auto val = mModule->Cast(mPropSrc, mIndexerValues[paramIdx].mTypedValue, methodInstance.mMethodInstance->GetParamType(paramIdx));
  12711. if (!val)
  12712. {
  12713. mPropDef = NULL;
  12714. return;
  12715. }
  12716. PushArg(val, args);
  12717. }
  12718. PushArg(convVal, args);
  12719. if (methodInstance)
  12720. CreateCall(methodInstance.mMethodInstance, methodInstance.mFunc, mPropDefBypassVirtual, args);
  12721. mPropDef = NULL;
  12722. mResult = convVal;
  12723. return;
  12724. }
  12725. }
  12726. auto toType = ptr.mType;
  12727. if (toType->IsRef())
  12728. {
  12729. auto refType = (BfRefType*)toType;
  12730. toType = refType->mElementType;
  12731. }
  12732. if ((autoComplete != NULL) && (assignExpr->mOpToken != NULL) && (toType != NULL))
  12733. autoComplete->CheckEmptyStart(assignExpr->mOpToken, toType);
  12734. BfExpression* rightExpr = assignExpr->mRight;
  12735. if (rightExpr == NULL)
  12736. {
  12737. mModule->AssertErrorState();
  12738. return;
  12739. }
  12740. bool alreadyWritten = false;
  12741. BfTypedValue convVal;
  12742. if (binaryOp != BfBinaryOp_None)
  12743. {
  12744. auto expectedType = ptr.mType;
  12745. if ((binaryOp == BfBinaryOp_LeftShift) || (binaryOp == BfBinaryOp_RightShift))
  12746. expectedType = mModule->GetPrimitiveType(BfTypeCode_IntPtr);
  12747. if ((!rightValue) && (assignExpr->mRight != NULL))
  12748. {
  12749. rightValue = mModule->CreateValueFromExpression(assignExpr->mRight, expectedType, (BfEvalExprFlags)(BfEvalExprFlags_AllowSplat | BfEvalExprFlags_NoCast));
  12750. }
  12751. CheckResultForReading(ptr);
  12752. BfTypedValue leftValue = ptr;
  12753. leftValue = mModule->LoadValue(leftValue);
  12754. if (rightValue)
  12755. PerformBinaryOperation(assignExpr->mLeft, assignExpr->mRight, binaryOp, assignExpr->mOpToken, BfBinOpFlag_ForceLeftType, leftValue, rightValue);
  12756. convVal = mResult;
  12757. mResult = BfTypedValue();
  12758. if (!convVal)
  12759. return;
  12760. }
  12761. else
  12762. {
  12763. convVal = rightValue;
  12764. if (!convVal)
  12765. {
  12766. if (auto uninitExpr = BfNodeDynCast<BfUninitializedExpression>(rightExpr))
  12767. {
  12768. if (mResultLocalVar != NULL)
  12769. {
  12770. MarkResultAssigned();
  12771. return;
  12772. }
  12773. }
  12774. // In the cases like "structVal = GetVal()", the allowDirectStructRetWrite optimization allows us to pass the
  12775. // address of structVal into the sret. We only allow that if structVal is a local, because if it's globally
  12776. // visible then we could see the results of a partially-modified structVal
  12777. //bool allowDirectStructRetWrite = mResultLocalVarIdx != -1;
  12778. // ALTHOUGH- we can only allow this optimization if we can be sure the local value is not aliased- we could
  12779. // have the backend ensure that this local value never gets its address taken.
  12780. bool allowDirectStructWrite = false;
  12781. BfExprEvaluator exprEvaluator(mModule);
  12782. exprEvaluator.mExpectingType = toType;
  12783. if (allowDirectStructWrite)
  12784. exprEvaluator.mReceivingValue = &ptr;
  12785. exprEvaluator.Evaluate(rightExpr, false, false, true);
  12786. exprEvaluator.CheckResultForReading(exprEvaluator.mResult);
  12787. convVal = exprEvaluator.GetResult();
  12788. mModule->FixIntUnknown(convVal);
  12789. alreadyWritten = (allowDirectStructWrite) && (exprEvaluator.mReceivingValue == NULL);
  12790. if (!convVal)
  12791. convVal = mModule->GetDefaultTypedValue(toType);
  12792. // Did we use mReceivingValue as a mixin result?
  12793. if ((convVal.mValue) && (convVal.mValue == ptr.mValue))
  12794. {
  12795. mResult = convVal;
  12796. return;
  12797. }
  12798. }
  12799. }
  12800. BF_ASSERT(convVal);
  12801. if ((convVal) && (convVal.mType->IsNull()) && (ptr.mType->IsNullable()))
  12802. {
  12803. // Allow this to pass through so we can catch it in the memset later in this function
  12804. }
  12805. else
  12806. {
  12807. if (!convVal.mType->IsComposite())
  12808. convVal = mModule->LoadValue(convVal);
  12809. convVal = mModule->Cast(rightExpr, convVal, toType);
  12810. if (!convVal)
  12811. return;
  12812. convVal = mModule->LoadValue(convVal);
  12813. }
  12814. if (ptr.mType->IsVar())
  12815. {
  12816. mResult = ptr;
  12817. return;
  12818. }
  12819. if (convVal.mValue)
  12820. {
  12821. if ((ptr.mType->IsStruct()) && (!ptr.mType->IsValuelessType()) && (convVal.mValue.IsConst()))
  12822. {
  12823. auto constant = mModule->mBfIRBuilder->GetConstant(convVal.mValue);
  12824. if ((constant->mTypeCode == BfTypeCode_NullPtr) || (constant->mConstType == BfConstType_AggZero))
  12825. {
  12826. auto type = ptr.mType;
  12827. mModule->mBfIRBuilder->CreateMemSet(ptr.mValue, mModule->GetConstValue(0, mModule->GetPrimitiveType(BfTypeCode_Int8)),
  12828. mModule->GetConstValue(type->mSize), type->mAlign);
  12829. mResult = ptr;
  12830. MarkResultAssigned();
  12831. return;
  12832. }
  12833. }
  12834. // if (ptr.mType->IsMethodRef())
  12835. // {
  12836. // auto methodRefType = (BfMethodRefType*)ptr.mType;
  12837. // auto methodInstance = methodRefType->mMethodInstance;
  12838. // int implicitParamCount = methodInstance->GetImplicitParamCount();
  12839. // for (int implicitParamIdx = methodInstance->HasThis() ? - 1 : 0; implicitParamIdx < implicitParamCount; implicitParamIdx++)
  12840. // {
  12841. // bool failed = false;
  12842. // auto destPtr = DoImplicitArgCapture(assignExpr, methodRefType->mMethodInstance, implicitParamIdx, failed, BfImplicitParamKind_GenericTypeMember_Addr);
  12843. // auto srcVal = DoImplicitArgCapture(assignExpr, methodRefType->mMethodInstance, implicitParamIdx, failed, BfImplicitParamKind_GenericMethodMember);
  12844. // if ((destPtr) && (srcVal))
  12845. // {
  12846. // srcVal = mModule->AggregateSplat(srcVal);
  12847. // mModule->mBfIRBuilder->CreateStore(srcVal.mValue, destPtr.mValue);
  12848. // }
  12849. // }
  12850. // }
  12851. // else
  12852. {
  12853. mModule->mBfIRBuilder->PopulateType(ptr.mType);
  12854. if (convVal.IsSplat())
  12855. {
  12856. //convVal = mModule->AggregateSplat(convVal);
  12857. mModule->AggregateSplatIntoAddr(convVal, ptr.mValue);
  12858. }
  12859. else
  12860. {
  12861. if (ptr.mType->IsValuelessType())
  12862. {
  12863. mModule->EmitEnsureInstructionAt();
  12864. }
  12865. else if (!alreadyWritten)
  12866. {
  12867. //ptr = mModule->LoadValue(ptr);
  12868. BF_ASSERT(ptr.IsAddr());
  12869. convVal = mModule->LoadValue(convVal);
  12870. auto storeInst = mModule->mBfIRBuilder->CreateAlignedStore(convVal.mValue, ptr.mValue, ptr.mType->mAlign, mIsVolatileReference);
  12871. }
  12872. }
  12873. }
  12874. }
  12875. else
  12876. {
  12877. BF_ASSERT(convVal.mType->IsValuelessType());
  12878. }
  12879. mResult = convVal;
  12880. MarkResultAssigned();
  12881. }
  12882. void BfExprEvaluator::Visit(BfAssignmentExpression* assignExpr)
  12883. {
  12884. if (assignExpr->mLeft->IsA<BfTupleExpression>())
  12885. {
  12886. DoTupleAssignment(assignExpr);
  12887. return;
  12888. }
  12889. BfAutoParentNodeEntry autoParentNodeEntry(mModule, assignExpr);
  12890. BfTypedValue cascadeValue;
  12891. PerformAssignment(assignExpr, false, BfTypedValue(), &cascadeValue);
  12892. if (cascadeValue)
  12893. mResult = cascadeValue;
  12894. }
  12895. void BfExprEvaluator::Visit(BfParenthesizedExpression* parenExpr)
  12896. {
  12897. VisitChild(parenExpr->mExpression);
  12898. MakeResultAsValue();
  12899. }
  12900. void BfExprEvaluator::InitializedSizedArray(BfSizedArrayType* arrayType, BfTokenNode* openToken, const BfSizedArray<BfExpression*>& valueExprs, const BfSizedArray<BfTokenNode*>& commas, BfTokenNode* closeToken, BfTypedValue* receivingValue)
  12901. {
  12902. struct InitValue
  12903. {
  12904. BfTypedValue mValue;
  12905. bool mIsUninitialized;
  12906. bool mIsDefaultInitializer;
  12907. bool mIsDeferred;
  12908. InitValue()
  12909. {
  12910. mIsUninitialized = false;
  12911. mIsDefaultInitializer = false;
  12912. mIsDeferred = false;
  12913. }
  12914. };
  12915. SizedArray<InitValue, 8> values;
  12916. {
  12917. //bool hasFailed = false;
  12918. HashSet<int> failedAt;
  12919. bool isAllConst = true;
  12920. //bool endUninitialzied = false;
  12921. int depth = 0;
  12922. std::function<void(BfSizedArrayType*, BfTokenNode* openToken, const BfSizedArray<BfExpression*>&, const BfSizedArray<BfTokenNode*>&, BfTokenNode*, bool)>
  12923. _GetValues = [&](BfSizedArrayType* checkArrayType, BfTokenNode* openToken, const BfSizedArray<BfExpression*>& valueExprs, const BfSizedArray<BfTokenNode*>& commas, BfTokenNode* closeToken, bool ignore)
  12924. {
  12925. int64 initCountDiff = (int)valueExprs.size() - checkArrayType->mElementCount;
  12926. if ((initCountDiff != 0) && (!failedAt.Contains(depth)))
  12927. {
  12928. if (initCountDiff > 0)
  12929. {
  12930. mModule->Fail(StrFormat("Too many initializers, expected %d fewer", initCountDiff), valueExprs[(int)checkArrayType->mElementCount]);
  12931. failedAt.Add(depth);
  12932. }
  12933. else
  12934. {
  12935. // If it ends with ", ?) or ",)" then allow unsized
  12936. if (((valueExprs.size() == 0) || (BfNodeDynCast<BfUninitializedExpression>(valueExprs.back()) == NULL)) &&
  12937. ((commas.size() < valueExprs.size()) || (valueExprs.size() == 0)))
  12938. {
  12939. BfAstNode* refNode = closeToken;
  12940. if ((refNode == NULL) && (mModule->mParentNodeEntry != NULL))
  12941. refNode = mModule->mParentNodeEntry->mNode;
  12942. BF_ASSERT(refNode != NULL);
  12943. mModule->Fail(StrFormat("Too few initializer, expected %d more", -initCountDiff), refNode);
  12944. failedAt.Add(depth);
  12945. }
  12946. }
  12947. }
  12948. for (int idx = 0; idx < BF_MAX(checkArrayType->mElementCount, valueExprs.size()); idx++)
  12949. {
  12950. BfTypedValue elementValue;
  12951. bool deferredValue = false;
  12952. BfExpression* expr = NULL;
  12953. if (idx < (int)valueExprs.size())
  12954. {
  12955. expr = valueExprs[idx];
  12956. if (expr == NULL)
  12957. {
  12958. if (idx == 0)
  12959. mModule->FailAfter("Expression expected", openToken);
  12960. else
  12961. mModule->FailAfter("Expression expected", commas[idx - 1]);
  12962. }
  12963. if ((BfNodeDynCastExact<BfUninitializedExpression>(expr) != NULL) && (idx == (int)commas.size()))
  12964. {
  12965. isAllConst = false;
  12966. break;
  12967. }
  12968. if (checkArrayType->mElementType->IsSizedArray())
  12969. {
  12970. if (auto arrayInitExpr = BfNodeDynCast<BfTupleExpression>(expr))
  12971. {
  12972. depth++;
  12973. _GetValues((BfSizedArrayType*)checkArrayType->mElementType, arrayInitExpr->mOpenParen, arrayInitExpr->mValues, arrayInitExpr->mCommas, arrayInitExpr->mCloseParen, ignore);
  12974. depth--;
  12975. continue;
  12976. }
  12977. else if (auto arrayInitExpr = BfNodeDynCast<BfCollectionInitializerExpression>(expr))
  12978. {
  12979. depth++;
  12980. _GetValues((BfSizedArrayType*)checkArrayType->mElementType, arrayInitExpr->mOpenBrace, arrayInitExpr->mValues, arrayInitExpr->mCommas, arrayInitExpr->mCloseBrace, ignore);
  12981. depth--;
  12982. continue;
  12983. }
  12984. else if (auto parenExpr = BfNodeDynCast<BfParenthesizedExpression>(expr))
  12985. {
  12986. depth++;
  12987. SizedArray<BfExpression*, 1> values;
  12988. values.Add(parenExpr->mExpression);
  12989. SizedArray<BfTokenNode*, 1> commas;
  12990. _GetValues((BfSizedArrayType*)checkArrayType->mElementType, parenExpr->mOpenParen, values, commas, parenExpr->mCloseParen, ignore);
  12991. depth--;
  12992. continue;
  12993. }
  12994. }
  12995. if (expr != NULL)
  12996. {
  12997. bool tryDefer = false;
  12998. if ((checkArrayType->IsComposite()) &&
  12999. ((expr->IsA<BfInvocationExpression>()) || (expr->IsExact<BfTupleExpression>())))
  13000. {
  13001. tryDefer = true;
  13002. }
  13003. SetAndRestoreValue<bool> prevIgnoreWrites(mModule->mBfIRBuilder->mIgnoreWrites, mModule->mBfIRBuilder->mIgnoreWrites || tryDefer);
  13004. elementValue = mModule->CreateValueFromExpression(expr, checkArrayType->mElementType);
  13005. if (!elementValue)
  13006. elementValue = mModule->GetDefaultTypedValue(checkArrayType->mElementType);
  13007. deferredValue = !prevIgnoreWrites.mPrevVal && elementValue.mValue.IsFake();
  13008. if ((!elementValue) || (!CheckAllowValue(elementValue, expr)))
  13009. elementValue = mModule->GetDefaultTypedValue(checkArrayType->mElementType);
  13010. // For now, we can't properly create const-valued non-size-aligned composites
  13011. if (checkArrayType->mElementType->NeedsExplicitAlignment())
  13012. isAllConst = false;
  13013. if (!elementValue.mValue.IsConst())
  13014. isAllConst = false;
  13015. InitValue initValue;
  13016. initValue.mValue = elementValue;
  13017. initValue.mIsDeferred = deferredValue;
  13018. values.push_back(initValue);
  13019. }
  13020. }
  13021. }
  13022. };
  13023. int valueIdx = 0;
  13024. std::function<void(BfTypedValue, BfTokenNode* openToken, const BfSizedArray<BfExpression*>&, const BfSizedArray<BfTokenNode*>&, BfTokenNode*)>
  13025. _CreateMemArray = [&](BfTypedValue arrayValue, BfTokenNode* openToken, const BfSizedArray<BfExpression*>& valueExprs, const BfSizedArray<BfTokenNode*>& commas, BfTokenNode* closeToken)
  13026. {
  13027. BF_ASSERT(arrayValue.mType->IsSizedArray());
  13028. auto checkArrayType = (BfSizedArrayType*)arrayValue.mType;
  13029. int valIdx = 0;
  13030. bool hasUninit = false;
  13031. for (int idx = 0; idx < checkArrayType->mElementCount; idx++)
  13032. {
  13033. BfExpression* expr = NULL;
  13034. BfTypedValue elementValue;
  13035. if (idx >= (int)valueExprs.size())
  13036. break;
  13037. expr = valueExprs[idx];
  13038. if ((BfNodeDynCastExact<BfUninitializedExpression>(expr) != NULL) && (idx == (int)commas.size()))
  13039. {
  13040. hasUninit = true;
  13041. break;
  13042. }
  13043. BfIRValue elemPtrValue = mModule->CreateIndexedValue(checkArrayType->mElementType, arrayValue.mValue, valIdx, true);
  13044. valIdx++;
  13045. if (checkArrayType->mElementType->IsSizedArray())
  13046. {
  13047. if (auto arrayInitExpr = BfNodeDynCast<BfTupleExpression>(expr))
  13048. {
  13049. _CreateMemArray(BfTypedValue(elemPtrValue, checkArrayType->mElementType, true), arrayInitExpr->mOpenParen, arrayInitExpr->mValues, arrayInitExpr->mCommas, arrayInitExpr->mCloseParen);
  13050. continue;
  13051. }
  13052. else if (auto arrayInitExpr = BfNodeDynCast<BfCollectionInitializerExpression>(expr))
  13053. {
  13054. _CreateMemArray(BfTypedValue(elemPtrValue, checkArrayType->mElementType, true), arrayInitExpr->mOpenBrace, arrayInitExpr->mValues, arrayInitExpr->mCommas, arrayInitExpr->mCloseBrace);
  13055. continue;
  13056. }
  13057. else if (auto parenExpr = BfNodeDynCast<BfParenthesizedExpression>(expr))
  13058. {
  13059. depth++;
  13060. SizedArray<BfExpression*, 1> values;
  13061. values.Add(parenExpr->mExpression);
  13062. SizedArray<BfTokenNode*, 1> commas;
  13063. _CreateMemArray(BfTypedValue(elemPtrValue, checkArrayType->mElementType, true), parenExpr->mOpenParen, values, commas, parenExpr->mCloseParen);
  13064. depth--;
  13065. continue;
  13066. }
  13067. }
  13068. if (expr != NULL)
  13069. {
  13070. InitValue initValue = values[valueIdx++];
  13071. elementValue = initValue.mValue;
  13072. if (initValue.mIsDeferred)
  13073. {
  13074. BfTypedValue elemePtrTypedVal = BfTypedValue(elemPtrValue, checkArrayType->mElementType, BfTypedValueKind_Addr);
  13075. BfExprEvaluator exprEvaluator(mModule);
  13076. exprEvaluator.mExpectingType = checkArrayType->mElementType;
  13077. exprEvaluator.mReceivingValue = &elemePtrTypedVal;
  13078. exprEvaluator.Evaluate(expr);
  13079. exprEvaluator.GetResult();
  13080. if (exprEvaluator.mReceivingValue == NULL)
  13081. {
  13082. // We wrote directly to the array in-place, we're done with this element
  13083. continue;
  13084. }
  13085. elementValue = exprEvaluator.mResult;
  13086. elementValue = mModule->Cast(expr, elementValue, checkArrayType->mElementType);
  13087. if (!elementValue)
  13088. {
  13089. mModule->AssertErrorState();
  13090. continue;
  13091. }
  13092. }
  13093. elementValue = mModule->LoadValue(elementValue);
  13094. mModule->mBfIRBuilder->CreateAlignedStore(elementValue.mValue, elemPtrValue, checkArrayType->mElementType->mAlign);
  13095. }
  13096. }
  13097. int fillCount = (int)(checkArrayType->mElementCount - valIdx);
  13098. if (fillCount > 0)
  13099. {
  13100. BfIRValue elemPtrValue = mModule->CreateIndexedValue(checkArrayType->mElementType, arrayValue.mValue, valIdx, true);
  13101. if (hasUninit)
  13102. {
  13103. if (!mModule->IsOptimized())
  13104. {
  13105. int setSize = std::min(checkArrayType->mElementType->mSize, 128); // Keep it to a reasonable number of bytes to trash
  13106. mModule->mBfIRBuilder->CreateMemSet(elemPtrValue, mModule->mBfIRBuilder->CreateConst(BfTypeCode_Int8, 0xCC),
  13107. mModule->GetConstValue(setSize), checkArrayType->mElementType->mAlign);
  13108. }
  13109. }
  13110. else
  13111. {
  13112. int setSize = (int)((checkArrayType->mElementType->GetStride() * (fillCount - 1)) + checkArrayType->mElementType->mSize);
  13113. if (setSize >= 0)
  13114. {
  13115. mModule->mBfIRBuilder->CreateMemSet(elemPtrValue, mModule->mBfIRBuilder->CreateConst(BfTypeCode_Int8, 0),
  13116. mModule->GetConstValue(setSize), checkArrayType->mElementType->mAlign);
  13117. }
  13118. }
  13119. }
  13120. };
  13121. std::function<BfIRValue(BfTypedValue, BfTokenNode*, const BfSizedArray<BfExpression*>&, const BfSizedArray<BfTokenNode*>&, BfTokenNode*)>
  13122. _CreateConstArray = [&](BfTypedValue arrayValue, BfTokenNode* openToken, const BfSizedArray<BfExpression*>& valueExprs, const BfSizedArray<BfTokenNode*>& commas, BfTokenNode* closeToken)
  13123. {
  13124. SizedArray<BfIRValue, 8> members;
  13125. BF_ASSERT(arrayValue.mType->IsSizedArray());
  13126. auto checkArrayType = (BfSizedArrayType*)arrayValue.mType;
  13127. int valIdx = 0;
  13128. for (int idx = 0; idx < checkArrayType->mElementCount; idx++)
  13129. {
  13130. BfTypedValue elementValue;
  13131. if (idx >= (int)valueExprs.size())
  13132. break;
  13133. auto expr = valueExprs[idx];
  13134. if (expr == NULL)
  13135. continue;
  13136. valIdx++;
  13137. if (checkArrayType->mElementType->IsSizedArray())
  13138. {
  13139. if (auto arrayInitExpr = BfNodeDynCast<BfTupleExpression>(expr))
  13140. {
  13141. members.push_back(_CreateConstArray(checkArrayType->mElementType, arrayInitExpr->mOpenParen, arrayInitExpr->mValues, arrayInitExpr->mCommas, arrayInitExpr->mCloseParen));
  13142. continue;
  13143. }
  13144. else if (auto arrayInitExpr = BfNodeDynCast<BfCollectionInitializerExpression>(expr))
  13145. {
  13146. members.push_back(_CreateConstArray(checkArrayType->mElementType, arrayInitExpr->mOpenBrace, arrayInitExpr->mValues, arrayInitExpr->mCommas, arrayInitExpr->mCloseBrace));
  13147. continue;
  13148. }
  13149. else if (auto parenExpr = BfNodeDynCast<BfParenthesizedExpression>(expr))
  13150. {
  13151. depth++;
  13152. SizedArray<BfExpression*, 1> values;
  13153. values.Add(parenExpr->mExpression);
  13154. SizedArray<BfTokenNode*, 1> commas;
  13155. members.push_back(_CreateConstArray(checkArrayType->mElementType, parenExpr->mOpenParen, values, commas, parenExpr->mCloseParen));
  13156. depth--;
  13157. continue;
  13158. }
  13159. }
  13160. InitValue initValue = values[valueIdx++];
  13161. BF_ASSERT(!initValue.mIsUninitialized);
  13162. elementValue = initValue.mValue;
  13163. members.push_back(elementValue.mValue);
  13164. }
  13165. int fillCount = (int)(checkArrayType->mElementCount - valIdx);
  13166. if (fillCount > 0)
  13167. {
  13168. // We just need to insert one default value, it will be duplicated as needed into the backend
  13169. auto defaultVal = mModule->GetDefaultTypedValue(checkArrayType->GetUnderlyingType());
  13170. BF_ASSERT(defaultVal.mValue.IsConst());
  13171. members.push_back(defaultVal.mValue);
  13172. }
  13173. return mModule->mBfIRBuilder->CreateConstArray(mModule->mBfIRBuilder->MapType(checkArrayType), members);
  13174. };
  13175. _GetValues(arrayType, openToken, valueExprs, commas, closeToken, false);
  13176. if (!failedAt.IsEmpty())
  13177. {
  13178. mResult = mModule->GetDefaultTypedValue(arrayType, false, BfDefaultValueKind_Addr);
  13179. return;
  13180. }
  13181. if (receivingValue != NULL)
  13182. {
  13183. BF_ASSERT(receivingValue->mType == arrayType);
  13184. BF_ASSERT(receivingValue->IsAddr());
  13185. mResult = *receivingValue;
  13186. _CreateMemArray(mResult, openToken, valueExprs, commas, closeToken);
  13187. }
  13188. else if (isAllConst)
  13189. {
  13190. mResult = BfTypedValue(_CreateConstArray(arrayType, openToken, valueExprs, commas, closeToken), arrayType, BfTypedValueKind_Value);
  13191. }
  13192. else
  13193. {
  13194. if ((mReceivingValue != NULL) && (mReceivingValue->mType == arrayType) && (mReceivingValue->IsAddr()))
  13195. {
  13196. mResult = *mReceivingValue;
  13197. mReceivingValue = NULL;
  13198. }
  13199. else
  13200. {
  13201. auto arrayValue = mModule->CreateAlloca(arrayType);
  13202. mResult = BfTypedValue(arrayValue, arrayType, BfTypedValueKind_TempAddr);
  13203. }
  13204. _CreateMemArray(mResult, openToken, valueExprs, commas, closeToken);
  13205. }
  13206. }
  13207. }
  13208. void BfExprEvaluator::Visit(BfTupleExpression* tupleExpr)
  13209. {
  13210. if (mExpectingType != NULL)
  13211. {
  13212. if (mExpectingType->IsSizedArray())
  13213. {
  13214. InitializedSizedArray((BfSizedArrayType*)mExpectingType, tupleExpr->mOpenParen, tupleExpr->mValues, tupleExpr->mCommas, tupleExpr->mCloseParen);
  13215. return;
  13216. }
  13217. }
  13218. BfTupleType* tupleType = NULL;
  13219. bool hadFullMatch = false;
  13220. if ((mExpectingType != NULL) && (mExpectingType->IsTuple()))
  13221. {
  13222. tupleType = (BfTupleType*)mExpectingType;
  13223. hadFullMatch = tupleType->mFieldInstances.size() == tupleExpr->mValues.size();
  13224. }
  13225. struct InitValue
  13226. {
  13227. BfTypedValue mValue;
  13228. bool mIsUninitialized;
  13229. bool mIsDefaultInitializer;
  13230. bool mIsDeferred;
  13231. InitValue()
  13232. {
  13233. mIsUninitialized = false;
  13234. mIsDefaultInitializer = false;
  13235. mIsDeferred = false;
  13236. }
  13237. };
  13238. SizedArray<BfTypedValue, 2> typedValues;
  13239. if ((tupleExpr->mCommas.size() != 0) && (tupleExpr->mCommas.size() >= tupleExpr->mValues.size()))
  13240. {
  13241. // We would normally give this error during syntax parsing, but a TupleExpression can be an array initializer
  13242. mModule->FailAfter("Expression expected", tupleExpr->mCommas.back());
  13243. }
  13244. for (int valueIdx = 0; valueIdx < (int)tupleExpr->mValues.size(); valueIdx++)
  13245. {
  13246. BfExpression* valueExpr = tupleExpr->mValues[valueIdx];
  13247. BfType* fieldType = NULL;
  13248. BfFieldInstance* fieldInstance = NULL;
  13249. if (tupleType != NULL)
  13250. {
  13251. if (valueIdx < (int)tupleType->mFieldInstances.size())
  13252. {
  13253. fieldInstance = (BfFieldInstance*)&tupleType->mFieldInstances[valueIdx];
  13254. fieldType = fieldInstance->GetResolvedType();
  13255. if (fieldType->IsVoid())
  13256. {
  13257. typedValues.push_back(BfTypedValue());
  13258. continue;
  13259. }
  13260. if (fieldType->IsVar())
  13261. {
  13262. hadFullMatch = false;
  13263. fieldType = NULL;
  13264. }
  13265. }
  13266. }
  13267. bool tryDefer = false;
  13268. if (((fieldType == NULL) || (fieldType->IsComposite())) &&
  13269. ((valueExpr->IsA<BfInvocationExpression>()) || (valueExpr->IsExact<BfTupleExpression>())))
  13270. {
  13271. tryDefer = true;
  13272. }
  13273. SetAndRestoreValue<bool> prevIgnoreWrites(mModule->mBfIRBuilder->mIgnoreWrites, mModule->mBfIRBuilder->mIgnoreWrites || tryDefer);
  13274. BfTypedValue value = mModule->CreateValueFromExpression(valueExpr, fieldType);
  13275. if (!value)
  13276. {
  13277. if (fieldType != NULL)
  13278. value = mModule->GetDefaultTypedValue(fieldType);
  13279. else
  13280. value = mModule->GetDefaultTypedValue(mModule->mContext->mBfObjectType);
  13281. }
  13282. if ((fieldInstance != NULL) && (!fieldInstance->GetFieldDef()->IsUnnamedTupleField()) && (valueIdx < (int)tupleExpr->mNames.size()))
  13283. {
  13284. auto checkName = tupleExpr->mNames[valueIdx];
  13285. if (checkName != NULL)
  13286. {
  13287. if (checkName->ToString() != fieldInstance->GetFieldDef()->mName)
  13288. hadFullMatch = false;
  13289. }
  13290. }
  13291. value = mModule->LoadValue(value);
  13292. typedValues.push_back(value);
  13293. }
  13294. if (!hadFullMatch)
  13295. {
  13296. BfTypeVector fieldTypes;
  13297. Array<String> fieldNames;
  13298. for (auto typedVal : typedValues)
  13299. {
  13300. auto type = typedVal.mType;
  13301. if (type != NULL)
  13302. fieldTypes.push_back(type);
  13303. else
  13304. fieldTypes.push_back(mModule->mContext->mBfObjectType);
  13305. }
  13306. for (BfTupleNameNode* requestedName : tupleExpr->mNames)
  13307. {
  13308. if (requestedName == NULL)
  13309. fieldNames.push_back("");
  13310. else
  13311. fieldNames.push_back(requestedName->mNameNode->ToString());
  13312. }
  13313. tupleType = mModule->CreateTupleType(fieldTypes, fieldNames);
  13314. }
  13315. mModule->mBfIRBuilder->PopulateType(tupleType);
  13316. BfIRValue curTupleValue;
  13317. if ((mReceivingValue != NULL) && (mReceivingValue->mType == tupleType) && (mReceivingValue->IsAddr()))
  13318. {
  13319. mResult = *mReceivingValue;
  13320. mReceivingValue = NULL;
  13321. curTupleValue = mResult.mValue;
  13322. }
  13323. else
  13324. {
  13325. curTupleValue = mModule->CreateAlloca(tupleType);
  13326. mResultIsTempComposite = true;
  13327. mResult = BfTypedValue(curTupleValue, tupleType, BfTypedValueKind_TempAddr);
  13328. }
  13329. for (int valueIdx = 0; valueIdx < (int)typedValues.size(); valueIdx++)
  13330. {
  13331. BfFieldInstance* fieldInstance = &tupleType->mFieldInstances[valueIdx];
  13332. if (fieldInstance->mResolvedType->IsValuelessType())
  13333. continue;
  13334. auto typedVal = typedValues[valueIdx];
  13335. if (!typedVal)
  13336. {
  13337. mModule->AssertErrorState();
  13338. continue;
  13339. }
  13340. if (fieldInstance->mDataIdx >= 0)
  13341. {
  13342. auto memberVal = mModule->mBfIRBuilder->CreateInBoundsGEP(curTupleValue, 0, fieldInstance->mDataIdx);
  13343. if ((!mModule->mBfIRBuilder->mIgnoreWrites) && (typedVal.mValue.IsFake()))
  13344. {
  13345. // Value was deferred. Allow us to try to init in place
  13346. BfExpression* valueExpr = tupleExpr->mValues[valueIdx];
  13347. BfTypedValue memberPtrTypedVal = BfTypedValue(memberVal, fieldInstance->mResolvedType, BfTypedValueKind_Addr);
  13348. BfExprEvaluator exprEvaluator(mModule);
  13349. exprEvaluator.mExpectingType = fieldInstance->mResolvedType;
  13350. exprEvaluator.mReceivingValue = &memberPtrTypedVal;
  13351. exprEvaluator.Evaluate(valueExpr);
  13352. exprEvaluator.GetResult();
  13353. if (exprEvaluator.mReceivingValue == NULL)
  13354. {
  13355. // We wrote directly to the array in-place, we're done with this element
  13356. continue;
  13357. }
  13358. typedVal = exprEvaluator.mResult;
  13359. typedVal = mModule->Cast(valueExpr, typedVal, fieldInstance->mResolvedType);
  13360. if (!typedVal)
  13361. {
  13362. mModule->AssertErrorState();
  13363. continue;
  13364. }
  13365. typedVal = mModule->LoadValue(typedVal);
  13366. }
  13367. if (typedVal.IsSplat())
  13368. mModule->AggregateSplatIntoAddr(typedVal, memberVal);
  13369. else
  13370. mModule->mBfIRBuilder->CreateStore(typedVal.mValue, memberVal);
  13371. }
  13372. }
  13373. }
  13374. BfTypedValue BfExprEvaluator::SetupNullConditional(BfTypedValue thisValue, BfTokenNode* dotToken)
  13375. {
  13376. bool isStaticLookup = (!thisValue) ||
  13377. ((!thisValue.mType->IsValuelessType()) && (!thisValue.mValue));
  13378. if (isStaticLookup)
  13379. {
  13380. mModule->Fail("Null conditional reference not valid for static field references", dotToken);
  13381. return thisValue;
  13382. }
  13383. //TODO: But make null conditional work for Nullable types
  13384. if (thisValue.mType->IsNullable())
  13385. {
  13386. // Success
  13387. }
  13388. else if ((thisValue.mType->IsPointer()) || (thisValue.mType->IsObjectOrInterface()))
  13389. {
  13390. // Also good
  13391. }
  13392. else
  13393. {
  13394. if (thisValue.mType->IsStruct())
  13395. mModule->Warn(0, "Struct lookups can never fail, null conditional reference is unnecessary", dotToken);
  13396. else
  13397. mModule->AssertErrorState();
  13398. return thisValue;
  13399. }
  13400. thisValue = mModule->LoadValue(thisValue);
  13401. BfPendingNullConditional* pendingNullCond = mModule->mCurMethodState->mPendingNullConditional;
  13402. if (pendingNullCond == NULL)
  13403. {
  13404. pendingNullCond = new BfPendingNullConditional();
  13405. mModule->mCurMethodState->mPendingNullConditional = pendingNullCond;
  13406. }
  13407. if (!pendingNullCond->mPrevBB)
  13408. pendingNullCond->mPrevBB = mModule->mBfIRBuilder->GetInsertBlock();
  13409. if (!pendingNullCond->mDoneBB)
  13410. pendingNullCond->mDoneBB = mModule->mBfIRBuilder->CreateBlock("nullCond.done");
  13411. // We will in the br to checkBB later
  13412. if (!pendingNullCond->mCheckBB)
  13413. {
  13414. pendingNullCond->mCheckBB = mModule->mBfIRBuilder->CreateBlock("nullCond.check");
  13415. mModule->AddBasicBlock(pendingNullCond->mCheckBB);
  13416. }
  13417. BfIRValue isNotNull;
  13418. if (thisValue.mType->IsNullable())
  13419. {
  13420. BfGenericTypeInstance* nullableType = (BfGenericTypeInstance*)thisValue.mType->ToTypeInstance();
  13421. auto elementType = nullableType->GetUnderlyingType();
  13422. if (elementType->IsValuelessType())
  13423. {
  13424. thisValue = mModule->MakeAddressable(thisValue);
  13425. BfIRValue hasValuePtr = mModule->mBfIRBuilder->CreateInBoundsGEP(thisValue.mValue, 0, 1); // mHasValue
  13426. isNotNull = mModule->mBfIRBuilder->CreateLoad(hasValuePtr);
  13427. thisValue = BfTypedValue(mModule->mBfIRBuilder->GetFakeVal(), elementType, true);
  13428. }
  13429. else
  13430. {
  13431. thisValue = mModule->MakeAddressable(thisValue);
  13432. BfIRValue hasValuePtr = mModule->mBfIRBuilder->CreateInBoundsGEP(thisValue.mValue, 0, 2); // mHasValue
  13433. isNotNull = mModule->mBfIRBuilder->CreateLoad(hasValuePtr);
  13434. BfIRValue valuePtr = mModule->mBfIRBuilder->CreateInBoundsGEP(thisValue.mValue, 0, 1); // mValue
  13435. thisValue = BfTypedValue(valuePtr, elementType, true);
  13436. }
  13437. }
  13438. else
  13439. isNotNull = mModule->mBfIRBuilder->CreateIsNotNull(thisValue.mValue);
  13440. BfIRBlock notNullBB = mModule->mBfIRBuilder->CreateBlock("nullCond.notNull");
  13441. mModule->mBfIRBuilder->CreateCondBr(isNotNull, notNullBB, pendingNullCond->mDoneBB);
  13442. mModule->AddBasicBlock(notNullBB);
  13443. return thisValue;
  13444. }
  13445. void BfExprEvaluator::CheckDotToken(BfTokenNode* tokenNode)
  13446. {
  13447. if ((tokenNode != NULL) && (tokenNode->mToken == BfToken_DotDot))
  13448. mModule->Fail("Unexpected cascade operation. Chaining can only be used for method invocations", tokenNode);
  13449. }
  13450. void BfExprEvaluator::DoMemberReference(BfMemberReferenceExpression* memberRefExpr, BfTypedValue* outCascadeValue)
  13451. {
  13452. CheckDotToken(memberRefExpr->mDotToken);
  13453. BfAttributeState attributeState;
  13454. attributeState.mTarget = (BfAttributeTargets)(BfAttributeTargets_MemberAccess);
  13455. String findName;
  13456. BfAstNode* nameRefNode = memberRefExpr->mMemberName;
  13457. if (auto attrIdentifierExpr = BfNodeDynCast<BfAttributedIdentifierNode>(memberRefExpr->mMemberName))
  13458. {
  13459. nameRefNode = attrIdentifierExpr->mIdentifier;
  13460. // Don't validate
  13461. attributeState.mCustomAttributes = mModule->GetCustomAttributes(attrIdentifierExpr->mAttributes, BfAttributeTargets_SkipValidate);
  13462. if (nameRefNode != NULL)
  13463. findName = attrIdentifierExpr->mIdentifier->ToString();
  13464. }
  13465. else if (memberRefExpr->mMemberName != NULL)
  13466. findName = memberRefExpr->mMemberName->ToString();
  13467. defer
  13468. (
  13469. if (attributeState.mCustomAttributes != NULL)
  13470. {
  13471. if (mPropDef != NULL)
  13472. attributeState.mTarget = BfAttributeTargets_Invocation;
  13473. mModule->ValidateCustomAttributes(attributeState.mCustomAttributes, attributeState.mTarget);
  13474. }
  13475. );
  13476. SetAndRestoreValue<BfAttributeState*> prevAttributeState(mModule->mAttributeState, &attributeState);
  13477. BfTypeInstance* expectingTypeInst = NULL;
  13478. if (mExpectingType != NULL)
  13479. {
  13480. expectingTypeInst = mExpectingType->ToTypeInstance();
  13481. if (mExpectingType->IsPointer())
  13482. expectingTypeInst = mExpectingType->GetUnderlyingType()->ToTypeInstance();
  13483. else if (mExpectingType->IsNullable())
  13484. expectingTypeInst = mExpectingType->GetUnderlyingType()->ToTypeInstance();
  13485. else if (mExpectingType->IsConstExprValue())
  13486. expectingTypeInst = mExpectingType->GetUnderlyingType()->ToTypeInstance();
  13487. else if (mExpectingType->IsGenericParam())
  13488. {
  13489. auto genericParam = mModule->GetGenericParamInstance((BfGenericParamType*)mExpectingType);
  13490. if (genericParam->mTypeConstraint != NULL)
  13491. expectingTypeInst = genericParam->mTypeConstraint->ToTypeInstance();
  13492. }
  13493. }
  13494. BfAutoComplete* autoComplete = GetAutoComplete();
  13495. if (autoComplete != NULL)
  13496. {
  13497. SetAndRestoreValue<bool> prevFriendSet(autoComplete->mHasFriendSet, (attributeState.mCustomAttributes != NULL) && (attributeState.mCustomAttributes->Contains(mModule->mCompiler->mFriendAttributeTypeDef)));
  13498. if (memberRefExpr->mTarget == NULL)
  13499. {
  13500. String filter;
  13501. if ((mExpectingType != NULL) &&
  13502. (autoComplete->InitAutocomplete(memberRefExpr->mDotToken, memberRefExpr->mMemberName, filter)))
  13503. {
  13504. if (expectingTypeInst != NULL)
  13505. {
  13506. bool allowPrivate = expectingTypeInst == mModule->mCurTypeInstance;
  13507. if (expectingTypeInst->IsEnum())
  13508. autoComplete->AddEnumTypeMembers(expectingTypeInst, filter, false, allowPrivate);
  13509. autoComplete->AddSelfResultTypeMembers(expectingTypeInst, expectingTypeInst, filter, allowPrivate);
  13510. }
  13511. }
  13512. }
  13513. else
  13514. {
  13515. autoComplete->CheckMemberReference(memberRefExpr->mTarget, memberRefExpr->mDotToken, memberRefExpr->mMemberName);
  13516. if (auto objCreateExpr = BfNodeDynCast<BfObjectCreateExpression>(memberRefExpr->mTarget))
  13517. {
  13518. // This handles a weird case where we have "obj a = new\nWhatever().Thing = 123;".
  13519. // That gets parsed as "Whatever()" being the type we want to create, and then referencing
  13520. // the "Thing" member of that new object.
  13521. //if (objCreateExpr->mArraySizeSpecifier == NULL)
  13522. CheckObjectCreateTypeRef(mExpectingType, objCreateExpr->mNewNode);
  13523. }
  13524. }
  13525. }
  13526. if (memberRefExpr->mTarget == NULL)
  13527. {
  13528. if (mExpectingType == NULL)
  13529. {
  13530. mModule->Fail("Unqualified dot syntax can only be used when the result type can be inferred", nameRefNode);
  13531. return;
  13532. }
  13533. if (expectingTypeInst == NULL)
  13534. {
  13535. mModule->Fail(StrFormat("Unqualified dot syntax cannot be used with type '%s'", mModule->TypeToString(mExpectingType).c_str()), nameRefNode);
  13536. return;
  13537. }
  13538. if (mExpectingType->IsVar())
  13539. {
  13540. mResult = mModule->GetDefaultTypedValue(mExpectingType);
  13541. return;
  13542. }
  13543. BfTypedValue expectingVal(expectingTypeInst);
  13544. mResult = LookupField(memberRefExpr->mMemberName, expectingVal, findName);
  13545. if ((mResult) || (mPropDef != NULL))
  13546. return;
  13547. }
  13548. bool isNullCondLookup = (memberRefExpr->mDotToken != NULL) && (memberRefExpr->mDotToken->GetToken() == BfToken_QuestionDot);
  13549. bool isCascade = ((memberRefExpr->mDotToken != NULL) && (memberRefExpr->mDotToken->GetToken() == BfToken_DotDot));
  13550. BfIdentifierNode* nameLeft = BfNodeDynCast<BfIdentifierNode>(memberRefExpr->mTarget);
  13551. BfIdentifierNode* nameRight = BfIdentifierCast(memberRefExpr->mMemberName);
  13552. if ((nameLeft != NULL) && (nameRight != NULL) && (!isNullCondLookup) && (!isCascade))
  13553. {
  13554. bool hadError = false;
  13555. LookupQualifiedName(memberRefExpr, nameLeft, nameRight, true, &hadError);
  13556. if ((mResult) || (mPropDef != NULL))
  13557. return;
  13558. if (hadError)
  13559. return;
  13560. LookupQualifiedStaticField(memberRefExpr, nameLeft, nameRight, false);
  13561. return;
  13562. }
  13563. BfTypedValue thisValue;
  13564. if (auto exprTarget = BfNodeDynCast<BfExpression>(memberRefExpr->mTarget))
  13565. {
  13566. if (auto typeOfExpr = BfNodeDynCast<BfTypeOfExpression>(memberRefExpr->mTarget))
  13567. {
  13568. if (auto nameIdentifer = BfNodeDynCast<BfIdentifierNode>(memberRefExpr->mMemberName))
  13569. {
  13570. if (LookupTypeProp(typeOfExpr, nameIdentifer))
  13571. return;
  13572. }
  13573. }
  13574. //Hm, not using VisitChild broke our ability to write to a field for a not-initialized local struct
  13575. VisitChild(memberRefExpr->mTarget);
  13576. GetResult();
  13577. thisValue = mResult;
  13578. if (!thisValue)
  13579. {
  13580. if (auto targetIdentifier = BfNodeDynCast<BfIdentifierNode>(exprTarget))
  13581. thisValue = BfTypedValue(mModule->ResolveTypeRef(targetIdentifier, NULL));
  13582. }
  13583. if (!thisValue.HasType())
  13584. return;
  13585. //thisValue = mResult;
  13586. }
  13587. else if (auto typeRef = BfNodeDynCast<BfTypeReference>(memberRefExpr->mTarget))
  13588. {
  13589. // Look up static field
  13590. thisValue = BfTypedValue(ResolveTypeRef(typeRef));
  13591. }
  13592. if (nameRefNode == NULL)
  13593. {
  13594. mModule->AssertErrorState();
  13595. return;
  13596. }
  13597. if (isNullCondLookup)
  13598. thisValue = SetupNullConditional(thisValue, memberRefExpr->mDotToken);
  13599. mResult = LookupField(nameRefNode, thisValue, findName);
  13600. if ((!mResult) && (mPropDef == NULL))
  13601. {
  13602. if (thisValue.mType != NULL)
  13603. {
  13604. BfTypeInstance* typeInst = thisValue.mType->ToTypeInstance();
  13605. auto compiler = mModule->mCompiler;
  13606. if ((typeInst != NULL) && (compiler->IsAutocomplete()) && (compiler->mResolvePassData->mAutoComplete->CheckFixit(memberRefExpr->mMemberName)))
  13607. {
  13608. FixitAddMember(typeInst, mExpectingType, findName, !thisValue.mValue);
  13609. }
  13610. }
  13611. if ((!thisValue.mValue) && (thisValue.mType != NULL))
  13612. {
  13613. if (auto targetIdentifier = BfNodeDynCast<BfIdentifierNode>(memberRefExpr->mMemberName))
  13614. {
  13615. mResult.mType = mModule->ResolveInnerType(thisValue.mType, targetIdentifier, BfPopulateType_Declaration);
  13616. }
  13617. }
  13618. if (mResult.mType == NULL)
  13619. mModule->Fail("Unable to find member", nameRefNode);
  13620. }
  13621. if (isNullCondLookup)
  13622. mResult = GetResult();
  13623. if (isCascade)
  13624. {
  13625. if (outCascadeValue != NULL)
  13626. *outCascadeValue = thisValue;
  13627. else
  13628. mModule->Fail("Unexpected cascade operation. Chaining can only be used for method invocations", memberRefExpr->mDotToken);
  13629. }
  13630. }
  13631. void BfExprEvaluator::Visit(BfMemberReferenceExpression* memberRefExpr)
  13632. {
  13633. DoMemberReference(memberRefExpr, NULL);
  13634. }
  13635. void BfExprEvaluator::Visit(BfIndexerExpression* indexerExpr)
  13636. {
  13637. VisitChild(indexerExpr->mTarget);
  13638. ResolveGenericType();
  13639. auto target = GetResult(true);
  13640. if (!target)
  13641. return;
  13642. BfCheckedKind checkedKind = BfCheckedKind_NotSet;
  13643. bool isInlined = false;
  13644. if ((mModule->mAttributeState != NULL) && (mModule->mAttributeState->mCustomAttributes != NULL))
  13645. {
  13646. if (mModule->mAttributeState->mCustomAttributes->Contains(mModule->mCompiler->mInlineAttributeTypeDef))
  13647. {
  13648. isInlined = true;
  13649. mModule->mAttributeState->mUsed = true;
  13650. }
  13651. if (mModule->mAttributeState->mCustomAttributes->Contains(mModule->mCompiler->mCheckedAttributeTypeDef))
  13652. {
  13653. checkedKind = BfCheckedKind_Checked;
  13654. mModule->mAttributeState->mUsed = true;
  13655. }
  13656. if (mModule->mAttributeState->mCustomAttributes->Contains(mModule->mCompiler->mUncheckedAttributeTypeDef))
  13657. {
  13658. checkedKind = BfCheckedKind_Unchecked;
  13659. mModule->mAttributeState->mUsed = true;
  13660. }
  13661. }
  13662. bool isNullCondLookup = (indexerExpr->mOpenBracket != NULL) && (indexerExpr->mOpenBracket->GetToken() == BfToken_QuestionLBracket);
  13663. if (isNullCondLookup)
  13664. target = SetupNullConditional(target, indexerExpr->mOpenBracket);
  13665. if (target.mType->IsVar())
  13666. {
  13667. mResult = BfTypedValue(mModule->GetDefaultValue(target.mType), target.mType, true);
  13668. return;
  13669. }
  13670. if (target.mType->IsTypeInstance())
  13671. {
  13672. mIndexerValues.clear();
  13673. for (BfExpression* expr : indexerExpr->mArguments)
  13674. {
  13675. if (expr == NULL)
  13676. return;
  13677. auto argVal = mModule->CreateValueFromExpression(expr);
  13678. if (!argVal)
  13679. {
  13680. mModule->AssertErrorState();
  13681. argVal = mModule->GetDefaultTypedValue(mModule->mContext->mBfObjectType);
  13682. }
  13683. BfResolvedArg resolvedArg;
  13684. resolvedArg.mTypedValue = argVal;
  13685. mIndexerValues.push_back(resolvedArg);
  13686. }
  13687. BfMethodMatcher methodMatcher(indexerExpr->mTarget, mModule, "[]", mIndexerValues, NULL);
  13688. methodMatcher.mCheckedKind = checkedKind;
  13689. //methodMatcher.CheckType(target.mType->ToTypeInstance(), target, false);
  13690. BfMethodDef* methodDef = NULL;
  13691. auto startCheckTypeInst = target.mType->ToTypeInstance();
  13692. for (int pass = 0; pass < 2; pass++)
  13693. {
  13694. bool isFailurePass = pass == 1;
  13695. auto curCheckType = startCheckTypeInst;
  13696. while (curCheckType != NULL)
  13697. {
  13698. BfProtectionCheckFlags protectionCheckFlags = BfProtectionCheckFlag_None;
  13699. BfPropertyDef* foundProp = NULL;
  13700. BfTypeInstance* foundPropTypeInst = NULL;
  13701. int matchedIndexCount = 0;
  13702. curCheckType->mTypeDef->PopulateMemberSets();
  13703. BfMemberSetEntry* entry;
  13704. BfPropertyDef* matchedProp = NULL;
  13705. BfPropertyDef* nextProp = NULL;
  13706. if (curCheckType->mTypeDef->mPropertySet.TryGetWith(String("[]"), &entry))
  13707. nextProp = (BfPropertyDef*)entry->mMemberDef;
  13708. while (nextProp != NULL)
  13709. {
  13710. auto prop = nextProp;
  13711. nextProp = nextProp->mNextWithSameName;
  13712. //TODO: Match against setMethod (minus last param) if we have no 'get' method
  13713. for (auto checkMethod : prop->mMethods)
  13714. {
  13715. if (checkMethod->mMethodType != BfMethodType_PropertyGetter)
  13716. continue;
  13717. // For generic params - check interface constraints for an indexer, call that method
  13718. BF_ASSERT(!target.mType->IsGenericParam());
  13719. if (checkMethod->mExplicitInterface != NULL)
  13720. continue;
  13721. if (checkMethod->mIsOverride)
  13722. continue;
  13723. auto autoComplete = GetAutoComplete();
  13724. bool wasCapturingMethodMatchInfo = false;
  13725. if (autoComplete != NULL)
  13726. {
  13727. // Set to false to make sure we don't capture method match info from 'params' array creation
  13728. wasCapturingMethodMatchInfo = autoComplete->mIsCapturingMethodMatchInfo;
  13729. autoComplete->mIsCapturingMethodMatchInfo = false;
  13730. }
  13731. defer
  13732. (
  13733. if (autoComplete != NULL)
  13734. autoComplete->mIsCapturingMethodMatchInfo = wasCapturingMethodMatchInfo;
  13735. );
  13736. if ((!isFailurePass) && (!methodMatcher.WantsCheckMethod(protectionCheckFlags, startCheckTypeInst, curCheckType, checkMethod)))
  13737. continue;
  13738. if (!methodMatcher.IsMemberAccessible(curCheckType, checkMethod->mDeclaringType))
  13739. continue;
  13740. methodMatcher.mCheckedKind = checkedKind;
  13741. methodMatcher.CheckMethod(curCheckType, checkMethod, false);
  13742. if ((methodMatcher.mBestMethodDef == checkMethod) ||
  13743. ((foundProp == NULL) && (methodMatcher.mBackupMethodDef == checkMethod)))
  13744. {
  13745. foundPropTypeInst = curCheckType;
  13746. foundProp = prop;
  13747. matchedIndexCount = (int)checkMethod->mParams.size();
  13748. }
  13749. }
  13750. }
  13751. if (foundProp != NULL)
  13752. {
  13753. int indexDiff = matchedIndexCount - (int)mIndexerValues.size();
  13754. if (indexDiff > 0)
  13755. {
  13756. mModule->Fail(StrFormat("Expected %d more indices", indexDiff), indexerExpr->mTarget);
  13757. //mModule->mCompiler->mPassInstance->MoreInfo("See method declaration", methodInstance->mMethodDef->mMethodDeclaration);
  13758. }
  13759. else if (indexDiff < 0)
  13760. {
  13761. mModule->Fail(StrFormat("Expected %d fewer indices", indexDiff), indexerExpr->mTarget);
  13762. }
  13763. else
  13764. {
  13765. mPropSrc = indexerExpr->mOpenBracket;
  13766. mPropDef = foundProp;
  13767. if (foundProp->mIsStatic)
  13768. {
  13769. mPropTarget = BfTypedValue(curCheckType);
  13770. }
  13771. else
  13772. {
  13773. if (target.mType != foundPropTypeInst)
  13774. mPropTarget = mModule->Cast(indexerExpr->mTarget, target, foundPropTypeInst);
  13775. else
  13776. mPropTarget = target;
  13777. }
  13778. mOrigPropTarget = mPropTarget;
  13779. if (isInlined)
  13780. mPropGetMethodFlags = (BfGetMethodInstanceFlags)(mPropGetMethodFlags | BfGetMethodInstanceFlag_ForceInline);
  13781. mPropCheckedKind = checkedKind;
  13782. }
  13783. return;
  13784. }
  13785. curCheckType = curCheckType->mBaseType;
  13786. }
  13787. }
  13788. mModule->Fail("Unable to find indexer property", indexerExpr->mTarget);
  13789. return;
  13790. }
  13791. //target.mType = mModule->ResolveGenericType(target.mType);
  13792. if (target.mType->IsVar())
  13793. {
  13794. mResult = target;
  13795. return;
  13796. }
  13797. if ((!target.mType->IsPointer()) && (!target.mType->IsSizedArray()))
  13798. {
  13799. mModule->Fail("Expected pointer or array type", indexerExpr->mTarget);
  13800. return;
  13801. }
  13802. auto _GetDefaultResult = [&]()
  13803. {
  13804. return mModule->GetDefaultTypedValue(target.mType->GetUnderlyingType(), false, BfDefaultValueKind_Addr);
  13805. };
  13806. if (indexerExpr->mArguments.size() != 1)
  13807. {
  13808. mModule->Fail("Expected single index", indexerExpr->mOpenBracket);
  13809. mResult = _GetDefaultResult();
  13810. return;
  13811. }
  13812. if (indexerExpr->mArguments[0] == NULL)
  13813. {
  13814. mModule->AssertErrorState();
  13815. mResult = _GetDefaultResult();
  13816. return;
  13817. }
  13818. bool isUndefIndex = false;
  13819. auto indexArgument = mModule->CreateValueFromExpression(indexerExpr->mArguments[0]);
  13820. if (!indexArgument)
  13821. return;
  13822. if (!indexArgument.mType->IsIntegral())
  13823. {
  13824. if (indexArgument.mType->IsVar())
  13825. {
  13826. isUndefIndex = true;
  13827. indexArgument = mModule->GetDefaultTypedValue(mModule->GetPrimitiveType(BfTypeCode_IntPtr), false, BfDefaultValueKind_Undef);
  13828. }
  13829. else
  13830. {
  13831. mModule->Fail("Expected integer index", indexerExpr->mArguments[0]);
  13832. indexArgument = mModule->GetDefaultTypedValue(mModule->GetPrimitiveType(BfTypeCode_IntPtr));
  13833. }
  13834. }
  13835. if (indexArgument.mType->IsPrimitiveType())
  13836. {
  13837. auto primType = (BfPrimitiveType*)indexArgument.mType;
  13838. if ((!primType->IsSigned()) && (primType->mSize < 8))
  13839. {
  13840. // GEP will always do a signed upcast so we need to cast manually if we are unsigned
  13841. indexArgument = BfTypedValue(mModule->mBfIRBuilder->CreateNumericCast(indexArgument.mValue, false, BfTypeCode_IntPtr), mModule->GetPrimitiveType(BfTypeCode_IntPtr));
  13842. }
  13843. }
  13844. mModule->PopulateType(target.mType);
  13845. if (target.mType->IsSizedArray())
  13846. {
  13847. BfSizedArrayType* sizedArrayType = (BfSizedArrayType*)target.mType;
  13848. auto underlyingType = sizedArrayType->mElementType;
  13849. if (indexArgument.mValue.IsConst())
  13850. {
  13851. auto indexConst = mModule->mBfIRBuilder->GetConstant(indexArgument.mValue);
  13852. if (indexConst->mUInt64 >= (uint64)sizedArrayType->mElementCount)
  13853. {
  13854. mModule->Fail(StrFormat("Index '%d' is out of bounds for type '%s'", indexConst->mInt32, mModule->TypeToString(target.mType).c_str()), indexerExpr->mArguments[0]);
  13855. mResult = _GetDefaultResult();
  13856. return;
  13857. }
  13858. }
  13859. else if (mModule->HasCompiledOutput())
  13860. {
  13861. if (checkedKind == BfCheckedKind_NotSet)
  13862. checkedKind = mModule->GetDefaultCheckedKind();
  13863. if (checkedKind == BfCheckedKind_Checked)
  13864. {
  13865. auto oobBlock = mModule->mBfIRBuilder->CreateBlock("oob", true);
  13866. auto contBlock = mModule->mBfIRBuilder->CreateBlock("cont", true);
  13867. auto indexType = (BfPrimitiveType*)indexArgument.mType;
  13868. if (!mModule->mSystem->DoesLiteralFit(indexType->mTypeDef->mTypeCode, sizedArrayType->mElementCount))
  13869. {
  13870. // We need to upsize the index so we can compare it against the larger elementCount
  13871. indexType = mModule->GetPrimitiveType(BfTypeCode_IntPtr);
  13872. indexArgument = mModule->Cast(indexerExpr->mArguments[0], indexArgument, indexType);
  13873. }
  13874. auto cmpRes = mModule->mBfIRBuilder->CreateCmpGTE(indexArgument.mValue, mModule->mBfIRBuilder->CreateConst(indexType->mTypeDef->mTypeCode, (uint64)sizedArrayType->mElementCount), false);
  13875. mModule->mBfIRBuilder->CreateCondBr(cmpRes, oobBlock, contBlock);
  13876. mModule->mBfIRBuilder->SetInsertPoint(oobBlock);
  13877. auto internalType = mModule->ResolveTypeDef(mModule->mCompiler->mInternalTypeDef);
  13878. auto oobFunc = mModule->GetMethodByName(internalType->ToTypeInstance(), "ThrowIndexOutOfRange");
  13879. if (oobFunc.mFunc)
  13880. {
  13881. /*if (!mModule->mCompiler->mIsResolveOnly)
  13882. {
  13883. OutputDebugStrF("-OOB %d %d\n", oobFunc.mFunc.mId, oobFunc.mFunc.mFlags);
  13884. }*/
  13885. SizedArray<BfIRValue, 1> args;
  13886. args.push_back(mModule->GetConstValue(0));
  13887. mModule->mBfIRBuilder->CreateCall(oobFunc.mFunc, args);
  13888. mModule->mBfIRBuilder->CreateUnreachable();
  13889. mModule->mBfIRBuilder->SetInsertPoint(contBlock);
  13890. }
  13891. else
  13892. {
  13893. mModule->Fail("System.Internal class must contain method 'ThrowIndexOutOfRange'");
  13894. }
  13895. }
  13896. }
  13897. // If this is a 'bag of bytes', we should try hard not to have to make this addressable
  13898. if ((!target.IsAddr()) && (!target.mType->IsSizeAligned()))
  13899. mModule->MakeAddressable(target);
  13900. mModule->PopulateType(underlyingType);
  13901. if (sizedArrayType->IsUnknownSizedArray())
  13902. {
  13903. mResult = mModule->GetDefaultTypedValue(underlyingType);
  13904. }
  13905. else if (sizedArrayType->IsValuelessType())
  13906. {
  13907. if (underlyingType->IsValuelessType())
  13908. mResult = BfTypedValue(mModule->mBfIRBuilder->GetFakeVal(), underlyingType, true);
  13909. else
  13910. {
  13911. mResult = mModule->GetDefaultTypedValue(underlyingType);
  13912. if (sizedArrayType->mElementCount != 0)
  13913. mModule->AssertErrorState();
  13914. }
  13915. }
  13916. else if (target.IsAddr())
  13917. {
  13918. if (target.mType->IsSizeAligned())
  13919. {
  13920. auto ptrType = mModule->CreatePointerType(underlyingType);
  13921. auto ptrValue = mModule->mBfIRBuilder->CreateBitCast(target.mValue, mModule->mBfIRBuilder->MapType(ptrType));
  13922. auto gepResult = mModule->mBfIRBuilder->CreateInBoundsGEP(ptrValue, indexArgument.mValue);
  13923. mResult = BfTypedValue(gepResult, underlyingType, target.IsReadOnly() ? BfTypedValueKind_ReadOnlyAddr : BfTypedValueKind_Addr);
  13924. }
  13925. else
  13926. {
  13927. auto indexResult = mModule->CreateIndexedValue(underlyingType, target.mValue, indexArgument.mValue);
  13928. mResult = BfTypedValue(indexResult, underlyingType, target.IsReadOnly() ? BfTypedValueKind_ReadOnlyAddr : BfTypedValueKind_Addr);
  13929. }
  13930. }
  13931. else
  13932. {
  13933. if ((!target.mValue.IsConst()) && (!indexArgument.mValue.IsConst()))
  13934. {
  13935. mModule->Fail("Unable to index value", indexerExpr->mTarget);
  13936. return;
  13937. }
  13938. mModule->mBfIRBuilder->PopulateType(target.mType);
  13939. auto gepResult = mModule->mBfIRBuilder->CreateExtractValue(target.mValue, indexArgument.mValue);
  13940. if ((underlyingType->IsString()) || (underlyingType->IsPointer()))
  13941. {
  13942. auto resultConst = mModule->mBfIRBuilder->GetConstant(gepResult);
  13943. if ((resultConst != NULL) && (resultConst->mTypeCode == BfTypeCode_Int32))
  13944. {
  13945. int strId = resultConst->mInt32;
  13946. const StringImpl& str = mModule->mContext->mStringObjectIdMap[strId].mString;
  13947. if (underlyingType->IsString())
  13948. gepResult = mModule->GetStringObjectValue(str, false);
  13949. else
  13950. gepResult = mModule->GetStringCharPtr(strId);
  13951. }
  13952. }
  13953. mResult = BfTypedValue(gepResult, underlyingType, BfTypedValueKind_Value);
  13954. }
  13955. }
  13956. else
  13957. {
  13958. target = mModule->LoadValue(target);
  13959. BfPointerType* pointerType = (BfPointerType*)target.mType;
  13960. auto underlyingType = pointerType->mElementType;
  13961. mModule->mBfIRBuilder->PopulateType(underlyingType);
  13962. if (isUndefIndex)
  13963. {
  13964. mResult = mModule->GetDefaultTypedValue(underlyingType, false, BfDefaultValueKind_Addr);
  13965. }
  13966. else
  13967. {
  13968. BfIRValue result = mModule->CreateIndexedValue(underlyingType, target.mValue, indexArgument.mValue);
  13969. mResult = BfTypedValue(result, underlyingType, true);
  13970. }
  13971. }
  13972. }
  13973. void BfExprEvaluator::Visit(BfUnaryOperatorExpression* unaryOpExpr)
  13974. {
  13975. BfAutoParentNodeEntry autoParentNodeEntry(mModule, unaryOpExpr);
  13976. PerformUnaryOperation(unaryOpExpr->mExpression, unaryOpExpr->mOp, unaryOpExpr->mOpToken);
  13977. }
  13978. void BfExprEvaluator::PerformUnaryOperation(BfExpression* unaryOpExpr, BfUnaryOp unaryOp, BfTokenNode* opToken)
  13979. {
  13980. {
  13981. // If this is a cast, we don't want the value to be coerced before the unary operator is applied.
  13982. // WAIT: Why not?
  13983. //SetAndRestoreValue<BfType*> prevExpectingType(mExpectingType, NULL);
  13984. BfType* prevExpedcting = mExpectingType;
  13985. switch (unaryOp)
  13986. {
  13987. case BfUnaryOp_Negate:
  13988. case BfUnaryOp_Positive:
  13989. case BfUnaryOp_InvertBits:
  13990. // If we're expecting an int64 or uint64 then just leave the type as unknown
  13991. if ((mExpectingType != NULL) && (mExpectingType->IsInteger()) && (mExpectingType->mSize == 8))
  13992. mExpectingType = NULL;
  13993. // Otherwise keep expecting type
  13994. break;
  13995. default:
  13996. mExpectingType = NULL;
  13997. }
  13998. VisitChild(unaryOpExpr);
  13999. mExpectingType = prevExpedcting;
  14000. }
  14001. BfExprEvaluator::PerformUnaryOperation_OnResult(unaryOpExpr, unaryOp, opToken);
  14002. }
  14003. void BfExprEvaluator::PerformUnaryOperation_OnResult(BfExpression* unaryOpExpr, BfUnaryOp unaryOp, BfTokenNode* opToken)
  14004. {
  14005. BfAstNode* propSrc = mPropSrc;
  14006. BfTypedValue propTarget = mPropTarget;
  14007. BfPropertyDef* propDef = mPropDef;
  14008. SizedArray<BfResolvedArg, 2> indexerVals = mIndexerValues;
  14009. BfTypedValue writeToProp;
  14010. GetResult();
  14011. if (!mResult)
  14012. return;
  14013. if (mResult.mType->IsRef())
  14014. mResult.mType = mResult.mType->GetUnderlyingType();
  14015. if (mResult.mType->IsVar())
  14016. {
  14017. mResult = BfTypedValue(mModule->GetDefaultValue(mResult.mType), mResult.mType);
  14018. return;
  14019. }
  14020. if ((mResult.mType->IsTypeInstance()) || (mResult.mType->IsGenericParam()))
  14021. {
  14022. SizedArray<BfResolvedArg, 1> args;
  14023. BfResolvedArg resolvedArg;
  14024. resolvedArg.mTypedValue = mResult;
  14025. args.push_back(resolvedArg);
  14026. BfMethodMatcher methodMatcher(opToken, mModule, "", args, NULL);
  14027. BfBaseClassWalker baseClassWalker(mResult.mType, NULL, mModule);
  14028. BfUnaryOp findOp = unaryOp;
  14029. bool isPostOp = false;
  14030. if (findOp == BfUnaryOp_PostIncrement)
  14031. {
  14032. findOp = BfUnaryOp_Increment;
  14033. isPostOp = true;
  14034. }
  14035. if (findOp == BfUnaryOp_PostDecrement)
  14036. {
  14037. findOp = BfUnaryOp_Decrement;
  14038. isPostOp = true;
  14039. }
  14040. BfType* bestSelfType = NULL;
  14041. while (true)
  14042. {
  14043. auto entry = baseClassWalker.Next();
  14044. auto checkType = entry.mTypeInstance;
  14045. if (checkType == NULL)
  14046. break;
  14047. for (auto operatorDef : checkType->mTypeDef->mOperators)
  14048. {
  14049. if (operatorDef->mOperatorDeclaration->mUnaryOp == findOp)
  14050. {
  14051. if (!methodMatcher.IsMemberAccessible(checkType, operatorDef->mDeclaringType))
  14052. continue;
  14053. if (methodMatcher.CheckMethod(checkType, operatorDef, false))
  14054. methodMatcher.mSelfType = entry.mSrcType;
  14055. }
  14056. }
  14057. }
  14058. if (methodMatcher.mBestMethodDef != NULL)
  14059. {
  14060. if (!baseClassWalker.mMayBeFromInterface)
  14061. mModule->SetElementType(opToken, BfSourceElementType_Method);
  14062. auto methodDef = methodMatcher.mBestMethodDef;
  14063. auto autoComplete = GetAutoComplete();
  14064. if ((autoComplete != NULL) && (autoComplete->IsAutocompleteNode(opToken)))
  14065. {
  14066. auto operatorDecl = BfNodeDynCast<BfOperatorDeclaration>(methodDef->mMethodDeclaration);
  14067. if ((operatorDecl != NULL) && (operatorDecl->mOpTypeToken != NULL))
  14068. autoComplete->SetDefinitionLocation(operatorDecl->mOpTypeToken);
  14069. }
  14070. SizedArray<BfExpression*, 2> argSrcs;
  14071. argSrcs.push_back(unaryOpExpr);
  14072. mResult = CreateCall(&methodMatcher, BfTypedValue());
  14073. if ((mResult.mType != NULL) && (methodMatcher.mSelfType != NULL) && (mResult.mType->IsSelf()))
  14074. {
  14075. BF_ASSERT(mModule->IsInGeneric());
  14076. mResult = mModule->GetDefaultTypedValue(methodMatcher.mSelfType);
  14077. }
  14078. if (isPostOp)
  14079. mResult = args[0].mTypedValue;
  14080. return;
  14081. }
  14082. // Check method generic constraints
  14083. if ((mModule->mCurMethodInstance != NULL) && (mModule->mCurMethodInstance->mIsUnspecialized) && (mModule->mCurMethodInstance->mMethodInfoEx != NULL))
  14084. {
  14085. for (int genericParamIdx = 0; genericParamIdx < mModule->mCurMethodInstance->mMethodInfoEx->mGenericParams.size(); genericParamIdx++)
  14086. {
  14087. auto genericParam = mModule->mCurMethodInstance->mMethodInfoEx->mGenericParams[genericParamIdx];
  14088. for (auto& opConstraint : genericParam->mOperatorConstraints)
  14089. {
  14090. if (opConstraint.mUnaryOp == findOp)
  14091. {
  14092. if (mModule->CanImplicitlyCast(args[0].mTypedValue, opConstraint.mRightType))
  14093. {
  14094. mResult = BfTypedValue(mModule->mBfIRBuilder->GetFakeVal(), genericParam->mExternType);
  14095. return;
  14096. }
  14097. }
  14098. }
  14099. }
  14100. }
  14101. // Check type generic constraints
  14102. if ((mModule->mCurTypeInstance->IsGenericTypeInstance()) && (mModule->mCurTypeInstance->IsUnspecializedType()))
  14103. {
  14104. auto genericTypeInst = (BfGenericTypeInstance*)mModule->mCurTypeInstance;
  14105. for (int genericParamIdx = 0; genericParamIdx < genericTypeInst->mGenericParams.size(); genericParamIdx++)
  14106. {
  14107. auto genericParam = mModule->GetGenericTypeParamInstance(genericParamIdx);
  14108. for (auto& opConstraint : genericParam->mOperatorConstraints)
  14109. {
  14110. if (opConstraint.mUnaryOp == findOp)
  14111. {
  14112. if (mModule->CanImplicitlyCast(args[0].mTypedValue, opConstraint.mRightType))
  14113. {
  14114. mResult = BfTypedValue(mModule->mBfIRBuilder->GetFakeVal(), genericParam->mExternType);
  14115. return;
  14116. }
  14117. }
  14118. }
  14119. }
  14120. }
  14121. }
  14122. bool numericFail = false;
  14123. switch (unaryOp)
  14124. {
  14125. case BfUnaryOp_Not:
  14126. {
  14127. CheckResultForReading(mResult);
  14128. auto boolType = mModule->GetPrimitiveType(BfTypeCode_Boolean);
  14129. auto value = mModule->LoadValue(mResult);
  14130. value = mModule->Cast(unaryOpExpr, value, boolType);
  14131. if (!value)
  14132. return;
  14133. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateNot(value.mValue), boolType);
  14134. }
  14135. break;
  14136. case BfUnaryOp_Positive:
  14137. return;
  14138. case BfUnaryOp_Negate:
  14139. {
  14140. CheckResultForReading(mResult);
  14141. auto value = mModule->LoadValue(mResult);
  14142. if (!value)
  14143. return;
  14144. BfType* origType = value.mType;
  14145. if (value.mType->IsTypedPrimitive())
  14146. value.mType = value.mType->GetUnderlyingType();
  14147. if (value.mType->IsIntegral())
  14148. {
  14149. auto primType = (BfPrimitiveType*)value.mType;
  14150. auto wantType = primType;
  14151. auto constant = mModule->mBfIRBuilder->GetConstant(value.mValue);
  14152. if ((constant != NULL) && (mModule->mBfIRBuilder->IsInt(constant->mTypeCode)))
  14153. {
  14154. if ((primType->mTypeDef->mTypeCode == BfTypeCode_UInt32) && (constant->mInt64 == 0x80000000LL))
  14155. {
  14156. mResult = BfTypedValue(mModule->GetConstValue32(-0x80000000LL), mModule->GetPrimitiveType(BfTypeCode_Int32));
  14157. return;
  14158. }
  14159. else if ((primType->mTypeDef->mTypeCode == BfTypeCode_UInt64) && (constant->mInt64 == 0x8000000000000000LL))
  14160. {
  14161. mResult = BfTypedValue(mModule->GetConstValue64(-0x8000000000000000LL), mModule->GetPrimitiveType(BfTypeCode_Int64));
  14162. return;
  14163. }
  14164. }
  14165. /*if (auto constantInt = dyn_cast<ConstantInt>((Value*)value.mValue))
  14166. {
  14167. int64 i64Val = constantInt->getSExtValue();
  14168. // This is a special case where the user entered -0x80000000 (maxint) but we thought "0x80000000" was a uint in the parser
  14169. // which would get upcasted to an int64 for this negate. Properly bring back down to an int32
  14170. if ((primType->mTypeDef->mTypeCode == BfTypeCode_UInt32) && (i64Val == -0x80000000LL))
  14171. {
  14172. mResult = BfTypedValue(mModule->GetConstValue((int)i64Val), mModule->GetPrimitiveType(BfTypeCode_Int32));
  14173. return;
  14174. }
  14175. }*/
  14176. if (!primType->IsSigned())
  14177. {
  14178. if (primType->mSize == 1)
  14179. wantType = mModule->GetPrimitiveType(BfTypeCode_Int16);
  14180. else if (primType->mSize == 2)
  14181. wantType = mModule->GetPrimitiveType(BfTypeCode_Int32);
  14182. else if (primType->mSize == 4)
  14183. wantType = mModule->GetPrimitiveType(BfTypeCode_Int64);
  14184. else
  14185. mModule->Fail("Operator '-' cannot be applied to uint64", opToken);
  14186. }
  14187. if (primType != wantType)
  14188. {
  14189. value = mModule->Cast(unaryOpExpr, value, wantType, BfCastFlags_Explicit);
  14190. if (!value)
  14191. return;
  14192. }
  14193. if (origType->mSize == wantType->mSize) // Allow negative of primitive typed but not if we had to upsize
  14194. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateNeg(value.mValue), origType);
  14195. else
  14196. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateNeg(value.mValue), wantType);
  14197. }
  14198. else if (value.mType->IsFloat())
  14199. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateNeg(value.mValue), origType);
  14200. else
  14201. numericFail = true;
  14202. }
  14203. break;
  14204. case BfUnaryOp_InvertBits:
  14205. {
  14206. CheckResultForReading(mResult);
  14207. auto value = mModule->LoadValue(mResult);
  14208. if (!value)
  14209. return;
  14210. bool isInteger = value.mType->IsIntegral();
  14211. if (value.mType->IsTypedPrimitive())
  14212. isInteger = value.mType->GetUnderlyingType()->IsIntegral();
  14213. if (!isInteger)
  14214. {
  14215. mModule->Fail("Operator can only be used on integer types", opToken);
  14216. return;
  14217. }
  14218. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateNot(value.mValue), value.mType);
  14219. }
  14220. break;
  14221. case BfUnaryOp_AddressOf:
  14222. {
  14223. MarkResultUsed();
  14224. mModule->FixIntUnknown(mResult);
  14225. mModule->PopulateType(mResult.mType);
  14226. auto ptrType = mModule->CreatePointerType(mResult.mType);
  14227. if ((!CheckModifyResult(mResult, unaryOpExpr, "take address of")) || (mResult.mType->IsValuelessType()))
  14228. {
  14229. // Sentinel value
  14230. auto val = mModule->mBfIRBuilder->CreateIntToPtr(mModule->mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, 1), mModule->mBfIRBuilder->MapType(ptrType));
  14231. mResult = BfTypedValue(val, ptrType);
  14232. }
  14233. else
  14234. mResult = BfTypedValue(mResult.mValue, ptrType, false);
  14235. }
  14236. break;
  14237. case BfUnaryOp_Dereference:
  14238. {
  14239. CheckResultForReading(mResult);
  14240. if (!mResult.mType->IsPointer())
  14241. {
  14242. mResult = BfTypedValue();
  14243. mModule->Fail("Cannot dereference non-pointer type", unaryOpExpr);
  14244. return;
  14245. }
  14246. auto derefTarget = mModule->LoadValue(mResult);
  14247. BfPointerType* pointerType = (BfPointerType*)derefTarget.mType;
  14248. auto resolvedType = mModule->ResolveType(pointerType->mElementType);
  14249. if (resolvedType == NULL)
  14250. {
  14251. mResult = BfTypedValue();
  14252. return;
  14253. }
  14254. mModule->PopulateType(resolvedType);
  14255. if (resolvedType->IsValuelessType())
  14256. mResult = BfTypedValue(mModule->mBfIRBuilder->GetFakeVal(), resolvedType, true);
  14257. else
  14258. mResult = BfTypedValue(derefTarget.mValue, resolvedType, true);
  14259. }
  14260. break;
  14261. case BfUnaryOp_PostIncrement:
  14262. case BfUnaryOp_Increment:
  14263. {
  14264. CheckResultForReading(mResult);
  14265. auto ptr = mResult;
  14266. //if ((propDef == NULL) && (!mModule->CheckModifyValue(ptr, opToken)))
  14267. if ((propDef == NULL) && (!CheckModifyResult(ptr, opToken, "increment")))
  14268. return;
  14269. BfTypedValue origTypedVal = mModule->LoadValue(ptr, NULL, mIsVolatileReference);
  14270. BfIRValue origVal = origTypedVal.mValue;
  14271. BfIRValue constValue = mModule->GetConstValue(1, ptr.mType);
  14272. BfIRValue resultValue;
  14273. if (ptr.mType->IsPointer())
  14274. {
  14275. BfPointerType* ptrType = (BfPointerType*)ptr.mType;
  14276. BfType* intPtrType = mModule->GetPrimitiveType(BfTypeCode_IntPtr);
  14277. constValue = mModule->GetConstValue(ptrType->mElementType->GetStride(), intPtrType);
  14278. BfIRValue origIntValue = mModule->mBfIRBuilder->CreatePtrToInt(origVal, BfTypeCode_IntPtr);
  14279. BfIRValue newIntValue = mModule->mBfIRBuilder->CreateAdd(origIntValue, constValue/*, "inc"*/);
  14280. resultValue = mModule->mBfIRBuilder->CreateIntToPtr(newIntValue, mModule->mBfIRBuilder->MapType(ptr.mType));
  14281. }
  14282. else
  14283. {
  14284. constValue = mModule->GetConstValue(1, ptr.mType);
  14285. if (!constValue)
  14286. {
  14287. numericFail = true;
  14288. break;
  14289. }
  14290. if ((ptr.mType->IsIntegral()) || (ptr.mType->IsEnum()) || (ptr.mType->IsFloat()))
  14291. {
  14292. resultValue = mModule->mBfIRBuilder->CreateAdd(origVal, constValue/*, "inc"*/);
  14293. }
  14294. else
  14295. {
  14296. numericFail = true;
  14297. break;
  14298. }
  14299. }
  14300. if ((propDef != NULL) && (!ptr.IsAddr()))
  14301. writeToProp = BfTypedValue(resultValue, ptr.mType);
  14302. else
  14303. mModule->mBfIRBuilder->CreateStore(resultValue, ptr.mValue, mIsVolatileReference);
  14304. if (unaryOp == BfUnaryOp_PostIncrement)
  14305. mResult = BfTypedValue(origVal, ptr.mType, false);
  14306. else
  14307. mResult = BfTypedValue(resultValue, ptr.mType, false);
  14308. }
  14309. break;
  14310. case BfUnaryOp_PostDecrement:
  14311. case BfUnaryOp_Decrement:
  14312. {
  14313. CheckResultForReading(mResult);
  14314. auto ptr = mResult;
  14315. //if ((propDef == NULL) && (!mModule->CheckModifyValue(ptr, opToken)))
  14316. //return;
  14317. if ((propDef == NULL) && (!CheckModifyResult(ptr, opToken, "decrement")))
  14318. return;
  14319. BfTypedValue origTypedVal = mModule->LoadValue(ptr, NULL, mIsVolatileReference);
  14320. BfIRValue origVal = origTypedVal.mValue;
  14321. BfIRValue constValue = mModule->GetConstValue(1, ptr.mType);
  14322. BfIRValue resultValue;
  14323. if (ptr.mType->IsPointer())
  14324. {
  14325. BfPointerType* ptrType = (BfPointerType*)ptr.mType;
  14326. BfType* intPtrType = mModule->GetPrimitiveType(BfTypeCode_IntPtr);
  14327. constValue = mModule->GetConstValue(ptrType->mElementType->GetStride(), intPtrType);
  14328. BfIRValue origIntValue = mModule->mBfIRBuilder->CreatePtrToInt(origVal, BfTypeCode_IntPtr);
  14329. BfIRValue newIntValue = mModule->mBfIRBuilder->CreateSub(origIntValue, constValue);
  14330. resultValue = mModule->mBfIRBuilder->CreateIntToPtr(newIntValue, mModule->mBfIRBuilder->MapType(ptr.mType));
  14331. }
  14332. else
  14333. {
  14334. BfIRValue constValue = mModule->GetConstValue(1, ptr.mType);
  14335. if (!constValue)
  14336. {
  14337. numericFail = true;
  14338. break;
  14339. }
  14340. if ((ptr.mType->IsIntegral()) || (ptr.mType->IsEnum()))
  14341. {
  14342. resultValue = mModule->mBfIRBuilder->CreateSub(origVal, constValue);
  14343. }
  14344. else if (ptr.mType->IsFloat())
  14345. {
  14346. resultValue = mModule->mBfIRBuilder->CreateSub(origVal, constValue);
  14347. }
  14348. else
  14349. {
  14350. numericFail = true;
  14351. break;
  14352. }
  14353. }
  14354. if ((propDef != NULL) && (!ptr.IsAddr()))
  14355. writeToProp = BfTypedValue(resultValue, ptr.mType);
  14356. else
  14357. mModule->mBfIRBuilder->CreateStore(resultValue, ptr.mValue, mIsVolatileReference);
  14358. if (unaryOp == BfUnaryOp_PostDecrement)
  14359. mResult = BfTypedValue(origVal, ptr.mType, false);
  14360. else
  14361. mResult = BfTypedValue(resultValue, ptr.mType, false);
  14362. }
  14363. break;
  14364. case BfUnaryOp_Ref:
  14365. case BfUnaryOp_Mut:
  14366. {
  14367. if (mAllowReadOnlyReference)
  14368. {
  14369. if (mResult.mKind == BfTypedValueKind_ReadOnlyAddr)
  14370. mResult.mKind = BfTypedValueKind_Addr;
  14371. }
  14372. CheckResultForReading(mResult);
  14373. if ((unaryOp == BfUnaryOp_Mut) && (!mResult.mType->IsComposite()) && (!mResult.mType->IsGenericParam()))
  14374. {
  14375. // Non-composite types are already mutable, leave them alone...
  14376. break;
  14377. }
  14378. if ((unaryOp != BfUnaryOp_Mut) || (mResult.mKind != BfTypedValueKind_MutableValue))
  14379. {
  14380. if (!CheckModifyResult(mResult, unaryOpExpr, StrFormat("use '%s' on", BfGetOpName(unaryOp)).c_str()))
  14381. {
  14382. // Just leave the non-ref version in mResult
  14383. return;
  14384. }
  14385. }
  14386. if ((mBfEvalExprFlags & BfEvalExprFlags_AllowRefExpr) == 0)
  14387. {
  14388. mModule->Fail(StrFormat("Invalid usage of '%s' expression", BfGetOpName(unaryOp)), opToken);
  14389. return;
  14390. }
  14391. ResolveGenericType();
  14392. mResult = BfTypedValue(mResult.mValue, mModule->CreateRefType(mResult.mType, (unaryOp == BfUnaryOp_Ref) ? BfRefType::RefKind_Ref : BfRefType::RefKind_Mut));
  14393. }
  14394. break;
  14395. case BfUnaryOp_Out:
  14396. {
  14397. if (!CheckModifyResult(mResult, unaryOpExpr, "use 'out' on"))
  14398. {
  14399. // Just leave the non-ref version in mResult
  14400. return;
  14401. }
  14402. if ((mBfEvalExprFlags & BfEvalExprFlags_AllowOutExpr) == 0)
  14403. {
  14404. mModule->Fail("Invalid usage of 'out' expression", opToken);
  14405. return;
  14406. }
  14407. MarkResultAssigned();
  14408. MarkResultUsed();
  14409. ResolveGenericType();
  14410. mResult = BfTypedValue(mResult.mValue, mModule->CreateRefType(mResult.mType, BfRefType::RefKind_Out));
  14411. }
  14412. break;
  14413. case BfUnaryOp_Params:
  14414. {
  14415. bool allowParams = (mBfEvalExprFlags & BfEvalExprFlags_AllowParamsExpr) != 0;
  14416. if (mResultLocalVar == NULL)
  14417. allowParams = false;
  14418. if (allowParams)
  14419. {
  14420. if (mResultLocalVar->mCompositeCount >= 0) // Delegate params
  14421. {
  14422. allowParams = true;
  14423. }
  14424. else
  14425. {
  14426. auto isValid = false;
  14427. auto genericTypeInst = mResult.mType->ToGenericTypeInstance();
  14428. if ((genericTypeInst != NULL) && (genericTypeInst->mTypeDef == mModule->mCompiler->mSpanTypeDef))
  14429. isValid = true;
  14430. else if (mResult.mType->IsArray())
  14431. isValid = true;
  14432. if (!isValid)
  14433. {
  14434. mModule->Fail(StrFormat("A 'params' expression cannot be used on type '%s'", mModule->TypeToString(mResult.mType).c_str()), opToken);
  14435. }
  14436. }
  14437. }
  14438. if (allowParams)
  14439. {
  14440. mResult = mModule->LoadValue(mResult);
  14441. if (mResult.IsSplat())
  14442. mResult.mKind = BfTypedValueKind_ParamsSplat;
  14443. else
  14444. mResult.mKind = BfTypedValueKind_Params;
  14445. }
  14446. else
  14447. {
  14448. mModule->Fail("Illegal use of 'params' expression", opToken);
  14449. }
  14450. }
  14451. break;
  14452. default:
  14453. mModule->Fail("INTERNAL ERROR: Unhandled unary operator", unaryOpExpr);
  14454. break;
  14455. }
  14456. if (numericFail)
  14457. {
  14458. mModule->Fail("Operator can only be used on numeric types", opToken);
  14459. mResult = BfTypedValue();
  14460. }
  14461. if (writeToProp)
  14462. {
  14463. auto setMethod = GetPropertyMethodDef(propDef, BfMethodType_PropertySetter, mPropCheckedKind);
  14464. if (setMethod == NULL)
  14465. {
  14466. mModule->Fail("Property has no setter", propSrc);
  14467. return;
  14468. }
  14469. auto methodInstance = GetPropertyMethodInstance(setMethod);
  14470. if (!methodInstance.mFunc)
  14471. return;
  14472. if (propSrc != NULL)
  14473. mModule->UpdateExprSrcPos(propSrc);
  14474. SizedArray<BfIRValue, 4> args;
  14475. if (!setMethod->mIsStatic)
  14476. PushThis(propSrc, propTarget, methodInstance.mMethodInstance, args);
  14477. //args.push_back(propTarget.mValue);
  14478. for (int paramIdx = 0; paramIdx < (int)indexerVals.size(); paramIdx++)
  14479. {
  14480. auto val = mModule->Cast(propSrc, indexerVals[paramIdx].mTypedValue, methodInstance.mMethodInstance->GetParamType(paramIdx));
  14481. if (!val)
  14482. return;
  14483. PushArg(val, args);
  14484. }
  14485. PushArg(writeToProp, args);
  14486. CreateCall(methodInstance.mMethodInstance, methodInstance.mFunc, false, args);
  14487. }
  14488. }
  14489. void BfExprEvaluator::PerformBinaryOperation(BfExpression* leftExpression, BfExpression* rightExpression, BfBinaryOp binaryOp, BfTokenNode* opToken, BfBinOpFlags flags, BfTypedValue leftValue)
  14490. {
  14491. BfTypedValue rightValue;
  14492. if (rightExpression == NULL)
  14493. {
  14494. mModule->AssertErrorState();
  14495. return;
  14496. }
  14497. if (!leftValue)
  14498. {
  14499. if (!rightValue)
  14500. mModule->CreateValueFromExpression(rightExpression);
  14501. return;
  14502. }
  14503. if (leftValue.mType->IsRef())
  14504. leftValue.mType = leftValue.mType->GetUnderlyingType();
  14505. if ((binaryOp == BfBinaryOp_ConditionalAnd) || (binaryOp == BfBinaryOp_ConditionalOr))
  14506. {
  14507. if (mModule->mCurMethodState->mDeferredLocalAssignData != NULL)
  14508. mModule->mCurMethodState->mDeferredLocalAssignData->BreakExtendChain();
  14509. bool isAnd = binaryOp == BfBinaryOp_ConditionalAnd;
  14510. auto boolType = mModule->GetPrimitiveType(BfTypeCode_Boolean);
  14511. leftValue = mModule->Cast(leftExpression, leftValue, boolType);
  14512. if (!leftValue)
  14513. {
  14514. mModule->CreateValueFromExpression(rightExpression);
  14515. return;
  14516. }
  14517. auto prevBB = mModule->mBfIRBuilder->GetInsertBlock();
  14518. SetAndRestoreValue<bool> prevInCondBlock(mModule->mCurMethodState->mInConditionalBlock, true);
  14519. // The RHS is not guaranteed to be executed
  14520. if ((mModule->mCurMethodState->mDeferredLocalAssignData != NULL) &&
  14521. (mModule->mCurMethodState->mDeferredLocalAssignData->mIsIfCondition))
  14522. mModule->mCurMethodState->mDeferredLocalAssignData->mIfMayBeSkipped = true;
  14523. if (isAnd)
  14524. {
  14525. bool isConstBranch = false;
  14526. bool constResult = false;
  14527. if (leftValue.mValue.IsConst())
  14528. {
  14529. auto constValue = mModule->mBfIRBuilder->GetConstant(leftValue.mValue);
  14530. if (constValue->mTypeCode == BfTypeCode_Boolean)
  14531. {
  14532. isConstBranch = true;
  14533. constResult = constValue->mBool;
  14534. }
  14535. }
  14536. if (isConstBranch)
  14537. {
  14538. if ((constResult) || (HasVariableDeclaration(rightExpression)))
  14539. {
  14540. // Only right side
  14541. rightValue = mModule->CreateValueFromExpression(rightExpression, boolType);
  14542. mResult = rightValue;
  14543. }
  14544. else
  14545. {
  14546. // Always false
  14547. SetAndRestoreValue<bool> prevIgnoreWrites(mModule->mBfIRBuilder->mIgnoreWrites, true);
  14548. rightValue = mModule->CreateValueFromExpression(rightExpression, boolType);
  14549. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConst(BfTypeCode_Boolean, 0), boolType);
  14550. }
  14551. }
  14552. else
  14553. {
  14554. auto rhsBB = mModule->mBfIRBuilder->CreateBlock("land.rhs");
  14555. auto endBB = mModule->mBfIRBuilder->CreateBlock("land.end");
  14556. // This makes any 'scope' allocs be dyn since we aren't sure if this will be short-circuited
  14557. SetAndRestoreValue<bool> prevIsConditional(mModule->mCurMethodState->mCurScope->mIsConditional, true);
  14558. mModule->mBfIRBuilder->CreateCondBr(leftValue.mValue, rhsBB, endBB);
  14559. mModule->AddBasicBlock(rhsBB);
  14560. rightValue = mModule->CreateValueFromExpression(rightExpression, boolType);
  14561. mModule->mBfIRBuilder->CreateBr(endBB);
  14562. auto endRhsBB = mModule->mBfIRBuilder->GetInsertBlock();
  14563. mModule->AddBasicBlock(endBB);
  14564. auto phi = mModule->mBfIRBuilder->CreatePhi(mModule->mBfIRBuilder->MapType(boolType), 2);
  14565. mModule->mBfIRBuilder->AddPhiIncoming(phi, mModule->GetConstValue(0, boolType), prevBB);
  14566. if (rightValue)
  14567. mModule->mBfIRBuilder->AddPhiIncoming(phi, rightValue.mValue, endRhsBB);
  14568. mResult = BfTypedValue(phi, boolType);
  14569. }
  14570. }
  14571. else
  14572. {
  14573. // Put variables in here into a 'possibly assigned' but never commit it.
  14574. // Because if we had "if ((Get(out a)) || (GetOther(out a))" then the LHS would already set it as defined, so
  14575. // the RHS is inconsequential
  14576. BfDeferredLocalAssignData deferredLocalAssignData;
  14577. deferredLocalAssignData.ExtendFrom(mModule->mCurMethodState->mDeferredLocalAssignData, false);
  14578. deferredLocalAssignData.mVarIdBarrier = mModule->mCurMethodState->GetRootMethodState()->mCurLocalVarId;
  14579. SetAndRestoreValue<BfDeferredLocalAssignData*> prevDLA(mModule->mCurMethodState->mDeferredLocalAssignData, &deferredLocalAssignData);
  14580. bool isConstBranch = false;
  14581. bool constResult = false;
  14582. if (leftValue.mValue.IsConst())
  14583. {
  14584. auto constValue = mModule->mBfIRBuilder->GetConstant(leftValue.mValue);
  14585. if (constValue->mTypeCode == BfTypeCode_Boolean)
  14586. {
  14587. isConstBranch = true;
  14588. constResult = constValue->mBool;
  14589. }
  14590. }
  14591. if (isConstBranch)
  14592. {
  14593. if ((constResult) && (!HasVariableDeclaration(rightExpression)))
  14594. {
  14595. // Always true
  14596. SetAndRestoreValue<bool> prevIgnoreWrites(mModule->mBfIRBuilder->mIgnoreWrites, true);
  14597. rightValue = mModule->CreateValueFromExpression(rightExpression, boolType);
  14598. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConst(BfTypeCode_Boolean, 1), boolType);
  14599. }
  14600. else
  14601. {
  14602. // Only right side
  14603. rightValue = mModule->CreateValueFromExpression(rightExpression, boolType);
  14604. mResult = rightValue;
  14605. }
  14606. }
  14607. else
  14608. {
  14609. auto rhsBB = mModule->mBfIRBuilder->CreateBlock("lor.rhs");
  14610. auto endBB = mModule->mBfIRBuilder->CreateBlock("lor.end");
  14611. // This makes any 'scope' allocs be dyn since we aren't sure if this will be short-circuited
  14612. SetAndRestoreValue<bool> prevIsConditional(mModule->mCurMethodState->mCurScope->mIsConditional, true);
  14613. mModule->mBfIRBuilder->CreateCondBr(leftValue.mValue, endBB, rhsBB);
  14614. mModule->AddBasicBlock(rhsBB);
  14615. rightValue = mModule->CreateValueFromExpression(rightExpression, boolType);
  14616. mModule->mBfIRBuilder->CreateBr(endBB);
  14617. auto endRhsBB = mModule->mBfIRBuilder->GetInsertBlock();
  14618. mModule->AddBasicBlock(endBB);
  14619. auto phi = mModule->mBfIRBuilder->CreatePhi(mModule->mBfIRBuilder->MapType(boolType), 2);
  14620. mModule->mBfIRBuilder->AddPhiIncoming(phi, mModule->GetConstValue(1, boolType), prevBB);
  14621. if (rightValue)
  14622. mModule->mBfIRBuilder->AddPhiIncoming(phi, rightValue.mValue, endRhsBB);
  14623. mResult = BfTypedValue(phi, boolType);
  14624. }
  14625. }
  14626. return;
  14627. }
  14628. BfType* wantType = leftValue.mType;
  14629. if ((binaryOp == BfBinaryOp_LeftShift) || (binaryOp == BfBinaryOp_RightShift))
  14630. wantType = NULL; // Don't presume
  14631. rightValue = mModule->CreateValueFromExpression(rightExpression, wantType, BfEvalExprFlags_NoCast);
  14632. if ((!leftValue) || (!rightValue))
  14633. return;
  14634. PerformBinaryOperation(leftExpression, rightExpression, binaryOp, opToken, flags, leftValue, rightValue);
  14635. }
  14636. void BfExprEvaluator::PerformBinaryOperation(BfExpression* leftExpression, BfExpression* rightExpression, BfBinaryOp binaryOp, BfTokenNode* opToken, BfBinOpFlags flags)
  14637. {
  14638. BfTypedValue leftValue;
  14639. if (leftExpression != NULL)
  14640. {
  14641. leftValue = mModule->CreateValueFromExpression(leftExpression, mExpectingType, (BfEvalExprFlags)(BfEvalExprFlags_NoCast | BfEvalExprFlags_AllowIntUnknown));
  14642. }
  14643. return PerformBinaryOperation(leftExpression, rightExpression, binaryOp, opToken, flags, leftValue);
  14644. }
  14645. bool BfExprEvaluator::CheckConstCompare(BfBinaryOp binaryOp, BfAstNode* opToken, const BfTypedValue& leftValue, const BfTypedValue& rightValue)
  14646. {
  14647. if ((binaryOp < BfBinaryOp_Equality) || (binaryOp > BfBinaryOp_LessThanOrEqual))
  14648. return false;
  14649. // LHS is expected to be a value and RHS is expected to be a const
  14650. if (!leftValue.mType->IsIntegral())
  14651. return false;
  14652. BF_ASSERT(rightValue.mValue.IsConst());
  14653. auto rightConst = mModule->mBfIRBuilder->GetConstant(rightValue.mValue);
  14654. if (!mModule->mBfIRBuilder->IsInt(rightConst->mTypeCode))
  14655. return false;
  14656. BfType* checkType = leftValue.mType;
  14657. if (checkType->IsTypedPrimitive())
  14658. checkType = checkType->GetUnderlyingType();
  14659. if (!checkType->IsPrimitiveType())
  14660. return false;
  14661. BfTypeCode typeCode = ((BfPrimitiveType*)checkType)->mTypeDef->mTypeCode;
  14662. int64 minValue = 0;
  14663. int64 maxValue = 0;
  14664. switch (typeCode)
  14665. {
  14666. case BfTypeCode_Int8:
  14667. minValue = -0x80;
  14668. maxValue = 0x7F;
  14669. break;
  14670. case BfTypeCode_Int16:
  14671. minValue = -0x8000;
  14672. maxValue = 0x7FFF;
  14673. break;
  14674. case BfTypeCode_Int32:
  14675. minValue = -0x80000000LL;
  14676. maxValue = 0x7FFFFFFF;
  14677. break;
  14678. case BfTypeCode_Int64:
  14679. minValue = -0x8000000000000000LL;
  14680. maxValue = 0x7FFFFFFFFFFFFFFFLL;
  14681. break;
  14682. case BfTypeCode_UInt8:
  14683. maxValue = 0xFF;
  14684. break;
  14685. case BfTypeCode_UInt16:
  14686. maxValue = 0xFFFF;
  14687. break;
  14688. case BfTypeCode_UInt32:
  14689. maxValue = 0xFFFFFFFF;
  14690. break;
  14691. default:
  14692. return false;
  14693. }
  14694. int constResult = -1;
  14695. if (typeCode == BfTypeCode_UInt64)
  14696. {
  14697. switch (binaryOp)
  14698. {
  14699. case BfBinaryOp_Equality:
  14700. if (rightConst->mInt64 < minValue)
  14701. constResult = 0;
  14702. break;
  14703. case BfBinaryOp_InEquality:
  14704. if (rightConst->mInt64 < minValue)
  14705. constResult = 1;
  14706. break;
  14707. case BfBinaryOp_LessThan:
  14708. if (rightConst->mInt64 <= minValue)
  14709. constResult = 0;
  14710. break;
  14711. case BfBinaryOp_LessThanOrEqual:
  14712. if (rightConst->mInt64 < minValue)
  14713. constResult = 0;
  14714. break;
  14715. default: break;
  14716. }
  14717. return false;
  14718. }
  14719. else
  14720. {
  14721. switch (binaryOp)
  14722. {
  14723. case BfBinaryOp_Equality:
  14724. if (rightConst->mInt64 < minValue)
  14725. constResult = 0;
  14726. else if (rightConst->mInt64 > maxValue)
  14727. constResult = 0;
  14728. break;
  14729. case BfBinaryOp_InEquality:
  14730. if (rightConst->mInt64 < minValue)
  14731. constResult = 1;
  14732. else if (rightConst->mInt64 > maxValue)
  14733. constResult = 1;
  14734. break;
  14735. case BfBinaryOp_LessThan:
  14736. if (rightConst->mInt64 <= minValue)
  14737. constResult = 0;
  14738. else if (rightConst->mInt64 > maxValue)
  14739. constResult = 1;
  14740. break;
  14741. case BfBinaryOp_LessThanOrEqual:
  14742. if (rightConst->mInt64 < minValue)
  14743. constResult = 0;
  14744. else if (rightConst->mInt64 >= maxValue)
  14745. constResult = 1;
  14746. break;
  14747. case BfBinaryOp_GreaterThan:
  14748. if (rightConst->mInt64 >= maxValue)
  14749. constResult = 0;
  14750. else if (rightConst->mInt64 < minValue)
  14751. constResult = 1;
  14752. break;
  14753. case BfBinaryOp_GreaterThanOrEqual:
  14754. if (rightConst->mInt64 > maxValue)
  14755. constResult = 0;
  14756. else if (rightConst->mInt64 <= minValue)
  14757. constResult = 1;
  14758. break;
  14759. default: break;
  14760. }
  14761. }
  14762. if (constResult == 0)
  14763. {
  14764. mModule->Warn(0, "The result of this operation is always 'false'", opToken);
  14765. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConst(BfTypeCode_Boolean, 1), mModule->GetPrimitiveType(BfTypeCode_Boolean));
  14766. return true;
  14767. }
  14768. else if (constResult == 1)
  14769. {
  14770. mModule->Warn(0, "The result of this operation is always 'true'", opToken);
  14771. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConst(BfTypeCode_Boolean, 1), mModule->GetPrimitiveType(BfTypeCode_Boolean));
  14772. return true;
  14773. }
  14774. return false;
  14775. }
  14776. void BfExprEvaluator::PerformBinaryOperation(BfAstNode* leftExpression, BfAstNode* rightExpression, BfBinaryOp binaryOp, BfAstNode* opToken, BfBinOpFlags flags, BfTypedValue leftValue, BfTypedValue rightValue)
  14777. {
  14778. bool noClassify = (flags & BfBinOpFlag_NoClassify) != 0;
  14779. bool forceLeftType = (flags & BfBinOpFlag_ForceLeftType) != 0;
  14780. if ((rightValue.mValue.IsConst()) && (!leftValue.mValue.IsConst()))
  14781. {
  14782. if (CheckConstCompare(binaryOp, opToken, leftValue, rightValue))
  14783. return;
  14784. }
  14785. else if ((leftValue.mValue.IsConst()) && (!rightValue.mValue.IsConst()))
  14786. {
  14787. if (CheckConstCompare(BfGetOppositeBinaryOp(binaryOp), opToken, rightValue, leftValue))
  14788. return;
  14789. }
  14790. if ((binaryOp == BfBinaryOp_NullCoalesce) && ((leftValue.mType->IsPointer()) || (leftValue.mType->IsObject())))
  14791. {
  14792. auto prevBB = mModule->mBfIRBuilder->GetInsertBlock();
  14793. auto rhsBB = mModule->mBfIRBuilder->CreateBlock("nullc.rhs");
  14794. auto endBB = mModule->mBfIRBuilder->CreateBlock("nullc.end");
  14795. auto isNull = mModule->mBfIRBuilder->CreateIsNull(leftValue.mValue);
  14796. mModule->mBfIRBuilder->CreateCondBr(isNull, rhsBB, endBB);
  14797. mModule->AddBasicBlock(rhsBB);
  14798. if (!rightValue)
  14799. {
  14800. mModule->AssertErrorState();
  14801. return;
  14802. }
  14803. else
  14804. {
  14805. auto rightToLeftValue = mModule->CastToValue(rightExpression, rightValue, leftValue.mType, BfCastFlags_SilentFail);
  14806. if (rightToLeftValue)
  14807. {
  14808. rightValue = BfTypedValue(rightToLeftValue, leftValue.mType);
  14809. }
  14810. else
  14811. {
  14812. auto leftToRightValue = mModule->CastToValue(leftExpression, leftValue, rightValue.mType, BfCastFlags_SilentFail);
  14813. if (leftToRightValue)
  14814. {
  14815. leftValue = BfTypedValue(leftToRightValue, rightValue.mType);
  14816. }
  14817. else
  14818. {
  14819. // Note: Annoying trigraph split for '??'
  14820. mModule->Fail(StrFormat("Operator '?" "?' cannot be applied to operands of type '%s' and '%s'",
  14821. mModule->TypeToString(leftValue.mType).c_str(), mModule->TypeToString(rightValue.mType).c_str()), opToken);
  14822. leftValue = mModule->GetDefaultTypedValue(rightValue.mType);
  14823. }
  14824. }
  14825. }
  14826. mModule->mBfIRBuilder->CreateBr(endBB);
  14827. auto endRhsBB = mModule->mBfIRBuilder->GetInsertBlock();
  14828. mModule->AddBasicBlock(endBB);
  14829. auto phi = mModule->mBfIRBuilder->CreatePhi(mModule->mBfIRBuilder->MapType(leftValue.mType), 2);
  14830. mModule->mBfIRBuilder->AddPhiIncoming(phi, leftValue.mValue, prevBB);
  14831. mModule->mBfIRBuilder->AddPhiIncoming(phi, rightValue.mValue, endRhsBB);
  14832. mResult = BfTypedValue(phi, leftValue.mType);
  14833. return;
  14834. }
  14835. if ((binaryOp == BfBinaryOp_LeftShift) || (binaryOp == BfBinaryOp_RightShift))
  14836. {
  14837. forceLeftType = true;
  14838. }
  14839. if (rightValue.mType->IsRef())
  14840. rightValue.mType = rightValue.mType->GetUnderlyingType();
  14841. mModule->FixIntUnknown(leftValue, rightValue);
  14842. // Prefer floats, prefer chars
  14843. int leftCompareSize = leftValue.mType->mSize;
  14844. if (leftValue.mType->IsFloat())
  14845. leftCompareSize += 0x10;
  14846. if (leftValue.mType->IsChar())
  14847. leftCompareSize += 0x100;
  14848. if (!leftValue.mType->IsPrimitiveType())
  14849. leftCompareSize += 0x1000;
  14850. int rightCompareSize = rightValue.mType->mSize;
  14851. if (rightValue.mType->IsFloat())
  14852. rightCompareSize += 0x10;
  14853. if (rightValue.mType->IsChar())
  14854. rightCompareSize += 0x100;
  14855. if (!rightValue.mType->IsPrimitiveType())
  14856. rightCompareSize += 0x1000;
  14857. if ((leftValue.mType->IsTypeInstance()) && (rightValue.mType->IsTypeInstance()))
  14858. {
  14859. int leftInheritDepth = leftValue.mType->ToTypeInstance()->mInheritDepth;
  14860. int rightInheritDepth = rightValue.mType->ToTypeInstance()->mInheritDepth;
  14861. if (leftInheritDepth < rightInheritDepth)
  14862. {
  14863. // If both are type instances then choose the type with the lowest inherit depth
  14864. // so we will choose the base type when applicable
  14865. forceLeftType = true;
  14866. }
  14867. }
  14868. auto resultType = leftValue.mType;
  14869. if (!forceLeftType)
  14870. {
  14871. bool handled = false;
  14872. // If one of these is a constant that can be converted into a smaller type, then do that
  14873. if (rightValue.mValue.IsConst())
  14874. {
  14875. if (mModule->CanImplicitlyCast(rightValue, leftValue.mType))
  14876. {
  14877. resultType = leftValue.mType;
  14878. handled = true;
  14879. }
  14880. }
  14881. // If left is an IntUnknown, allow the right to inform the type
  14882. if (leftValue.mType->IsIntUnknown())
  14883. {
  14884. if (leftValue.mValue.IsConst())
  14885. {
  14886. if (mModule->CanImplicitlyCast(leftValue, rightValue.mType))
  14887. {
  14888. resultType = rightValue.mType;
  14889. handled = true;
  14890. }
  14891. }
  14892. }
  14893. if (!handled)
  14894. {
  14895. if ((resultType->IsNull()) ||
  14896. (rightCompareSize > leftCompareSize) ||
  14897. (((rightCompareSize == leftCompareSize) && (!rightValue.mType->IsSigned()))) ||
  14898. (rightValue.mType->IsTypedPrimitive()))
  14899. {
  14900. // Select the type with the "most information"
  14901. if (!rightValue.mType->IsNull())
  14902. resultType = rightValue.mType;
  14903. }
  14904. if ((!resultType->IsPointer()) && (rightValue.mType->IsPointer()))
  14905. resultType = rightValue.mType;
  14906. }
  14907. }
  14908. bool explicitCast = false;
  14909. BfTypedValue* resultTypedValue;
  14910. BfTypedValue* otherTypedValue;
  14911. BfType* otherType;
  14912. BfAstNode* resultTypeSrc;
  14913. BfAstNode* otherTypeSrc;
  14914. if (resultType == leftValue.mType)
  14915. {
  14916. resultTypedValue = &leftValue;
  14917. resultTypeSrc = leftExpression;
  14918. otherTypedValue = &rightValue;
  14919. otherTypeSrc = rightExpression;
  14920. otherType = otherTypedValue->mType;
  14921. }
  14922. else
  14923. {
  14924. resultTypedValue = &rightValue;
  14925. resultTypeSrc = rightExpression;
  14926. otherTypedValue = &leftValue;
  14927. otherTypeSrc = leftExpression;
  14928. otherType = otherTypedValue->mType;
  14929. }
  14930. auto _OpFail = [&]()
  14931. {
  14932. if ((rightValue.mType != NULL) && (leftValue.mType != NULL))
  14933. {
  14934. if (rightValue.mType != leftValue.mType)
  14935. mModule->Fail(StrFormat("Cannot perform binary operation '%s' between types '%s' and '%s'",
  14936. BfGetOpName(binaryOp), mModule->TypeToString(leftValue.mType).c_str(), mModule->TypeToString(rightValue.mType).c_str()), opToken);
  14937. else
  14938. mModule->Fail(StrFormat("Cannot perform binary operation '%s' between two instances of type '%s'",
  14939. BfGetOpName(binaryOp), mModule->TypeToString(leftValue.mType).c_str()), opToken);
  14940. }
  14941. else
  14942. mModule->Fail(StrFormat("Cannot perform binary operation '%s'", BfGetOpName(binaryOp)), opToken);
  14943. };
  14944. // This case fixes cases like "c == 0" where "0" is technically an int but can be reduced
  14945. if ((binaryOp == BfBinaryOp_Equality) || (binaryOp == BfBinaryOp_InEquality))
  14946. {
  14947. if ((resultType != otherType) && (resultTypedValue->mValue.IsConst()) && (mModule->CanImplicitlyCast(*resultTypedValue, otherType)))
  14948. {
  14949. std::swap(resultTypedValue, otherTypedValue);
  14950. std::swap(resultTypeSrc, otherTypeSrc);
  14951. std::swap(resultType, otherType);
  14952. }
  14953. }
  14954. BfIRValue convLeftValue;
  14955. BfIRValue convRightValue;
  14956. if ((resultType->IsVar()) || (otherType->IsVar()))
  14957. {
  14958. mResult = BfTypedValue(mModule->GetDefaultValue(resultType), mModule->GetPrimitiveType(BfTypeCode_Var));
  14959. return;
  14960. }
  14961. if ((otherType->IsNull()) && ((binaryOp == BfBinaryOp_Equality) || (binaryOp == BfBinaryOp_InEquality)))
  14962. {
  14963. bool isEquality = (binaryOp == BfBinaryOp_Equality);
  14964. if ((resultType->IsValueType()) && (!resultType->IsFunction()))
  14965. {
  14966. auto boolType = mModule->GetPrimitiveType(BfTypeCode_Boolean);
  14967. if (resultType->IsNullable())
  14968. {
  14969. auto elementType = resultType->GetUnderlyingType();
  14970. if (elementType->IsValuelessType())
  14971. {
  14972. mModule->mBfIRBuilder->PopulateType(resultType);
  14973. BfTypedValue nullableTypedVale = mModule->MakeAddressable(*resultTypedValue);
  14974. BfIRValue hasValuePtr = mModule->mBfIRBuilder->CreateInBoundsGEP(nullableTypedVale.mValue, 0, 1);
  14975. BfIRValue hasValueValue = mModule->mBfIRBuilder->CreateLoad(hasValuePtr);
  14976. if (isEquality)
  14977. hasValueValue = mModule->mBfIRBuilder->CreateNot(hasValueValue);
  14978. mResult = BfTypedValue(hasValueValue, boolType);
  14979. }
  14980. else
  14981. {
  14982. mModule->mBfIRBuilder->PopulateType(resultType);
  14983. BfTypedValue nullableTypedVale = mModule->MakeAddressable(*resultTypedValue);
  14984. BfIRValue hasValuePtr = mModule->mBfIRBuilder->CreateInBoundsGEP(nullableTypedVale.mValue, 0, 2);
  14985. BfIRValue hasValueValue = mModule->mBfIRBuilder->CreateLoad(hasValuePtr);
  14986. if (isEquality)
  14987. hasValueValue = mModule->mBfIRBuilder->CreateNot(hasValueValue);
  14988. mResult = BfTypedValue(hasValueValue, boolType);
  14989. }
  14990. return;
  14991. }
  14992. if (resultType->IsNull())
  14993. {
  14994. // Null always equals null
  14995. mResult = BfTypedValue(mModule->GetConstValue(isEquality ? 1 : 0, boolType), boolType);
  14996. return;
  14997. }
  14998. if (!mModule->IsInSpecializedSection())
  14999. {
  15000. //CS0472: The result of the expression is always 'true' since a value of type 'int' is never equal to 'null' of type '<null>'
  15001. mModule->Warn(BfWarning_CS0472_ValueTypeNullCompare,
  15002. StrFormat("The result of the expression is always '%s' since a value of type '%s' can never be null",
  15003. isEquality ? "false" : "true", mModule->TypeToString(resultType).c_str()), otherTypeSrc);
  15004. }
  15005. // Valuetypes never equal null
  15006. mResult = BfTypedValue(mModule->GetConstValue(isEquality ? 0 : 1, boolType), boolType);
  15007. return;
  15008. }
  15009. }
  15010. if ((leftValue.mType->IsTypeInstance()) || (leftValue.mType->IsGenericParam()) ||
  15011. (rightValue.mType->IsTypeInstance()) || (rightValue.mType->IsGenericParam()))
  15012. {
  15013. // As an optimization, we don't call user operator overloads for null checks
  15014. bool skipOpOverload = false;
  15015. if ((binaryOp == BfBinaryOp_Equality) || (binaryOp == BfBinaryOp_InEquality))
  15016. {
  15017. auto leftConstant = mModule->mBfIRBuilder->GetConstant(leftValue.mValue);
  15018. auto rightConstant = mModule->mBfIRBuilder->GetConstant(rightValue.mValue);
  15019. if ((leftConstant != NULL) && (leftConstant->IsNull()))
  15020. skipOpOverload = true;
  15021. if ((rightConstant != NULL) && (rightConstant->IsNull()))
  15022. skipOpOverload = true;
  15023. }
  15024. if (!skipOpOverload)
  15025. {
  15026. BfBinaryOp findBinaryOp = binaryOp;
  15027. bool isComparison = (binaryOp >= BfBinaryOp_Equality) && (binaryOp <= BfBinaryOp_LessThanOrEqual);
  15028. for (int pass = 0; pass < 2; pass++)
  15029. {
  15030. bool foundOp = false;
  15031. SizedArray<BfResolvedArg, 2> args;
  15032. BfResolvedArg leftArg;
  15033. leftArg.mExpression = leftExpression;
  15034. leftArg.mTypedValue = leftValue;
  15035. BfResolvedArg rightArg;
  15036. rightArg.mExpression = rightExpression;
  15037. rightArg.mTypedValue = rightValue;
  15038. if (pass == 0)
  15039. {
  15040. args.push_back(leftArg);
  15041. args.push_back(rightArg);
  15042. }
  15043. else
  15044. {
  15045. args.push_back(rightArg);
  15046. args.push_back(leftArg);
  15047. }
  15048. BfMethodMatcher methodMatcher(opToken, mModule, "", args, NULL);
  15049. BfBaseClassWalker baseClassWalker(leftValue.mType, rightValue.mType, mModule);
  15050. bool invertResult = false;
  15051. BfBinaryOp oppositeBinaryOp = BfGetOppositeBinaryOp(findBinaryOp);
  15052. while (true)
  15053. {
  15054. auto entry = baseClassWalker.Next();
  15055. auto checkType = entry.mTypeInstance;
  15056. if (checkType == NULL)
  15057. break;
  15058. bool foundExactMatch = false;
  15059. Array<BfMethodDef*> oppositeOperatorDefs;
  15060. for (auto operatorDef : checkType->mTypeDef->mOperators)
  15061. {
  15062. bool allowOp = operatorDef->mOperatorDeclaration->mBinOp == findBinaryOp;
  15063. if ((isComparison) && (operatorDef->mOperatorDeclaration->mBinOp == BfBinaryOp_Compare))
  15064. allowOp = true;
  15065. if (allowOp)
  15066. {
  15067. foundOp = true;
  15068. if (!methodMatcher.IsMemberAccessible(checkType, operatorDef->mDeclaringType))
  15069. continue;
  15070. if (methodMatcher.CheckMethod(checkType, operatorDef, false))
  15071. {
  15072. methodMatcher.mSelfType = entry.mSrcType;
  15073. if (operatorDef->mOperatorDeclaration->mBinOp == findBinaryOp)
  15074. foundExactMatch = true;
  15075. }
  15076. }
  15077. else if (operatorDef->mOperatorDeclaration->mBinOp == oppositeBinaryOp)
  15078. oppositeOperatorDefs.Add(operatorDef);
  15079. }
  15080. if (((methodMatcher.mBestMethodDef == NULL) || (!foundExactMatch)) && (!oppositeOperatorDefs.IsEmpty()))
  15081. {
  15082. foundOp = true;
  15083. for (auto oppositeOperatorDef : oppositeOperatorDefs)
  15084. {
  15085. if (methodMatcher.CheckMethod(checkType, oppositeOperatorDef, false))
  15086. methodMatcher.mSelfType = entry.mSrcType;
  15087. }
  15088. }
  15089. }
  15090. if (methodMatcher.mBestMethodDef != NULL)
  15091. {
  15092. methodMatcher.FlushAmbiguityError();
  15093. auto matchedOp = ((BfOperatorDeclaration*)methodMatcher.mBestMethodDef->mMethodDeclaration)->mBinOp;
  15094. bool invertResult = matchedOp == oppositeBinaryOp;
  15095. auto methodDef = methodMatcher.mBestMethodDef;
  15096. auto autoComplete = GetAutoComplete();
  15097. if ((autoComplete != NULL) && (autoComplete->IsAutocompleteNode(opToken)))
  15098. {
  15099. auto operatorDecl = BfNodeDynCast<BfOperatorDeclaration>(methodDef->mMethodDeclaration);
  15100. if ((operatorDecl != NULL) && (operatorDecl->mOpTypeToken != NULL))
  15101. autoComplete->SetDefinitionLocation(operatorDecl->mOpTypeToken);
  15102. }
  15103. if (opToken != NULL)
  15104. {
  15105. if ((opToken->IsA<BfTokenNode>()) && (!noClassify) && (!baseClassWalker.mMayBeFromInterface))
  15106. mModule->SetElementType(opToken, BfSourceElementType_Method);
  15107. }
  15108. mResult = CreateCall(&methodMatcher, BfTypedValue());
  15109. if ((mResult.mType != NULL) && (methodMatcher.mSelfType != NULL) && (mResult.mType->IsSelf()))
  15110. {
  15111. BF_ASSERT(mModule->IsInGeneric());
  15112. mResult = mModule->GetDefaultTypedValue(methodMatcher.mSelfType);
  15113. }
  15114. if ((invertResult) && (mResult.mType == mModule->GetPrimitiveType(BfTypeCode_Boolean)))
  15115. mResult.mValue = mModule->mBfIRBuilder->CreateNot(mResult.mValue);
  15116. if (pass == 1)
  15117. {
  15118. if (findBinaryOp == BfBinaryOp_Compare)
  15119. {
  15120. mResult = mModule->LoadValue(mResult);
  15121. if (mResult.mType->IsIntegral())
  15122. mResult.mValue = mModule->mBfIRBuilder->CreateNeg(mResult.mValue);
  15123. }
  15124. }
  15125. if ((isComparison) && (matchedOp == BfBinaryOp_Compare))
  15126. {
  15127. auto intType = mModule->GetPrimitiveType(BfTypeCode_IntPtr);
  15128. mResult = mModule->LoadValue(mResult);
  15129. if (mResult.mType != intType)
  15130. mResult = mModule->GetDefaultTypedValue(intType);
  15131. auto zeroVal = mModule->mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, 0);
  15132. auto useBinaryOp = binaryOp;
  15133. if (pass == 1)
  15134. useBinaryOp = BfGetFlippedBinaryOp(useBinaryOp);
  15135. auto boolType = mModule->GetPrimitiveType(BfTypeCode_Boolean);
  15136. switch (useBinaryOp)
  15137. {
  15138. case BfBinaryOp_Equality:
  15139. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateCmpEQ(mResult.mValue, zeroVal), boolType);
  15140. break;
  15141. case BfBinaryOp_InEquality:
  15142. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateCmpNE(mResult.mValue, zeroVal), boolType);
  15143. break;
  15144. case BfBinaryOp_GreaterThan:
  15145. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateCmpGT(mResult.mValue, zeroVal, true), boolType);
  15146. break;
  15147. case BfBinaryOp_LessThan:
  15148. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateCmpLT(mResult.mValue, zeroVal, true), boolType);
  15149. break;
  15150. case BfBinaryOp_GreaterThanOrEqual:
  15151. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateCmpGTE(mResult.mValue, zeroVal, true), boolType);
  15152. break;
  15153. case BfBinaryOp_LessThanOrEqual:
  15154. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateCmpLTE(mResult.mValue, zeroVal, true), boolType);
  15155. break;
  15156. default: break;
  15157. }
  15158. }
  15159. return;
  15160. }
  15161. // Check method generic constraints
  15162. if ((mModule->mCurMethodInstance != NULL) && (mModule->mCurMethodInstance->mIsUnspecialized) && (mModule->mCurMethodInstance->mMethodInfoEx != NULL))
  15163. {
  15164. for (int genericParamIdx = 0; genericParamIdx < mModule->mCurMethodInstance->mMethodInfoEx->mGenericParams.size(); genericParamIdx++)
  15165. {
  15166. auto genericParam = mModule->mCurMethodInstance->mMethodInfoEx->mGenericParams[genericParamIdx];
  15167. for (auto& opConstraint : genericParam->mOperatorConstraints)
  15168. {
  15169. if (opConstraint.mBinaryOp == findBinaryOp)
  15170. {
  15171. if ((mModule->CanImplicitlyCast(args[0].mTypedValue, opConstraint.mLeftType)) &&
  15172. (mModule->CanImplicitlyCast(args[1].mTypedValue, opConstraint.mRightType)))
  15173. {
  15174. BF_ASSERT(genericParam->mExternType != NULL);
  15175. mResult = BfTypedValue(mModule->mBfIRBuilder->GetFakeVal(), genericParam->mExternType);
  15176. return;
  15177. }
  15178. }
  15179. }
  15180. }
  15181. }
  15182. // Check type generic constraints
  15183. if ((mModule->mCurTypeInstance->IsGenericTypeInstance()) && (mModule->mCurTypeInstance->IsUnspecializedType()))
  15184. {
  15185. auto genericTypeInst = (BfGenericTypeInstance*)mModule->mCurTypeInstance;
  15186. for (int genericParamIdx = 0; genericParamIdx < genericTypeInst->mGenericParams.size(); genericParamIdx++)
  15187. {
  15188. auto genericParam = mModule->GetGenericTypeParamInstance(genericParamIdx);
  15189. for (auto& opConstraint : genericParam->mOperatorConstraints)
  15190. {
  15191. if (opConstraint.mBinaryOp == findBinaryOp)
  15192. {
  15193. if ((mModule->CanImplicitlyCast(args[0].mTypedValue, opConstraint.mLeftType)) &&
  15194. (mModule->CanImplicitlyCast(args[1].mTypedValue, opConstraint.mRightType)))
  15195. {
  15196. mResult = BfTypedValue(mModule->mBfIRBuilder->GetFakeVal(), genericParam->mExternType);
  15197. return;
  15198. }
  15199. }
  15200. }
  15201. }
  15202. }
  15203. if ((!foundOp) || (pass == 1))
  15204. break;
  15205. switch (findBinaryOp)
  15206. {
  15207. case BfBinaryOp_Equality:
  15208. case BfBinaryOp_InEquality:
  15209. case BfBinaryOp_Compare:
  15210. // Still works
  15211. break;
  15212. case BfBinaryOp_LessThan:
  15213. findBinaryOp = BfBinaryOp_GreaterThanOrEqual;
  15214. break;
  15215. case BfBinaryOp_LessThanOrEqual:
  15216. findBinaryOp = BfBinaryOp_GreaterThan;
  15217. break;
  15218. case BfBinaryOp_GreaterThan:
  15219. findBinaryOp = BfBinaryOp_LessThanOrEqual;
  15220. break;
  15221. case BfBinaryOp_GreaterThanOrEqual:
  15222. findBinaryOp = BfBinaryOp_LessThan;
  15223. break;
  15224. default:
  15225. findBinaryOp = BfBinaryOp_None;
  15226. break;
  15227. }
  15228. if (findBinaryOp == BfBinaryOp_None)
  15229. break;
  15230. }
  15231. }
  15232. }
  15233. if (mModule->IsUnboundGeneric(resultType))
  15234. {
  15235. mResult = mModule->GetDefaultTypedValue(mModule->GetPrimitiveType(BfTypeCode_Var));
  15236. return;
  15237. }
  15238. if (resultType->IsPointer() && otherType->IsPointer())
  15239. {
  15240. //TODO: Allow all pointer comparisons, but only allow SUBTRACTION between equal pointer types
  15241. if (binaryOp == BfBinaryOp_Subtract)
  15242. {
  15243. if (resultType != otherType)
  15244. {
  15245. mModule->Fail(StrFormat("Operands must be the same type, '%s' doesn't match '%s'",
  15246. mModule->TypeToString(leftValue.mType).c_str(), mModule->TypeToString(rightValue.mType).c_str()),
  15247. opToken);
  15248. return;
  15249. }
  15250. BfPointerType* resultPointerType = (BfPointerType*)resultType;
  15251. BfType* intPtrType = mModule->GetPrimitiveType(BfTypeCode_IntPtr);
  15252. convLeftValue = mModule->CastToValue(leftExpression, leftValue, intPtrType, (BfCastFlags)(BfCastFlags_Explicit | BfCastFlags_FromCompiler));
  15253. convRightValue = mModule->CastToValue(rightExpression, rightValue, intPtrType, (BfCastFlags)(BfCastFlags_Explicit | BfCastFlags_FromCompiler));
  15254. BfIRValue diffValue = mModule->mBfIRBuilder->CreateSub(convLeftValue, convRightValue);
  15255. diffValue = mModule->mBfIRBuilder->CreateDiv(diffValue, mModule->GetConstValue(resultPointerType->mElementType->mSize, intPtrType), true);
  15256. mResult = BfTypedValue(diffValue, intPtrType);
  15257. return;
  15258. }
  15259. else if ((binaryOp != BfBinaryOp_Equality) && (binaryOp != BfBinaryOp_InEquality) &&
  15260. (binaryOp != BfBinaryOp_LessThan) && (binaryOp != BfBinaryOp_LessThanOrEqual) &&
  15261. (binaryOp != BfBinaryOp_GreaterThan) && (binaryOp != BfBinaryOp_GreaterThanOrEqual))
  15262. {
  15263. mModule->Fail("Invalid operation on pointers", opToken);
  15264. return;
  15265. }
  15266. if (((binaryOp != BfBinaryOp_Equality) && (binaryOp != BfBinaryOp_InEquality)) ||
  15267. (resultType != otherType))
  15268. {
  15269. resultType = mModule->GetPrimitiveType(BfTypeCode_UIntPtr);
  15270. explicitCast = true;
  15271. }
  15272. }
  15273. else if (resultType->IsPointer())
  15274. {
  15275. if (otherType->IsNull())
  15276. {
  15277. if ((binaryOp != BfBinaryOp_Equality) && (binaryOp != BfBinaryOp_InEquality))
  15278. {
  15279. mModule->Fail(StrFormat("Invalid operation between '%s' and null", mModule->TypeToString(resultType).c_str()), opToken);
  15280. return;
  15281. }
  15282. if (binaryOp == BfBinaryOp_Equality)
  15283. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateIsNull(resultTypedValue->mValue), mModule->GetPrimitiveType(BfTypeCode_Boolean));
  15284. else
  15285. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateIsNotNull(resultTypedValue->mValue), mModule->GetPrimitiveType(BfTypeCode_Boolean));
  15286. return;
  15287. }
  15288. // One pointer
  15289. if ((!otherType->IsIntegral()) ||
  15290. ((binaryOp != BfBinaryOp_Add) && (binaryOp != BfBinaryOp_Subtract)))
  15291. {
  15292. _OpFail();
  15293. return;
  15294. }
  15295. auto underlyingType = resultType->GetUnderlyingType();
  15296. BfIRValue addValue = otherTypedValue->mValue;
  15297. if ((!otherTypedValue->mType->IsSigned()) && (otherTypedValue->mType->mSize < mModule->mSystem->mPtrSize))
  15298. addValue = mModule->mBfIRBuilder->CreateNumericCast(addValue, false, BfTypeCode_UIntPtr);
  15299. if (binaryOp == BfBinaryOp_Subtract)
  15300. {
  15301. if (resultTypeSrc == rightExpression)
  15302. mModule->Fail("Cannot subtract a pointer from an integer", resultTypeSrc);
  15303. addValue = mModule->mBfIRBuilder->CreateNeg(addValue);
  15304. }
  15305. if (underlyingType->IsValuelessType())
  15306. {
  15307. if (!mModule->IsInSpecializedSection())
  15308. {
  15309. mModule->Warn(0, "Adding to a pointer to a zero-sized element has no effect", opToken);
  15310. }
  15311. mResult = *resultTypedValue;
  15312. return;
  15313. }
  15314. mModule->mBfIRBuilder->PopulateType(underlyingType);
  15315. mResult = BfTypedValue(mModule->CreateIndexedValue(underlyingType, resultTypedValue->mValue, addValue), resultType);
  15316. return;
  15317. }
  15318. if ((resultType->IsFunction()) || (resultType->IsPointer()) || (resultType->IsObject()) || (resultType->IsInterface()) || (resultType->IsGenericParam()))
  15319. {
  15320. //if ((resultType->IsFunction()) || (resultType->IsObject()) || (resultType->IsInterface()) || (resultType->IsGenericParam()))
  15321. {
  15322. if ((binaryOp != BfBinaryOp_Equality) && (binaryOp != BfBinaryOp_InEquality))
  15323. {
  15324. //mModule->Fail("Invalid operation for objects", opToken);
  15325. _OpFail();
  15326. return;
  15327. }
  15328. }
  15329. if (resultType->IsInterface())
  15330. {
  15331. // Compare as objects instead
  15332. resultType = mModule->mContext->mBfObjectType;
  15333. *resultTypedValue = mModule->Cast(resultTypeSrc, *resultTypedValue, resultType);
  15334. }
  15335. if (otherType->IsNull())
  15336. {
  15337. if (resultType->IsFunction())
  15338. {
  15339. if (binaryOp == BfBinaryOp_Equality)
  15340. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateCmpEQ(mModule->mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, 0), resultTypedValue->mValue), mModule->GetPrimitiveType(BfTypeCode_Boolean));
  15341. else
  15342. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateCmpNE(mModule->mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, 0), resultTypedValue->mValue), mModule->GetPrimitiveType(BfTypeCode_Boolean));
  15343. }
  15344. else
  15345. {
  15346. if (binaryOp == BfBinaryOp_Equality)
  15347. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateIsNull(resultTypedValue->mValue), mModule->GetPrimitiveType(BfTypeCode_Boolean));
  15348. else
  15349. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateIsNotNull(resultTypedValue->mValue), mModule->GetPrimitiveType(BfTypeCode_Boolean));
  15350. }
  15351. }
  15352. else
  15353. {
  15354. auto convertedValue = mModule->CastToValue(otherTypeSrc, *otherTypedValue, resultType);
  15355. if (!convertedValue)
  15356. return;
  15357. if (binaryOp == BfBinaryOp_Equality)
  15358. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateCmpEQ(resultTypedValue->mValue, convertedValue), mModule->GetPrimitiveType(BfTypeCode_Boolean));
  15359. else
  15360. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateCmpNE(resultTypedValue->mValue, convertedValue), mModule->GetPrimitiveType(BfTypeCode_Boolean));
  15361. }
  15362. return;
  15363. }
  15364. if (resultType->IsTypedPrimitive())
  15365. {
  15366. bool needsOtherCast = true;
  15367. if (otherType != resultType)
  15368. {
  15369. if ((otherType->IsPrimitiveType()) && (!otherType->IsValuelessType()))
  15370. {
  15371. // Allow zero comparisons to match all typed primitives
  15372. if ((binaryOp == BfBinaryOp_Equality) || (binaryOp == BfBinaryOp_InEquality))
  15373. {
  15374. auto constant = mModule->mBfIRBuilder->GetConstant(otherTypedValue->mValue);
  15375. if ((constant != NULL) && (mModule->mBfIRBuilder->IsInt(constant->mTypeCode)) && (constant->mInt64 == 0))
  15376. needsOtherCast = false;
  15377. }
  15378. // Allow integer offsetting
  15379. if ((binaryOp == BfBinaryOp_Add) || (binaryOp == BfBinaryOp_Subtract))
  15380. {
  15381. if (otherType->IsIntegral())
  15382. needsOtherCast = false;
  15383. }
  15384. }
  15385. if (needsOtherCast)
  15386. {
  15387. // The only purpose of this cast is to potentially throw a casting error
  15388. BfIRValue otherCastResult = mModule->CastToValue(otherTypeSrc, *otherTypedValue, resultType, explicitCast ? BfCastFlags_Explicit : BfCastFlags_None);
  15389. if (!otherCastResult)
  15390. return;
  15391. }
  15392. }
  15393. auto underlyingType = resultType->GetUnderlyingType();
  15394. BfIRValue convResultValue = mModule->CastToValue(resultTypeSrc, *resultTypedValue, underlyingType, BfCastFlags_Explicit);
  15395. BfIRValue convOtherValue = mModule->CastToValue(otherTypeSrc, *otherTypedValue, underlyingType, BfCastFlags_Explicit);
  15396. if ((!underlyingType->IsValuelessType()) && ((!convResultValue) || (!convOtherValue)))
  15397. return;
  15398. if (resultTypedValue == &leftValue)
  15399. PerformBinaryOperation(underlyingType, convResultValue, convOtherValue, binaryOp, opToken);
  15400. else
  15401. PerformBinaryOperation(underlyingType, convOtherValue, convResultValue, binaryOp, opToken);
  15402. if (mResult.mType == underlyingType)
  15403. mResult.mType = resultType;
  15404. return;
  15405. }
  15406. auto _CallValueTypeEquals = [&]()
  15407. {
  15408. BfModuleMethodInstance moduleMethodInstance;
  15409. auto typeInst = leftValue.mType->ToTypeInstance();
  15410. if (typeInst != NULL)
  15411. {
  15412. moduleMethodInstance = mModule->GetMethodByName(typeInst, BF_METHODNAME_DEFAULT_EQUALS);
  15413. }
  15414. else
  15415. {
  15416. BF_ASSERT(leftValue.mType->IsSizedArray() || leftValue.mType->IsMethodRef());
  15417. auto valueTypeInst = mModule->ResolveTypeDef(mModule->mCompiler->mValueTypeTypeDef)->ToTypeInstance();
  15418. BfMethodDef* equalsMethodDef = mModule->mCompiler->mValueTypeTypeDef->GetMethodByName("Equals");
  15419. BfTypeVector typeVec;
  15420. typeVec.push_back(leftValue.mType);
  15421. moduleMethodInstance = mModule->GetMethodInstance(valueTypeInst, equalsMethodDef, typeVec);
  15422. }
  15423. if (moduleMethodInstance)
  15424. {
  15425. if ((opToken != NULL) && (!noClassify))
  15426. mModule->SetElementType(opToken, BfSourceElementType_Method);
  15427. SizedArray<BfResolvedArg, 4> argValues;
  15428. BfResolvedArg resolvedArg;
  15429. resolvedArg.mTypedValue = leftValue;
  15430. argValues.push_back(resolvedArg);
  15431. resolvedArg.mTypedValue = rightValue;
  15432. argValues.push_back(resolvedArg);
  15433. mResult = CreateCall(opToken, BfTypedValue(), BfTypedValue(), moduleMethodInstance.mMethodInstance->mMethodDef, moduleMethodInstance, false, argValues);
  15434. if ((mResult) && (binaryOp == BfBinaryOp_InEquality))
  15435. mResult.mValue = mModule->mBfIRBuilder->CreateNot(mResult.mValue);
  15436. return true;
  15437. }
  15438. return false;
  15439. };
  15440. if (((leftValue.mType->IsComposite()) || (leftValue.mType->IsObject())))
  15441. {
  15442. bool areEquivalentTuples = false;
  15443. if ((leftValue.mType->IsTuple()) && (rightValue.mType->IsTuple()))
  15444. {
  15445. auto leftTupleType = (BfTupleType*)leftValue.mType;
  15446. auto rightTupleType = (BfTupleType*)rightValue.mType;
  15447. // We only do this for tuples, because we would allow an implicit struct
  15448. // truncation if we allow it for all structs, which would result in only
  15449. // the base class's fields being compared
  15450. if (mModule->CanImplicitlyCast(rightValue, leftValue.mType))
  15451. rightValue = mModule->Cast(opToken, rightValue, leftValue.mType, BfCastFlags_Explicit);
  15452. else if (mModule->CanImplicitlyCast(leftValue, rightValue.mType))
  15453. leftValue = mModule->Cast(opToken, leftValue, rightValue.mType, BfCastFlags_Explicit);
  15454. }
  15455. if (leftValue.mType == rightValue.mType)
  15456. {
  15457. if ((binaryOp == BfBinaryOp_Equality) || (binaryOp == BfBinaryOp_InEquality))
  15458. {
  15459. auto intCoercibleType = mModule->GetIntCoercibleType(leftValue.mType);
  15460. if (intCoercibleType != NULL)
  15461. {
  15462. auto intLHS = mModule->GetIntCoercible(leftValue);
  15463. auto intRHS = mModule->GetIntCoercible(rightValue);
  15464. auto boolType = mModule->GetPrimitiveType(BfTypeCode_Boolean);
  15465. if (binaryOp == BfBinaryOp_Equality)
  15466. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateCmpEQ(intLHS.mValue, intRHS.mValue), boolType);
  15467. else
  15468. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateCmpNE(intLHS.mValue, intRHS.mValue), boolType);
  15469. return;
  15470. }
  15471. if (_CallValueTypeEquals())
  15472. return;
  15473. }
  15474. mModule->Fail(StrFormat("Operator '%s' cannot be applied to operands of type '%s'",
  15475. BfGetOpName(binaryOp),
  15476. mModule->TypeToString(leftValue.mType).c_str()), opToken);
  15477. }
  15478. else
  15479. {
  15480. mModule->Fail(StrFormat("Operator '%s' cannot be applied to operands of type '%s' and '%s'",
  15481. BfGetOpName(binaryOp),
  15482. mModule->TypeToString(leftValue.mType).c_str(),
  15483. mModule->TypeToString(rightValue.mType).c_str()), opToken);
  15484. }
  15485. return;
  15486. }
  15487. if (resultType->IsMethodRef() && otherType->IsMethodRef())
  15488. {
  15489. if ((binaryOp == BfBinaryOp_Equality) || (binaryOp == BfBinaryOp_InEquality))
  15490. {
  15491. auto boolType = mModule->GetPrimitiveType(BfTypeCode_Boolean);
  15492. BfMethodRefType* lhsMethodRefType = (BfMethodRefType*)leftValue.mType;
  15493. BfMethodRefType* rhsMethodRefType = (BfMethodRefType*)rightValue.mType;
  15494. if (lhsMethodRefType->mMethodRef != rhsMethodRefType->mMethodRef)
  15495. {
  15496. mResult = BfTypedValue(mModule->GetConstValue((binaryOp == BfBinaryOp_Equality) ? 0 : 1, boolType), boolType);
  15497. return;
  15498. }
  15499. if (_CallValueTypeEquals())
  15500. return;
  15501. }
  15502. }
  15503. if (resultType->IsIntegral())
  15504. {
  15505. if ((binaryOp == BfBinaryOp_LeftShift) || (binaryOp == BfBinaryOp_RightShift))
  15506. {
  15507. if (rightValue.mValue.IsConst())
  15508. {
  15509. auto constVal = mModule->mBfIRBuilder->GetConstant(rightValue.mValue);
  15510. if ((constVal->mInt64 < 0) || (constVal->mInt64 >= 8 * resultType->mSize))
  15511. {
  15512. mModule->Fail(StrFormat("Shift value '%lld' is out of range for type '%s'", constVal->mInt64, mModule->TypeToString(resultType).c_str()), opToken);
  15513. }
  15514. }
  15515. }
  15516. // We're trying a simplified scheme that doesn't always try to up-convert into an 'int'
  15517. if (leftValue.mType != rightValue.mType)
  15518. {
  15519. bool isBitwiseExpr =
  15520. (binaryOp == BfBinaryOp_BitwiseAnd) |
  15521. (binaryOp == BfBinaryOp_BitwiseOr) |
  15522. (binaryOp == BfBinaryOp_ExclusiveOr) |
  15523. (binaryOp == BfBinaryOp_LeftShift) |
  15524. (binaryOp == BfBinaryOp_RightShift) |
  15525. (binaryOp == BfBinaryOp_Equality) |
  15526. (binaryOp == BfBinaryOp_InEquality);
  15527. if ((binaryOp == BfBinaryOp_LeftShift) || (binaryOp == BfBinaryOp_RightShift))
  15528. {
  15529. // For shifts we have more lenient rules - shifts are naturally limited so any int type is equally valid
  15530. if (rightValue.mType->IsIntegral())
  15531. explicitCast = true;
  15532. }
  15533. else if (((binaryOp == BfBinaryOp_Add) || (binaryOp == BfBinaryOp_Subtract)) && (resultType->IsChar()) && (otherType->IsInteger()))
  15534. {
  15535. // charVal += intVal;
  15536. explicitCast = true;
  15537. }
  15538. else if ((!resultType->IsSigned()) && (otherType->IsSigned()))
  15539. {
  15540. if (mModule->CanImplicitlyCast(*otherTypedValue, resultType))
  15541. {
  15542. // If we can convert the 'other' value implicitly then it's a convertible literal, leave as uint
  15543. }
  15544. else
  15545. {
  15546. mModule->Fail(StrFormat("Operator cannot be applied to operands of type '%s' and '%s'",
  15547. mModule->TypeToString(leftValue.mType).c_str(),
  15548. mModule->TypeToString(rightValue.mType).c_str()), opToken);
  15549. return;
  15550. }
  15551. }
  15552. else if ((isBitwiseExpr) && (otherType->IsIntegral()) && (resultType->mSize == otherType->mSize))
  15553. {
  15554. // Forget about signed/unsigned mismatches for bitwise operations
  15555. explicitCast = true;
  15556. }
  15557. else
  15558. {
  15559. if ((binaryOp == BfBinaryOp_Subtract) && (resultType->IsChar()) && (otherType->IsChar()))
  15560. {
  15561. // "wchar - char" subtraction will always fit into int32, because of unicode range
  15562. resultType = mModule->GetPrimitiveType(BfTypeCode_Int32);
  15563. explicitCast = true;
  15564. }
  15565. else if ((otherType->IsChar()) &&
  15566. ((binaryOp == BfBinaryOp_Add) || (binaryOp == BfBinaryOp_Subtract)))
  15567. {
  15568. mModule->Fail(StrFormat("Cannot perform operation between types '%s' and '%s'",
  15569. mModule->TypeToString(leftValue.mType).c_str(),
  15570. mModule->TypeToString(rightValue.mType).c_str()), opToken);
  15571. }
  15572. }
  15573. }
  15574. else if ((!resultType->IsSigned()) && (binaryOp == BfBinaryOp_Subtract) && (!forceLeftType))
  15575. {
  15576. if ((mExpectingType == NULL) || (mExpectingType->IsSigned()) || (resultType->IsChar()))
  15577. {
  15578. if ((resultType->IsChar()) && (resultType->mSize == 4))
  15579. {
  15580. // "wchar - wchar" subtraction will always fit into int32, because of unicode range
  15581. resultType = mModule->GetPrimitiveType(BfTypeCode_Int32);
  15582. }
  15583. else
  15584. {
  15585. // The result of uint8 - uint8 is int16 (for example)
  15586. switch (resultType->mSize)
  15587. {
  15588. case 1:
  15589. resultType = mModule->GetPrimitiveType(BfTypeCode_Int16);
  15590. break;
  15591. case 2:
  15592. resultType = mModule->GetPrimitiveType(BfTypeCode_Int32);
  15593. break;
  15594. case 4:
  15595. resultType = mModule->GetPrimitiveType(BfTypeCode_Int64);
  15596. break;
  15597. }
  15598. }
  15599. explicitCast = true;
  15600. }
  15601. }
  15602. else if (resultType->IsChar())
  15603. {
  15604. bool canDoOp =
  15605. (binaryOp == BfBinaryOp_BitwiseAnd) ||
  15606. (binaryOp == BfBinaryOp_BitwiseOr) ||
  15607. ((binaryOp >= BfBinaryOp_Equality) && (binaryOp <= BfBinaryOp_Compare));
  15608. if (!canDoOp)
  15609. {
  15610. mModule->Fail(StrFormat("Cannot perform operation on type '%s'", mModule->TypeToString(resultType).c_str()), opToken);
  15611. return;
  15612. }
  15613. }
  15614. }
  15615. if (!convLeftValue)
  15616. convLeftValue = mModule->CastToValue(leftExpression, leftValue, resultType,
  15617. explicitCast ? (BfCastFlags)(BfCastFlags_Explicit | BfCastFlags_FromCompiler) : BfCastFlags_None);
  15618. if (!convRightValue)
  15619. convRightValue = mModule->CastToValue(rightExpression, rightValue, resultType,
  15620. explicitCast ? (BfCastFlags)(BfCastFlags_Explicit | BfCastFlags_FromCompiler) : BfCastFlags_None);
  15621. PerformBinaryOperation(resultType, convLeftValue, convRightValue, binaryOp, opToken);
  15622. }
  15623. void BfExprEvaluator::PerformBinaryOperation(BfType* resultType, BfIRValue convLeftValue, BfIRValue convRightValue, BfBinaryOp binaryOp, BfAstNode* opToken)
  15624. {
  15625. if (resultType->IsValuelessType())
  15626. {
  15627. switch (binaryOp)
  15628. {
  15629. case BfBinaryOp_Equality:
  15630. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConst(BfTypeCode_Boolean, 1),
  15631. mModule->GetPrimitiveType(BfTypeCode_Boolean));
  15632. break;
  15633. case BfBinaryOp_InEquality:
  15634. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConst(BfTypeCode_Boolean, 0),
  15635. mModule->GetPrimitiveType(BfTypeCode_Boolean));
  15636. break;
  15637. default:
  15638. mModule->Fail("Invalid operation for void", opToken);
  15639. break;
  15640. }
  15641. return;
  15642. }
  15643. if ((!convLeftValue) || (!convRightValue))
  15644. return;
  15645. if (resultType->IsPrimitiveType())
  15646. {
  15647. auto primType = (BfPrimitiveType*)resultType;
  15648. if (primType->mTypeDef->mTypeCode == BfTypeCode_Boolean)
  15649. {
  15650. switch (binaryOp)
  15651. {
  15652. case BfBinaryOp_Equality:
  15653. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateCmpEQ(convLeftValue, convRightValue),
  15654. mModule->GetPrimitiveType(BfTypeCode_Boolean));
  15655. break;
  15656. case BfBinaryOp_InEquality:
  15657. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateCmpNE(convLeftValue, convRightValue),
  15658. mModule->GetPrimitiveType(BfTypeCode_Boolean));
  15659. break;
  15660. case BfBinaryOp_BitwiseAnd:
  15661. case BfBinaryOp_ConditionalAnd:
  15662. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateAnd(convLeftValue, convRightValue),
  15663. mModule->GetPrimitiveType(BfTypeCode_Boolean));
  15664. break;
  15665. case BfBinaryOp_BitwiseOr:
  15666. case BfBinaryOp_ConditionalOr:
  15667. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateOr(convLeftValue, convRightValue),
  15668. mModule->GetPrimitiveType(BfTypeCode_Boolean));
  15669. break;
  15670. case BfBinaryOp_ExclusiveOr:
  15671. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateXor(convLeftValue, convRightValue),
  15672. mModule->GetPrimitiveType(BfTypeCode_Boolean));
  15673. break;
  15674. default:
  15675. mModule->Fail("Invalid operation for booleans", opToken);
  15676. break;
  15677. }
  15678. return;
  15679. }
  15680. }
  15681. if ((!resultType->IsIntegral()) && (!resultType->IsFloat()))
  15682. {
  15683. mModule->Fail(StrFormat("Cannot perform operation on type '%s'", mModule->TypeToString(resultType).c_str()), opToken);
  15684. return;
  15685. }
  15686. if (resultType->IsIntegral())
  15687. {
  15688. switch (binaryOp)
  15689. {
  15690. case BfBinaryOp_BitwiseAnd:
  15691. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateAnd(convLeftValue, convRightValue), resultType);
  15692. return;
  15693. case BfBinaryOp_BitwiseOr:
  15694. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateOr(convLeftValue, convRightValue), resultType);
  15695. return;
  15696. case BfBinaryOp_ExclusiveOr:
  15697. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateXor(convLeftValue, convRightValue), resultType);
  15698. return;
  15699. case BfBinaryOp_LeftShift:
  15700. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateShl(convLeftValue, convRightValue), resultType);
  15701. mModule->CheckRangeError(resultType, opToken);
  15702. return;
  15703. case BfBinaryOp_RightShift:
  15704. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateShr(convLeftValue, convRightValue, resultType->IsSigned()), resultType);
  15705. return;
  15706. default: break;
  15707. }
  15708. }
  15709. if ((resultType->IsChar()) &&
  15710. ((binaryOp == BfBinaryOp_Multiply) ||
  15711. (binaryOp == BfBinaryOp_Divide) ||
  15712. (binaryOp == BfBinaryOp_Modulus)))
  15713. {
  15714. mModule->Fail(StrFormat("Cannot perform operation on type '%s'", mModule->TypeToString(resultType).c_str()), opToken);
  15715. return;
  15716. }
  15717. switch (binaryOp)
  15718. {
  15719. case BfBinaryOp_Add:
  15720. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateAdd(convLeftValue, convRightValue), resultType);
  15721. mModule->CheckRangeError(resultType, opToken);
  15722. break;
  15723. case BfBinaryOp_Subtract:
  15724. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateSub(convLeftValue, convRightValue), resultType);
  15725. mModule->CheckRangeError(resultType, opToken);
  15726. break;
  15727. case BfBinaryOp_Multiply:
  15728. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateMul(convLeftValue, convRightValue), resultType);
  15729. mModule->CheckRangeError(resultType, opToken);
  15730. break;
  15731. case BfBinaryOp_Divide:
  15732. {
  15733. bool isZero = false;
  15734. if (convRightValue.IsConst())
  15735. {
  15736. auto constVal = mModule->mBfIRBuilder->GetConstant(convRightValue);
  15737. if (BfIRBuilder::IsInt(constVal->mTypeCode))
  15738. isZero = constVal->mInt64 == 0;
  15739. }
  15740. if (isZero)
  15741. {
  15742. mModule->Fail("Divide by zero", opToken);
  15743. mResult = mModule->GetDefaultTypedValue(resultType);
  15744. }
  15745. else
  15746. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateDiv(convLeftValue, convRightValue, resultType->IsSigned()), resultType);
  15747. }
  15748. break;
  15749. case BfBinaryOp_Modulus:
  15750. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateRem(convLeftValue, convRightValue, resultType->IsSigned()), resultType);
  15751. break;
  15752. case BfBinaryOp_Equality:
  15753. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateCmpEQ(convLeftValue, convRightValue),
  15754. mModule->GetPrimitiveType(BfTypeCode_Boolean));
  15755. break;
  15756. case BfBinaryOp_InEquality:
  15757. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateCmpNE(convLeftValue, convRightValue),
  15758. mModule->GetPrimitiveType(BfTypeCode_Boolean));
  15759. break;
  15760. case BfBinaryOp_LessThan:
  15761. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateCmpLT(convLeftValue, convRightValue, resultType->IsSignedInt()),
  15762. mModule->GetPrimitiveType(BfTypeCode_Boolean));
  15763. break;
  15764. case BfBinaryOp_LessThanOrEqual:
  15765. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateCmpLTE(convLeftValue, convRightValue, resultType->IsSignedInt()),
  15766. mModule->GetPrimitiveType(BfTypeCode_Boolean));
  15767. break;
  15768. case BfBinaryOp_GreaterThan:
  15769. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateCmpGT(convLeftValue, convRightValue, resultType->IsSignedInt()),
  15770. mModule->GetPrimitiveType(BfTypeCode_Boolean));
  15771. break;
  15772. case BfBinaryOp_GreaterThanOrEqual:
  15773. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateCmpGTE(convLeftValue, convRightValue, resultType->IsSignedInt()),
  15774. mModule->GetPrimitiveType(BfTypeCode_Boolean));
  15775. break;
  15776. case BfBinaryOp_Compare:
  15777. {
  15778. auto intType = mModule->GetPrimitiveType(BfTypeCode_IntPtr);
  15779. BfIRBlock checkGtBlock = mModule->mBfIRBuilder->CreateBlock("cmpCheckGt");
  15780. BfIRBlock eqBlock = mModule->mBfIRBuilder->CreateBlock("cmpEq");
  15781. BfIRBlock endBlock = mModule->mBfIRBuilder->CreateBlock("cmpEnd");
  15782. auto startBlock = mModule->mBfIRBuilder->GetInsertBlock();
  15783. auto cmpLtVal = mModule->mBfIRBuilder->CreateCmpLT(convLeftValue, convRightValue, resultType->IsSignedInt());
  15784. mModule->mBfIRBuilder->CreateCondBr(cmpLtVal, endBlock, checkGtBlock);
  15785. mModule->mBfIRBuilder->AddBlock(checkGtBlock);
  15786. mModule->mBfIRBuilder->SetInsertPoint(checkGtBlock);
  15787. auto cmpGtVal = mModule->mBfIRBuilder->CreateCmpGT(convLeftValue, convRightValue, resultType->IsSignedInt());
  15788. mModule->mBfIRBuilder->CreateCondBr(cmpGtVal, endBlock, eqBlock);
  15789. mModule->mBfIRBuilder->AddBlock(eqBlock);
  15790. mModule->mBfIRBuilder->SetInsertPoint(eqBlock);
  15791. mModule->mBfIRBuilder->CreateBr(endBlock);
  15792. mModule->mBfIRBuilder->AddBlock(endBlock);
  15793. mModule->mBfIRBuilder->SetInsertPoint(endBlock);
  15794. auto phiVal = mModule->mBfIRBuilder->CreatePhi(mModule->mBfIRBuilder->MapType(intType), 3);
  15795. mModule->mBfIRBuilder->AddPhiIncoming(phiVal, mModule->mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, -1), startBlock);
  15796. mModule->mBfIRBuilder->AddPhiIncoming(phiVal, mModule->mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, 1), checkGtBlock);
  15797. mModule->mBfIRBuilder->AddPhiIncoming(phiVal, mModule->mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, 0), eqBlock);
  15798. mResult = BfTypedValue(phiVal, intType);
  15799. }
  15800. break;
  15801. default:
  15802. mModule->Fail("Invalid operation", opToken);
  15803. break;
  15804. }
  15805. }
  15806. void BfExprEvaluator::Visit(BfBinaryOperatorExpression* binOpExpr)
  15807. {
  15808. BfAutoParentNodeEntry autoParentNodeEntry(mModule, binOpExpr);
  15809. // There are a few binary operations that could actually be casts followed by an unary operation
  15810. // We can't determine that until we know whether the identifier in the parens is a typename or not
  15811. // (double)-1.0 (intptr)&val (BaseStruct)*val
  15812. BfUnaryOp unaryOp = BfUnaryOp_None;
  15813. switch (binOpExpr->mOp)
  15814. {
  15815. case BfBinaryOp_Add: unaryOp = BfUnaryOp_Positive; break;
  15816. case BfBinaryOp_Subtract: unaryOp = BfUnaryOp_Negate; break;
  15817. case BfBinaryOp_Multiply: unaryOp = BfUnaryOp_Dereference; break;
  15818. case BfBinaryOp_BitwiseAnd: unaryOp = BfUnaryOp_AddressOf; break;
  15819. default: break;
  15820. }
  15821. if (unaryOp != BfUnaryOp_None)
  15822. {
  15823. if (auto parenExpr = BfNodeDynCast<BfParenthesizedExpression>(binOpExpr->mLeft))
  15824. {
  15825. if (auto castTypeExpr = BfNodeDynCast<BfIdentifierNode>(parenExpr->mExpression))
  15826. {
  15827. SetAndRestoreValue<bool> prevIgnoreError(mModule->mIgnoreErrors, true);
  15828. auto resolvedType = mModule->ResolveTypeRef(castTypeExpr, NULL);
  15829. prevIgnoreError.Restore();
  15830. if (resolvedType != NULL)
  15831. {
  15832. if (auto rightBinOpExpr = BfNodeDynCast<BfBinaryOperatorExpression>(binOpExpr->mRight))
  15833. {
  15834. int leftPrecedence = BfGetBinaryOpPrecendence(binOpExpr->mOp);
  15835. int rightPrecedence = BfGetBinaryOpPrecendence(rightBinOpExpr->mOp);
  15836. // Do we have a precedence order issue due to mis-parsing this?
  15837. // An example is: "(int)-5.5 * 10"
  15838. if (rightPrecedence > leftPrecedence)
  15839. {
  15840. mModule->FailAfter("Cast target must be wrapped in parentheses", binOpExpr->mLeft);
  15841. }
  15842. }
  15843. PerformUnaryOperation(binOpExpr->mRight, unaryOp, binOpExpr->mOpToken);
  15844. if (mResult)
  15845. {
  15846. mResult = mModule->LoadValue(mResult);
  15847. mResult = mModule->Cast(binOpExpr, mResult, resolvedType, BfCastFlags_Explicit);
  15848. }
  15849. return;
  15850. }
  15851. }
  15852. }
  15853. }
  15854. if (binOpExpr->mRight == NULL)
  15855. {
  15856. // We visit the children for autocompletion only
  15857. if (binOpExpr->mLeft != NULL)
  15858. VisitChild(binOpExpr->mLeft);
  15859. if (mResult)
  15860. {
  15861. auto autoComplete = GetAutoComplete();
  15862. if (autoComplete != NULL)
  15863. autoComplete->CheckEmptyStart(binOpExpr->mOpToken, mResult.mType);
  15864. }
  15865. if (binOpExpr->mRight != NULL)
  15866. VisitChild(binOpExpr->mRight);
  15867. return;
  15868. }
  15869. PerformBinaryOperation(binOpExpr->mLeft, binOpExpr->mRight, binOpExpr->mOp, binOpExpr->mOpToken, BfBinOpFlag_None);
  15870. }
  15871. //