MMRScriptCodeGen.cs 282 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417
  1. /*
  2. * Copyright (c) Contributors, http://opensimulator.org/
  3. * See CONTRIBUTORS.TXT for a full list of copyright holders.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. * * Redistributions of source code must retain the above copyright
  8. * notice, this list of conditions and the following disclaimer.
  9. * * Redistributions in binary form must reproduce the above copyright
  10. * notice, this list of conditions and the following disclaimer in the
  11. * documentation and/or other materials provided with the distribution.
  12. * * Neither the name of the OpenSimulator Project nor the
  13. * names of its contributors may be used to endorse or promote products
  14. * derived from this software without specific prior written permission.
  15. *
  16. * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
  17. * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  18. * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  19. * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
  20. * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  21. * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  22. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  23. * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  24. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  25. * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  26. */
  27. using OpenSim.Region.ScriptEngine.Shared.ScriptBase;
  28. using OpenSim.Region.ScriptEngine.Yengine;
  29. using System;
  30. using System.Collections.Generic;
  31. using System.IO;
  32. using System.Reflection;
  33. using System.Reflection.Emit;
  34. using System.Runtime.Serialization;
  35. using System.Text;
  36. using LSL_Float = OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLFloat;
  37. using LSL_Integer = OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLInteger;
  38. using LSL_Key = OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLString;
  39. using LSL_List = OpenSim.Region.ScriptEngine.Shared.LSL_Types.list;
  40. using LSL_Rotation = OpenSim.Region.ScriptEngine.Shared.LSL_Types.Quaternion;
  41. using LSL_String = OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLString;
  42. using LSL_Vector = OpenSim.Region.ScriptEngine.Shared.LSL_Types.Vector3;
  43. /**
  44. * @brief translate a reduced script token into corresponding CIL code.
  45. * The single script token contains a tokenized and textured version of the whole script file.
  46. */
  47. namespace OpenSim.Region.ScriptEngine.Yengine
  48. {
  49. public interface IScriptCodeGen
  50. {
  51. ScriptMyILGen ilGen
  52. {
  53. get;
  54. } // the output instruction stream
  55. void ErrorMsg(Token token, string message);
  56. void PushDefaultValue(TokenType type);
  57. void PushXMRInst();
  58. }
  59. public class ScriptCodeGen: IScriptCodeGen
  60. {
  61. public static readonly string OBJECT_CODE_MAGIC = "YObjectCode";
  62. // reserve positive version values for original xmr
  63. public static int COMPILED_VERSION_VALUE = -10; // decremented when compiler or object file changes
  64. public static readonly int CALL_FRAME_MEMUSE = 64;
  65. public static readonly int STRING_LEN_TO_MEMUSE = 2;
  66. public static Type xmrInstSuperType = null; // typeof whatever is actually malloc'd for script instances
  67. // - must inherit from XMRInstAbstract
  68. // Static tables that there only needs to be one copy of for all.
  69. private static readonly VarDict legalEventHandlers = CreateLegalEventHandlers();
  70. private static readonly CompValu[] zeroCompValus = Array.Empty<CompValu>();
  71. private static readonly TokenType[] zeroArgs = Array.Empty<TokenType>();
  72. private static readonly TokenTypeBool tokenTypeBool = new(null);
  73. private static readonly TokenTypeExc tokenTypeExc = new(null);
  74. private static readonly TokenTypeFloat tokenTypeFlt = new(null);
  75. private static readonly TokenTypeInt tokenTypeInt = new(null);
  76. private static readonly TokenTypeObject tokenTypeObj = new(null);
  77. private static readonly TokenTypeRot tokenTypeRot = new(null);
  78. private static readonly TokenTypeStr tokenTypeStr = new(null);
  79. private static readonly TokenTypeVec tokenTypeVec = new(null);
  80. private static readonly Type[] instanceTypeArg = [typeof(XMRInstAbstract)];
  81. private static readonly string[] instanceNameArg = ["$xmrthis"];
  82. private static readonly ConstructorInfo lslFloatConstructorInfo = typeof(LSL_Float).GetConstructor([typeof(double)]);
  83. private static readonly ConstructorInfo lslIntegerConstructorInfo = typeof(LSL_Integer).GetConstructor([typeof(int)]);
  84. private static readonly ConstructorInfo lslListConstructorInfo = typeof(LSL_List).GetConstructor([typeof(object[])]);
  85. public static readonly ConstructorInfo lslRotationConstructorInfo = typeof(LSL_Rotation).GetConstructor([typeof(double), typeof(double), typeof(double), typeof(double)]);
  86. private static readonly ConstructorInfo lslStringConstructorInfo = typeof(LSL_String).GetConstructor([typeof(string)]);
  87. public static readonly ConstructorInfo lslVectorConstructorInfo = typeof(LSL_Vector).GetConstructor([typeof(double), typeof(double), typeof(double)]);
  88. private static readonly ConstructorInfo scriptBadCallNoExceptionConstructorInfo = typeof(ScriptBadCallNoException).GetConstructor([typeof(int)]);
  89. private static readonly ConstructorInfo scriptChangeStateExceptionConstructorInfo = typeof(ScriptChangeStateException).GetConstructor([typeof(int)]);
  90. private static readonly ConstructorInfo scriptRestoreCatchExceptionConstructorInfo = typeof(ScriptRestoreCatchException).GetConstructor([typeof(Exception)]);
  91. private static readonly ConstructorInfo scriptUndefinedStateExceptionConstructorInfo = typeof(ScriptUndefinedStateException).GetConstructor([typeof(string)]);
  92. private static readonly ConstructorInfo sdtClassConstructorInfo = typeof(XMRSDTypeClObj).GetConstructor([typeof(XMRInstAbstract), typeof(int)]);
  93. private static readonly ConstructorInfo xmrArrayConstructorInfo = typeof(XMR_Array).GetConstructor([typeof(XMRInstAbstract)]);
  94. private static readonly FieldInfo callModeFieldInfo = typeof(XMRInstAbstract).GetField("callMode");
  95. private static readonly FieldInfo doGblInitFieldInfo = typeof(XMRInstAbstract).GetField("doGblInit");
  96. private static readonly FieldInfo ehArgsFieldInfo = typeof(XMRInstAbstract).GetField("ehArgs");
  97. private static readonly FieldInfo rotationXFieldInfo = typeof(LSL_Rotation).GetField("x");
  98. private static readonly FieldInfo rotationYFieldInfo = typeof(LSL_Rotation).GetField("y");
  99. private static readonly FieldInfo rotationZFieldInfo = typeof(LSL_Rotation).GetField("z");
  100. private static readonly FieldInfo rotationSFieldInfo = typeof(LSL_Rotation).GetField("s");
  101. private static readonly FieldInfo sdtXMRInstFieldInfo = typeof(XMRSDTypeClObj).GetField("xmrInst");
  102. private static readonly FieldInfo stackLeftFieldInfo = typeof(XMRInstAbstract).GetField("m_StackLeft");
  103. private static readonly FieldInfo heapUsedFieldInfo = typeof(XMRInstAbstract).GetField("m_localsHeapUsed");
  104. private static readonly FieldInfo vectorXFieldInfo = typeof(LSL_Vector).GetField("x");
  105. private static readonly FieldInfo vectorYFieldInfo = typeof(LSL_Vector).GetField("y");
  106. private static readonly FieldInfo vectorZFieldInfo = typeof(LSL_Vector).GetField("z");
  107. private static readonly MethodInfo arrayClearMethodInfo = typeof(XMR_Array).GetMethod("__pub_clear", Array.Empty<Type>());
  108. private static readonly MethodInfo arrayCountMethodInfo = typeof(XMR_Array).GetMethod("__pub_count", Array.Empty<Type>());
  109. private static readonly MethodInfo arrayIndexMethodInfo = typeof(XMR_Array).GetMethod("__pub_index", [typeof(int)]);
  110. private static readonly MethodInfo arrayValueMethodInfo = typeof(XMR_Array).GetMethod("__pub_value", [typeof(int)]);
  111. private static readonly MethodInfo checkRunStackMethInfo = typeof(XMRInstAbstract).GetMethod("CheckRunStack", Array.Empty<Type>());
  112. private static readonly MethodInfo checkRunQuickMethInfo = typeof(XMRInstAbstract).GetMethod("CheckRunQuick", Array.Empty<Type>());
  113. private static readonly MethodInfo ehArgUnwrapFloat = GetStaticMethod(typeof(TypeCast), "EHArgUnwrapFloat", [typeof(object)]);
  114. private static readonly MethodInfo ehArgUnwrapInteger = GetStaticMethod(typeof(TypeCast), "EHArgUnwrapInteger", [typeof(object)]);
  115. private static readonly MethodInfo ehArgUnwrapRotation = GetStaticMethod(typeof(TypeCast), "EHArgUnwrapRotation", [typeof(object)]);
  116. private static readonly MethodInfo ehArgUnwrapString = GetStaticMethod(typeof(TypeCast), "EHArgUnwrapString", [typeof(object)]);
  117. private static readonly MethodInfo ehArgUnwrapVector = GetStaticMethod(typeof(TypeCast), "EHArgUnwrapVector", [typeof(object)]);
  118. private static readonly MethodInfo xmrArrPubIndexMethod = typeof(XMR_Array).GetMethod("__pub_index", [typeof(int)]);
  119. private static readonly MethodInfo xmrArrPubValueMethod = typeof(XMR_Array).GetMethod("__pub_value", [typeof(int)]);
  120. private static readonly MethodInfo captureStackFrameMethodInfo = typeof(XMRInstAbstract).GetMethod("CaptureStackFrame", [typeof(string), typeof(int), typeof(int)]);
  121. private static readonly MethodInfo restoreStackFrameMethodInfo = typeof(XMRInstAbstract).GetMethod("RestoreStackFrame", [typeof(string), typeof(int).MakeByRefType()]);
  122. private static readonly MethodInfo stringCompareMethodInfo = GetStaticMethod(typeof(BinOpStr), "StringCompareOrdinal", [typeof(string), typeof(string)]);
  123. private static readonly MethodInfo stringConcat2MethodInfo = GetStaticMethod(typeof(BinOpStr), "StringConcat", [typeof(string), typeof(string)]);
  124. private static readonly MethodInfo stringConcat3MethodInfo = GetStaticMethod(typeof(BinOpStr), "StringConcat", [typeof(string), typeof(string), typeof(string)]);
  125. private static readonly MethodInfo stringConcat4MethodInfo = GetStaticMethod(typeof(BinOpStr), "StringConcat", [typeof(string), typeof(string), typeof(string), typeof(string)]);
  126. private static readonly MethodInfo lslRotationNegateMethodInfo = GetStaticMethod(typeof(ScriptCodeGen), "LSLRotationNegate", [typeof(LSL_Rotation)]);
  127. private static readonly MethodInfo lslVectorNegateMethodInfo = GetStaticMethod(typeof(ScriptCodeGen), "LSLVectorNegate", [typeof(LSL_Vector)]);
  128. private static readonly MethodInfo scriptRestoreCatchExceptionUnwrap = GetStaticMethod(typeof(ScriptRestoreCatchException), "Unwrap", [typeof(Exception)]);
  129. private static readonly MethodInfo thrownExceptionWrapMethodInfo = GetStaticMethod(typeof(ScriptThrownException), "Wrap", [typeof(object)]);
  130. private static readonly MethodInfo catchExcToStrMethodInfo = GetStaticMethod(typeof(ScriptCodeGen), "CatchExcToStr", [typeof(Exception)]);
  131. private static readonly MethodInfo consoleWriteMethodInfo = GetStaticMethod(typeof(ScriptCodeGen), "ConsoleWrite", [typeof(object)]);
  132. public static void ConsoleWrite(object o)
  133. {
  134. o ??= "<<null>>";
  135. Console.Write(o.ToString());
  136. }
  137. public static bool CodeGen(TokenScript tokenScript, BinaryWriter objFileWriter, string sourceHash)
  138. {
  139. // Run compiler such that it has a 'this' context for convenience.
  140. ScriptCodeGen scg = new(tokenScript, objFileWriter, sourceHash);
  141. // Return pointer to resultant script object code.
  142. return !scg.youveAnError;
  143. }
  144. // There is one set of these variables for each script being compiled.
  145. private bool mightGetHere = false;
  146. private bool youveAnError = false;
  147. private BreakContTarg curBreakTarg = null;
  148. private BreakContTarg curContTarg = null;
  149. private int lastErrorLine = 0;
  150. private int nStates = 0;
  151. private readonly string sourceHash;
  152. private string lastErrorFile = "";
  153. private string[] stateNames;
  154. private readonly XMRInstArSizes glblSizes = new ();
  155. private Token errorMessageToken = null;
  156. private TokenDeclVar curDeclFunc = null;
  157. private TokenStmtBlock curStmtBlock = null;
  158. private readonly BinaryWriter objFileWriter = null;
  159. private readonly TokenScript tokenScript = null;
  160. public int tempCompValuNum = 0;
  161. private TokenDeclSDTypeClass currentSDTClass = null;
  162. private Dictionary<string, int> stateIndices = null;
  163. // These get cleared at beginning of every function definition
  164. private ScriptMyLocal instancePointer; // holds XMRInstanceSuperType pointer
  165. private ScriptMyLocal curHeapSize;
  166. private ScriptMyLabel retLabel = null; // where to jump to exit function
  167. private ScriptMyLocal retValue = null;
  168. private ScriptMyLocal actCallNo = null; // for the active try/catch/finally stack or the big one outside them all
  169. private LinkedList<CallLabel> actCallLabels = new(); // for the active try/catch/finally stack or the big one outside them all
  170. private LinkedList<CallLabel> allCallLabels = new(); // this holds each and every one for all stacks in total
  171. public CallLabel openCallLabel = null; // only one call label can be open at a time
  172. // - the call label is open from the time of CallPre() until corresponding CallPost()
  173. // - so no non-trivial pushes/pops etc allowed between a CallPre() and a CallPost()
  174. private ScriptMyILGen _ilGen;
  175. public ScriptMyILGen ilGen
  176. {
  177. get
  178. {
  179. return _ilGen;
  180. }
  181. }
  182. private ScriptCodeGen(TokenScript tokenScript, BinaryWriter objFileWriter, string sourceHash)
  183. {
  184. this.tokenScript = tokenScript;
  185. this.objFileWriter = objFileWriter;
  186. this.sourceHash = sourceHash;
  187. try
  188. {
  189. PerformCompilation();
  190. }
  191. catch
  192. {
  193. // if we've an error, just punt on any exception
  194. // it's probably just a null reference from something
  195. // not being filled in etc.
  196. if(!youveAnError)
  197. throw;
  198. }
  199. finally
  200. {
  201. }
  202. }
  203. /**
  204. * @brief Convert 'tokenScript' to 'objFileWriter' format.
  205. * 'tokenScript' is a parsed/reduced abstract syntax tree of the script source file
  206. * 'objFileWriter' is a serialized form of the CIL code that we generate
  207. */
  208. private void PerformCompilation()
  209. {
  210. // errorMessageToken is used only when the given token doesn't have a
  211. // output delegate associated with it such as for backend API functions
  212. // that only have one copy for the whole system. It is kept up-to-date
  213. // approximately but is rarely needed so going to assume it doesn't have
  214. // to be exact.
  215. errorMessageToken = tokenScript;
  216. // Set up dictionary to translate state names to their index number.
  217. stateIndices = new Dictionary<string, int>();
  218. // Assign each state its own unique index.
  219. // The default state gets 0.
  220. nStates = 0;
  221. tokenScript.defaultState.body.index = nStates++;
  222. stateIndices.Add("default", 0);
  223. foreach(KeyValuePair<string, TokenDeclState> kvp in tokenScript.states)
  224. {
  225. TokenDeclState declState = kvp.Value;
  226. declState.body.index = nStates++;
  227. stateIndices.Add(declState.name.val, declState.body.index);
  228. }
  229. // Make up an array that translates state indices to state name strings.
  230. stateNames = new string[nStates];
  231. stateNames[0] = "default";
  232. foreach(KeyValuePair<string, TokenDeclState> kvp in tokenScript.states)
  233. {
  234. TokenDeclState declState = kvp.Value;
  235. stateNames[declState.body.index] = declState.name.val;
  236. }
  237. // Make sure we have delegates for all script-defined functions and methods,
  238. // creating anonymous ones if needed. Note that this includes all property
  239. // getter and setter methods.
  240. foreach(TokenDeclVar declFunc in tokenScript.variablesStack)
  241. {
  242. if(declFunc.retType != null)
  243. {
  244. declFunc.GetDelType();
  245. }
  246. }
  247. while(true)
  248. {
  249. bool itIsAGoodDayToDie = true;
  250. try
  251. {
  252. foreach(TokenDeclSDType sdType in tokenScript.sdSrcTypesValues)
  253. {
  254. itIsAGoodDayToDie = false;
  255. if(sdType is TokenDeclSDTypeClass sdtClass)
  256. {
  257. foreach(TokenDeclVar declFunc in sdtClass.members)
  258. {
  259. if(declFunc.retType != null)
  260. {
  261. declFunc.GetDelType();
  262. if(declFunc.funcNameSig.val.StartsWith("$ctor("))
  263. {
  264. // this is for the "$new()" static method that we create below.
  265. // See GenerateStmtNewobj() etc.
  266. _ = new TokenTypeSDTypeDelegate(declFunc, sdtClass.MakeRefToken(declFunc),
  267. declFunc.argDecl.types, tokenScript);
  268. }
  269. }
  270. }
  271. }
  272. if(sdType is TokenDeclSDTypeInterface sdtIFace)
  273. {
  274. foreach(TokenDeclVar declFunc in sdtIFace.methsNProps)
  275. {
  276. if(declFunc.retType != null)
  277. {
  278. declFunc.GetDelType();
  279. }
  280. }
  281. }
  282. itIsAGoodDayToDie = true;
  283. }
  284. break;
  285. }
  286. catch(InvalidOperationException)
  287. {
  288. if(!itIsAGoodDayToDie)
  289. throw;
  290. // fetching the delegate created an anonymous entry in tokenScript.sdSrcTypesValues
  291. // which made the foreach statement puque, so start over...
  292. }
  293. }
  294. // No more types can be defined or we won't be able to write them to the object file.
  295. tokenScript.sdSrcTypesSeal();
  296. // Assign all global variables a slot in its corresponding XMRInstance.gbl<Type>s[] array.
  297. // Global variables are simply elements of those arrays at runtime, thus we don't need to create
  298. // an unique class for each script, we can just use XMRInstance as is for all.
  299. foreach(TokenDeclVar declVar in tokenScript.variablesStack)
  300. {
  301. // Omit 'constant' variables as they are coded inline so don't need a slot.
  302. if(declVar.constant)
  303. continue;
  304. // Do functions later.
  305. if(declVar.retType != null)
  306. continue;
  307. // Create entry in the value array for the variable or property.
  308. declVar.location = new CompValuGlobalVar(declVar, glblSizes);
  309. }
  310. // Likewise for any static fields in script-defined classes.
  311. // They can be referenced anywhere by <typename>.<fieldname>, see
  312. // GenerateFromLValSField().
  313. foreach(TokenDeclSDType sdType in tokenScript.sdSrcTypesValues)
  314. {
  315. if(sdType is not TokenDeclSDTypeClass)
  316. continue;
  317. TokenDeclSDTypeClass sdtClass = (TokenDeclSDTypeClass)sdType;
  318. foreach(TokenDeclVar declVar in sdtClass.members)
  319. {
  320. // Omit 'constant' variables as they are coded inline so don't need a slot.
  321. if(declVar.constant)
  322. continue;
  323. // Do methods later.
  324. if(declVar.retType != null)
  325. continue;
  326. // Ignore non-static fields for now.
  327. // They get assigned below.
  328. if((declVar.sdtFlags & ScriptReduce.SDT_STATIC) == 0)
  329. continue;
  330. // Create entry in the value array for the static field or static property.
  331. declVar.location = new CompValuGlobalVar(declVar, glblSizes);
  332. }
  333. }
  334. // Assign slots for all interface method prototypes.
  335. // These indices are used to index the array of delegates that holds a class' implementation of an
  336. // interface.
  337. // Properties do not get a slot because they aren't called as such. But their corresponding
  338. // <name>$get() and <name>$set(<type>) methods are in the table and they each get a slot.
  339. foreach(TokenDeclSDType sdType in tokenScript.sdSrcTypesValues)
  340. {
  341. if(sdType is not TokenDeclSDTypeInterface sdtIFace)
  342. continue;
  343. int vti = 0;
  344. foreach(TokenDeclVar im in sdtIFace.methsNProps)
  345. {
  346. if((im.getProp == null) && (im.setProp == null))
  347. {
  348. im.vTableIndex = vti++;
  349. }
  350. }
  351. }
  352. // Assign slots for all instance fields and virtual methods of script-defined classes.
  353. int maxExtends = tokenScript.sdSrcTypesCount;
  354. bool didOne;
  355. do
  356. {
  357. didOne = false;
  358. foreach(TokenDeclSDType sdType in tokenScript.sdSrcTypesValues)
  359. {
  360. if(sdType is not TokenDeclSDTypeClass sdtClass)
  361. continue;
  362. if(sdtClass.slotsAssigned)
  363. continue;
  364. // If this class extends another, the extended class has to already
  365. // be set up, because our slots add on to the end of the extended class.
  366. TokenDeclSDTypeClass extends = sdtClass.extends;
  367. if(extends != null)
  368. {
  369. if(!extends.slotsAssigned)
  370. continue;
  371. sdtClass.instSizes = extends.instSizes;
  372. sdtClass.numVirtFuncs = extends.numVirtFuncs;
  373. sdtClass.numInterfaces = extends.numInterfaces;
  374. int n = maxExtends;
  375. for(TokenDeclSDTypeClass ex = extends; ex != null; ex = ex.extends)
  376. {
  377. if(--n < 0)
  378. break;
  379. }
  380. if(n < 0)
  381. {
  382. ErrorMsg(sdtClass, "loop in extended classes");
  383. sdtClass.slotsAssigned = true;
  384. continue;
  385. }
  386. }
  387. // Extended class's slots all assigned, assign our instance fields
  388. // slots in the XMRSDTypeClObj arrays.
  389. foreach(TokenDeclVar declVar in sdtClass.members)
  390. {
  391. if(declVar.retType != null)
  392. continue;
  393. if(declVar.constant)
  394. continue;
  395. if((declVar.sdtFlags & ScriptReduce.SDT_STATIC) != 0)
  396. continue;
  397. if((declVar.getProp == null) && (declVar.setProp == null))
  398. {
  399. declVar.type.AssignVarSlot(declVar, sdtClass.instSizes);
  400. }
  401. }
  402. // ... and assign virtual method vtable slots.
  403. //
  404. // - : error if any overridden method, doesn't need a slot
  405. // abstract : error if any overridden method, alloc new slot but leave it empty
  406. // new : ignore any overridden method, doesn't need a slot
  407. // new abstract : ignore any overridden method, alloc new slot but leave it empty
  408. // override : must have overridden abstract/virtual, use old slot
  409. // override abstract : must have overridden abstract, use old slot but it is still empty
  410. // static : error if any overridden method, doesn't need a slot
  411. // static new : ignore any overridden method, doesn't need a slot
  412. // virtual : error if any overridden method, alloc new slot and fill it in
  413. // virtual new : ignore any overridden method, alloc new slot and fill it in
  414. foreach(TokenDeclVar declFunc in sdtClass.members)
  415. {
  416. if(declFunc.retType == null)
  417. continue;
  418. curDeclFunc = declFunc;
  419. // See if there is a method in an extended class that this method overshadows.
  420. // If so, check for various conflicts.
  421. // In any case, SDT_NEW on our method means to ignore any overshadowed method.
  422. string declLongName = sdtClass.longName.val + "." + declFunc.funcNameSig.val;
  423. uint declFlags = declFunc.sdtFlags;
  424. TokenDeclVar overridden = null;
  425. if((declFlags & ScriptReduce.SDT_NEW) == 0)
  426. {
  427. for(TokenDeclSDTypeClass sdtd = extends; sdtd != null; sdtd = sdtd.extends)
  428. {
  429. overridden = FindExactWithRet(sdtd.members, declFunc.name, declFunc.retType, declFunc.argDecl.types);
  430. if(overridden != null)
  431. break;
  432. }
  433. }
  434. if(overridden != null)
  435. do
  436. {
  437. string overLongName = overridden.sdtClass.longName.val;
  438. uint overFlags = overridden.sdtFlags;
  439. // See if overridden method allows itself to be overridden.
  440. if((overFlags & ScriptReduce.SDT_ABSTRACT) != 0)
  441. {
  442. if((declFlags & (ScriptReduce.SDT_ABSTRACT | ScriptReduce.SDT_OVERRIDE)) == 0)
  443. {
  444. ErrorMsg(declFunc, declLongName + " overshadows abstract " + overLongName + " but is not marked abstract, new or override");
  445. break;
  446. }
  447. }
  448. else if((overFlags & ScriptReduce.SDT_FINAL) != 0)
  449. {
  450. ErrorMsg(declFunc, declLongName + " overshadows final " + overLongName + " but is not marked new");
  451. }
  452. else if((overFlags & (ScriptReduce.SDT_OVERRIDE | ScriptReduce.SDT_VIRTUAL)) != 0)
  453. {
  454. if((declFlags & (ScriptReduce.SDT_NEW | ScriptReduce.SDT_OVERRIDE)) == 0)
  455. {
  456. ErrorMsg(declFunc, declLongName + " overshadows virtual " + overLongName + " but is not marked new or override");
  457. break;
  458. }
  459. }
  460. else
  461. {
  462. ErrorMsg(declFunc, declLongName + " overshadows non-virtual " + overLongName + " but is not marked new");
  463. break;
  464. }
  465. // See if our method is capable of overriding the other method.
  466. if((declFlags & ScriptReduce.SDT_ABSTRACT) != 0)
  467. {
  468. if((overFlags & ScriptReduce.SDT_ABSTRACT) == 0)
  469. {
  470. ErrorMsg(declFunc, declLongName + " abstract overshadows non-abstract " + overLongName + " but is not marked new");
  471. break;
  472. }
  473. }
  474. else if((declFlags & ScriptReduce.SDT_OVERRIDE) != 0)
  475. {
  476. if((overFlags & (ScriptReduce.SDT_ABSTRACT | ScriptReduce.SDT_OVERRIDE | ScriptReduce.SDT_VIRTUAL)) == 0)
  477. {
  478. ErrorMsg(declFunc, declLongName + " override overshadows non-abstract/non-virtual " + overLongName);
  479. break;
  480. }
  481. }
  482. else
  483. {
  484. ErrorMsg(declFunc, declLongName + " overshadows " + overLongName + " but is not marked new");
  485. break;
  486. }
  487. } while(false);
  488. // Now we can assign it a vtable slot if it needs one (ie, it is virtual).
  489. declFunc.vTableIndex = -1;
  490. if(overridden != null)
  491. {
  492. declFunc.vTableIndex = overridden.vTableIndex;
  493. }
  494. else if((declFlags & ScriptReduce.SDT_OVERRIDE) != 0)
  495. {
  496. ErrorMsg(declFunc, declLongName + " marked override but nothing matching found that it overrides");
  497. }
  498. if((declFlags & (ScriptReduce.SDT_ABSTRACT | ScriptReduce.SDT_VIRTUAL)) != 0)
  499. {
  500. declFunc.vTableIndex = sdtClass.numVirtFuncs++;
  501. }
  502. }
  503. curDeclFunc = null;
  504. // ... and assign implemented interface slots.
  505. // Note that our implementations of a given interface is completely independent of any
  506. // rootward class's implementation of that same interface.
  507. int nIFaces = sdtClass.numInterfaces + sdtClass.implements.Count;
  508. sdtClass.iFaces = new TokenDeclSDTypeInterface[nIFaces];
  509. sdtClass.iImplFunc = new TokenDeclVar[nIFaces][];
  510. for(int i = 0; i < sdtClass.numInterfaces; i++)
  511. {
  512. sdtClass.iFaces[i] = extends.iFaces[i];
  513. sdtClass.iImplFunc[i] = extends.iImplFunc[i];
  514. }
  515. foreach(TokenDeclSDTypeInterface intf in sdtClass.implements)
  516. {
  517. int i = sdtClass.numInterfaces++;
  518. sdtClass.iFaces[i] = intf;
  519. sdtClass.intfIndices.Add(intf.longName.val, i);
  520. int nMeths = 0;
  521. foreach(TokenDeclVar m in intf.methsNProps)
  522. {
  523. if((m.getProp == null) && (m.setProp == null))
  524. nMeths++;
  525. }
  526. sdtClass.iImplFunc[i] = new TokenDeclVar[nMeths];
  527. }
  528. foreach(TokenDeclVar classMeth in sdtClass.members)
  529. {
  530. if(classMeth.retType == null)
  531. continue;
  532. curDeclFunc = classMeth;
  533. for(TokenIntfImpl intfImpl = classMeth.implements; intfImpl != null; intfImpl = (TokenIntfImpl)intfImpl.nextToken)
  534. {
  535. // One of the class methods implements an interface method.
  536. // Try to find the interface method that is implemented and verify its signature.
  537. TokenDeclSDTypeInterface intfType = intfImpl.intfType.decl;
  538. TokenDeclVar intfMeth = FindExactWithRet(intfType.methsNProps, intfImpl.methName, classMeth.retType, classMeth.argDecl.types);
  539. if(intfMeth == null)
  540. {
  541. ErrorMsg(intfImpl, "interface does not define method " + intfImpl.methName.val + classMeth.argDecl.GetArgSig());
  542. continue;
  543. }
  544. // See if this class was declared to implement that interface.
  545. bool found = false;
  546. foreach(TokenDeclSDTypeInterface intf in sdtClass.implements)
  547. {
  548. if(intf == intfType)
  549. {
  550. found = true;
  551. break;
  552. }
  553. }
  554. if(!found)
  555. {
  556. ErrorMsg(intfImpl, "class not declared to implement " + intfType.longName.val);
  557. continue;
  558. }
  559. // Get index in iFaces[] and iImplFunc[] arrays.
  560. // Start scanning from the end in case one of our rootward classes also implements the interface.
  561. // We should always be successful because we know by now that this class implements the interface.
  562. int i;
  563. for(i = sdtClass.numInterfaces; --i >= 0;)
  564. {
  565. if(sdtClass.iFaces[i] == intfType)
  566. break;
  567. }
  568. // Now remember which of the class methods implements that interface method.
  569. int j = intfMeth.vTableIndex;
  570. if(sdtClass.iImplFunc[i][j] != null)
  571. {
  572. ErrorMsg(intfImpl, "also implemented by " + sdtClass.iImplFunc[i][j].funcNameSig.val);
  573. continue;
  574. }
  575. sdtClass.iImplFunc[i][j] = classMeth;
  576. }
  577. }
  578. curDeclFunc = null;
  579. // Now make sure this class implements all methods for all declared interfaces.
  580. for(int i = sdtClass.numInterfaces - sdtClass.implements.Count; i < sdtClass.numInterfaces; i++)
  581. {
  582. TokenDeclVar[] implementations = sdtClass.iImplFunc[i];
  583. for(int j = implementations.Length; --j >= 0;)
  584. {
  585. if(implementations[j] == null)
  586. {
  587. TokenDeclSDTypeInterface intf = sdtClass.iFaces[i];
  588. TokenDeclVar meth = null;
  589. foreach(TokenDeclVar im in intf.methsNProps)
  590. {
  591. if(im.vTableIndex == j)
  592. {
  593. meth = im;
  594. break;
  595. }
  596. }
  597. ErrorMsg(sdtClass, "does not implement " + intf.longName.val + "." + meth.funcNameSig.val);
  598. }
  599. }
  600. }
  601. // All slots for this class have been assigned.
  602. sdtClass.slotsAssigned = true;
  603. didOne = true;
  604. }
  605. } while(didOne);
  606. // Compute final values for all variables/fields declared as 'constant'.
  607. // Note that there may be forward references.
  608. do
  609. {
  610. didOne = false;
  611. foreach(TokenDeclVar tdv in tokenScript.variablesStack)
  612. {
  613. if(tdv.constant && tdv.init is not TokenRValConst)
  614. {
  615. tdv.init = tdv.init.TryComputeConstant(LookupInitConstants, ref didOne);
  616. }
  617. }
  618. foreach(TokenDeclSDType sdType in tokenScript.sdSrcTypesValues)
  619. {
  620. if(sdType is not TokenDeclSDTypeClass TokenDeclSDTypeClasssdType)
  621. continue;
  622. currentSDTClass = TokenDeclSDTypeClasssdType;
  623. foreach(TokenDeclVar tdv in currentSDTClass.members)
  624. {
  625. if(tdv.constant && tdv.init is not TokenRValConst)
  626. {
  627. tdv.init = tdv.init.TryComputeConstant(LookupInitConstants, ref didOne);
  628. }
  629. }
  630. }
  631. currentSDTClass = null;
  632. } while(didOne);
  633. // Now we should be able to assign all those constants their type and location.
  634. foreach(TokenDeclVar tdv in tokenScript.variablesStack)
  635. {
  636. if(tdv.constant)
  637. {
  638. if (tdv.init is TokenRValConst rvc)
  639. {
  640. tdv.type = rvc.tokType;
  641. tdv.location = rvc.GetCompValu();
  642. }
  643. else
  644. {
  645. ErrorMsg(tdv, "value is not constant");
  646. }
  647. }
  648. }
  649. foreach(TokenDeclSDType sdType in tokenScript.sdSrcTypesValues)
  650. {
  651. if(sdType is not TokenDeclSDTypeClass TokenDeclSDTypeClasssdType)
  652. continue;
  653. currentSDTClass = TokenDeclSDTypeClasssdType;
  654. foreach(TokenDeclVar tdv in currentSDTClass.members)
  655. {
  656. if(tdv.constant)
  657. {
  658. if (tdv.init is TokenRValConst rvc)
  659. {
  660. tdv.type = rvc.tokType;
  661. tdv.location = rvc.GetCompValu();
  662. }
  663. else
  664. {
  665. ErrorMsg(tdv, "value is not constant");
  666. }
  667. }
  668. }
  669. }
  670. currentSDTClass = null;
  671. // For all classes that define all the methods needed for the class, ie, they aren't abstract,
  672. // define a static class.$new() method with same args as the $ctor(s). This will allow the
  673. // class to be instantiated via the new operator.
  674. foreach(TokenDeclSDType sdType in tokenScript.sdSrcTypesValues)
  675. {
  676. if(sdType is not TokenDeclSDTypeClass sdtClass)
  677. continue;
  678. // See if the class as it stands would be able to fill every slot of its vtable.
  679. bool[] filled = new bool[sdtClass.numVirtFuncs];
  680. int numFilled = 0;
  681. for(TokenDeclSDTypeClass sdtc = sdtClass; sdtc != null; sdtc = sdtc.extends)
  682. {
  683. foreach(TokenDeclVar tdf in sdtc.members)
  684. {
  685. if((tdf.retType != null) && (tdf.vTableIndex >= 0) && ((tdf.sdtFlags & ScriptReduce.SDT_ABSTRACT) == 0))
  686. {
  687. if(!filled[tdf.vTableIndex])
  688. {
  689. filled[tdf.vTableIndex] = true;
  690. numFilled++;
  691. }
  692. }
  693. }
  694. }
  695. // If so, define a static class.$new() method for every constructor defined for the class.
  696. // Give it the same access (private/protected/public) as the script declared for the constructor.
  697. // Note that the reducer made sure there is at least a default constructor for every class.
  698. if(numFilled >= sdtClass.numVirtFuncs)
  699. {
  700. List<TokenDeclVar> newobjDeclFuncs = new ();
  701. foreach(TokenDeclVar ctorDeclFunc in sdtClass.members)
  702. {
  703. if((ctorDeclFunc.funcNameSig != null) && ctorDeclFunc.funcNameSig.val.StartsWith("$ctor("))
  704. {
  705. TokenDeclVar newobjDeclFunc = DefineNewobjFunc(ctorDeclFunc);
  706. newobjDeclFuncs.Add(newobjDeclFunc);
  707. }
  708. }
  709. foreach(TokenDeclVar newobjDeclFunc in newobjDeclFuncs)
  710. {
  711. sdtClass.members.AddEntry(newobjDeclFunc);
  712. }
  713. }
  714. }
  715. // Write fixed portion of object file.
  716. objFileWriter.Write(OBJECT_CODE_MAGIC.ToCharArray());
  717. objFileWriter.Write(COMPILED_VERSION_VALUE);
  718. objFileWriter.Write(sourceHash);
  719. glblSizes.WriteToFile(objFileWriter);
  720. objFileWriter.Write(nStates);
  721. for(int i = 0; i < nStates; i++)
  722. {
  723. objFileWriter.Write(stateNames[i]);
  724. }
  725. // For debugging, we also write out global variable array slot assignments.
  726. foreach(TokenDeclVar declVar in tokenScript.variablesStack)
  727. {
  728. if(declVar.retType == null)
  729. {
  730. WriteOutGblAssignment("", declVar);
  731. }
  732. }
  733. foreach(TokenDeclSDType sdType in tokenScript.sdSrcTypesValues)
  734. {
  735. if(sdType is not TokenDeclSDTypeClass sdtClass)
  736. continue;
  737. foreach(TokenDeclVar declVar in sdtClass.members)
  738. {
  739. if((declVar.sdtFlags & ScriptReduce.SDT_STATIC) != 0)
  740. {
  741. WriteOutGblAssignment(sdtClass.longName.val + ".", declVar);
  742. }
  743. }
  744. }
  745. objFileWriter.Write("");
  746. // Write out script-defined types.
  747. foreach(TokenDeclSDType sdType in tokenScript.sdSrcTypesValues)
  748. {
  749. objFileWriter.Write(sdType.longName.val);
  750. sdType.WriteToFile(objFileWriter);
  751. }
  752. objFileWriter.Write("");
  753. // Output function headers then bodies.
  754. // Do all headers first in case bodies do forward references.
  755. // Do both global functions, script-defined class static methods and
  756. // script-defined instance methods, as we handle the differences
  757. // during compilation of the functions/methods themselves.
  758. // headers
  759. foreach(TokenDeclVar declFunc in tokenScript.variablesStack)
  760. {
  761. if(declFunc.retType != null)
  762. GenerateMethodHeader(declFunc);
  763. }
  764. foreach(TokenDeclSDType sdType in tokenScript.sdSrcTypesValues)
  765. {
  766. if (sdType is TokenDeclSDTypeClass sdtClass)
  767. {
  768. foreach (TokenDeclVar declFunc in sdtClass.members)
  769. {
  770. if ((declFunc.retType != null) && ((declFunc.sdtFlags & ScriptReduce.SDT_ABSTRACT) == 0))
  771. GenerateMethodHeader(declFunc);
  772. }
  773. }
  774. }
  775. // now bodies
  776. foreach(TokenDeclVar declFunc in tokenScript.variablesStack)
  777. {
  778. if(declFunc.retType != null)
  779. GenerateMethodBody(declFunc);
  780. }
  781. foreach(TokenDeclSDType sdType in tokenScript.sdSrcTypesValues)
  782. {
  783. if (sdType is TokenDeclSDTypeClass sdtClass)
  784. {
  785. foreach (TokenDeclVar declFunc in sdtClass.members)
  786. {
  787. if ((declFunc.retType != null) && ((declFunc.sdtFlags & ScriptReduce.SDT_ABSTRACT) == 0))
  788. GenerateMethodBody(declFunc);
  789. }
  790. }
  791. }
  792. // Output default state event handler functions.
  793. // Each event handler is a private static method named 'default <eventname>'.
  794. // Splice in a default state_entry() handler if none defined so we can init global vars.
  795. TokenDeclVar defaultStateEntry = tokenScript.defaultState.body.eventFuncs;
  796. while(defaultStateEntry != null)
  797. {
  798. if("state_entry()".Equals(defaultStateEntry.funcNameSig.val))
  799. break;
  800. defaultStateEntry = (TokenDeclVar)defaultStateEntry.nextToken;
  801. }
  802. if (defaultStateEntry == null)
  803. {
  804. defaultStateEntry = new TokenDeclVar(tokenScript.defaultState.body, null, tokenScript)
  805. {
  806. name = new TokenName(tokenScript.defaultState.body, "state_entry"),
  807. retType = new TokenTypeVoid(tokenScript.defaultState.body),
  808. argDecl = new TokenArgDecl(tokenScript.defaultState.body),
  809. body = new TokenStmtBlock(tokenScript.defaultState.body)
  810. };
  811. defaultStateEntry.body.function = defaultStateEntry;
  812. defaultStateEntry.nextToken = tokenScript.defaultState.body.eventFuncs;
  813. tokenScript.defaultState.body.eventFuncs = defaultStateEntry;
  814. }
  815. GenerateStateEventHandlers("default", tokenScript.defaultState.body);
  816. // Output script-defined state event handler methods.
  817. // Each event handler is a private static method named <statename> <eventname>
  818. foreach(KeyValuePair<string, TokenDeclState> kvp in tokenScript.states)
  819. {
  820. TokenDeclState declState = kvp.Value;
  821. GenerateStateEventHandlers(declState.name.val, declState.body);
  822. }
  823. ScriptObjWriter.TheEnd(objFileWriter);
  824. }
  825. /**
  826. * @brief Write out what slot was assigned for a global or sdtclass static variable.
  827. * Constants, functions, instance fields, methods, properties do not have slots in the global variables arrays.
  828. */
  829. private void WriteOutGblAssignment(string pfx, TokenDeclVar declVar)
  830. {
  831. if(!declVar.constant && (declVar.retType == null) && (declVar.getProp == null) && (declVar.setProp == null))
  832. {
  833. objFileWriter.Write(pfx + declVar.name.val); // string
  834. objFileWriter.Write(declVar.vTableArray.Name); // string
  835. objFileWriter.Write(declVar.vTableIndex); // int
  836. }
  837. }
  838. /**
  839. * @brief generate event handler code
  840. * Writes out a function definition for each state handler
  841. * named <statename> <eventname>
  842. *
  843. * However, each has just 'XMRInstance __sw' as its single argument
  844. * and each of its user-visible argments is extracted from __sw.ehArgs[].
  845. *
  846. * So we end up generating something like this:
  847. *
  848. * private static void <statename> <eventname>(XMRInstance __sw)
  849. * {
  850. * <typeArg0> <nameArg0> = (<typeArg0>)__sw.ehArgs[0];
  851. * <typeArg1> <nameArg1> = (<typeArg1>)__sw.ehArgs[1];
  852. *
  853. * ... script code ...
  854. * }
  855. *
  856. * The continuations code assumes there will be no references to ehArgs[]
  857. * after the first call to CheckRun() as CheckRun() makes no attempt to
  858. * serialize the ehArgs[] array, as doing so would be redundant. Any values
  859. * from ehArgs[] that are being used will be in local stack variables and
  860. * thus preserved that way.
  861. */
  862. private void GenerateStateEventHandlers(string statename, TokenStateBody body)
  863. {
  864. Dictionary<string, TokenDeclVar> statehandlers = new();
  865. for(Token t = body.eventFuncs; t != null; t = t.nextToken)
  866. {
  867. TokenDeclVar tdv = (TokenDeclVar)t;
  868. string eventname = tdv.GetSimpleName();
  869. if(statehandlers.TryAdd(eventname, tdv))
  870. GenerateEventHandler(statename, tdv);
  871. else
  872. ErrorMsg(tdv, "event handler " + eventname + " already defined for state " + statename);
  873. }
  874. }
  875. private void GenerateEventHandler(string statename, TokenDeclVar declFunc)
  876. {
  877. string eventname = declFunc.GetSimpleName();
  878. TokenArgDecl argDecl = declFunc.argDecl;
  879. // Make sure event handler name is valid and that number and type of arguments is correct.
  880. // Apparently some scripts exist with fewer than correct number of args in their declaration
  881. // so allow for that. It is ok because the handlers are called with the arguments in an
  882. // object[] array, and we just won't access the missing argments in the vector. But the
  883. // specified types must match one of the prototypes in legalEventHandlers.
  884. TokenDeclVar protoDeclFunc = legalEventHandlers.FindExact(eventname, argDecl.types);
  885. if(protoDeclFunc == null)
  886. {
  887. ErrorMsg(declFunc, "unknown event handler " + eventname + argDecl.GetArgSig());
  888. return;
  889. }
  890. // Output function header.
  891. // They just have the XMRInstAbstract pointer as the one argument.
  892. string functionName = statename + " " + eventname;
  893. _ilGen = new ScriptObjWriter(tokenScript,
  894. functionName,
  895. typeof(void),
  896. instanceTypeArg,
  897. instanceNameArg,
  898. objFileWriter);
  899. StartFunctionBody(declFunc);
  900. // Create a temp to hold XMRInstanceSuperType version of arg 0.
  901. instancePointer = ilGen.DeclareLocal(xmrInstSuperType, "__xmrinst");
  902. ilGen.Emit(declFunc, OpCodes.Ldarg_0);
  903. ilGen.Emit(declFunc, OpCodes.Castclass, xmrInstSuperType);
  904. ilGen.Emit(declFunc, OpCodes.Stloc, instancePointer);
  905. if (!"$globalvarinit()".Equals(curDeclFunc.fullName))
  906. {
  907. PushXMRInst();
  908. ilGen.Emit(curDeclFunc, OpCodes.Ldfld, heapUsedFieldInfo);
  909. curHeapSize = ilGen.DeclareLocal(typeof(int), "__curHeap");
  910. ilGen.Emit(curDeclFunc, OpCodes.Stloc, curHeapSize);
  911. }
  912. // Output args as variable definitions and initialize each from __sw.ehArgs[].
  913. // If the script writer goofed, the typecast will complain.
  914. for(int i = 0; i < argDecl.vars.Length; i++)
  915. {
  916. // Say that the argument variable is going to be located in a local var.
  917. TokenDeclVar argVar = argDecl.vars[i];
  918. TokenType argTokType = argVar.type;
  919. CompValuLocalVar local = new (argTokType, argVar.name.val, this);
  920. argVar.location = local;
  921. // Copy from the ehArgs[i] element to the temp var.
  922. // Cast as needed, there is a lot of craziness like OpenMetaverse.Quaternion.
  923. local.PopPre(this, argVar.name);
  924. PushXMRInst(); // instance
  925. ilGen.Emit(declFunc, OpCodes.Ldfld, ehArgsFieldInfo); // instance.ehArgs (array of objects)
  926. ilGen.Emit(declFunc, OpCodes.Ldc_I4, i); // array index = i
  927. ilGen.Emit(declFunc, OpCodes.Ldelem, typeof(object)); // select the argument we want
  928. TokenType stkTokType = tokenTypeObj; // stack has a type 'object' on it now
  929. Type argSysType = argTokType.ToSysType(); // this is the type the script expects
  930. if (argSysType == typeof(int))
  931. { // LSL_Integer/int -> int
  932. ilGen.Emit(declFunc, OpCodes.Call, ehArgUnwrapInteger);
  933. stkTokType = tokenTypeInt; // stack has a type 'int' on it now
  934. }
  935. else if (argSysType == typeof(string))
  936. { // LSL_Key/LSL_String/string -> string
  937. ilGen.Emit(declFunc, OpCodes.Call, ehArgUnwrapString);
  938. stkTokType = tokenTypeStr; // stack has a type 'string' on it now
  939. }
  940. else if (argSysType == typeof(double))
  941. { // LSL_Float/double -> double
  942. ilGen.Emit(declFunc, OpCodes.Call, ehArgUnwrapFloat);
  943. stkTokType = tokenTypeFlt; // stack has a type 'double' on it now
  944. }
  945. else if (argSysType == typeof(LSL_Vector))
  946. { // OpenMetaverse.Vector3/LSL_Vector -> LSL_Vector
  947. ilGen.Emit(declFunc, OpCodes.Call, ehArgUnwrapVector);
  948. stkTokType = tokenTypeVec; // stack has a type 'LSL_Vector' on it now
  949. }
  950. else if (argSysType == typeof(LSL_List))
  951. { // LSL_List -> LSL_List
  952. TypeCast.CastTopOfStack(this, argVar.name, stkTokType, argTokType, true);
  953. stkTokType = argTokType; // stack has a type 'LSL_List' on it now
  954. }
  955. else if (argSysType == typeof(LSL_Rotation))
  956. { // OpenMetaverse.Quaternion/LSL_Rotation -> LSL_Rotation
  957. ilGen.Emit(declFunc, OpCodes.Call, ehArgUnwrapRotation);
  958. stkTokType = tokenTypeRot; // stack has a type 'LSL_Rotation' on it now
  959. }
  960. local.PopPost(this, argVar.name, stkTokType); // pop stack type into argtype
  961. }
  962. // Output code for the statements and clean up.
  963. GenerateFuncBody();
  964. }
  965. /**
  966. * @brief generate header for an arbitrary script-defined global function.
  967. * @param declFunc = function being defined
  968. */
  969. private void GenerateMethodHeader(TokenDeclVar declFunc)
  970. {
  971. curDeclFunc = declFunc;
  972. // Make up array of all argument types as seen by the code generator.
  973. // We splice in XMRInstanceSuperType or XMRSDTypeClObj for the first
  974. // arg as the function itself is static, followed by script-visible
  975. // arg types.
  976. TokenArgDecl argDecl = declFunc.argDecl;
  977. int nArgs = argDecl.vars.Length;
  978. Type[] argTypes = new Type[nArgs + 1];
  979. string[] argNames = new string[nArgs + 1];
  980. if(IsSDTInstMethod())
  981. {
  982. argTypes[0] = typeof(XMRSDTypeClObj);
  983. argNames[0] = "$sdtthis";
  984. }
  985. else
  986. {
  987. argTypes[0] = xmrInstSuperType;
  988. argNames[0] = "$xmrthis";
  989. }
  990. for(int i = 0; i < nArgs; i++)
  991. {
  992. argTypes[i + 1] = argDecl.vars[i].type.ToSysType();
  993. argNames[i + 1] = argDecl.vars[i].name.val;
  994. }
  995. // Set up entrypoint.
  996. string objCodeName = declFunc.GetObjCodeName();
  997. declFunc.ilGen = new ScriptObjWriter(tokenScript,
  998. objCodeName,
  999. declFunc.retType.ToSysType(),
  1000. argTypes,
  1001. argNames,
  1002. objFileWriter);
  1003. // This says how to generate a call to the function and to get a delegate.
  1004. declFunc.location = new CompValuGlobalMeth(declFunc);
  1005. curDeclFunc = null;
  1006. }
  1007. /**
  1008. * @brief generate code for an arbitrary script-defined function.
  1009. * @param name = name of the function
  1010. * @param argDecl = argument declarations
  1011. * @param body = function's code body
  1012. */
  1013. private void GenerateMethodBody(TokenDeclVar declFunc)
  1014. {
  1015. if ("$globalvarinit()".Equals(declFunc.fullName))
  1016. {
  1017. if(declFunc.body?.statements == null)
  1018. return;
  1019. }
  1020. // Set up code generator for the function's contents.
  1021. _ilGen = declFunc.ilGen;
  1022. StartFunctionBody(declFunc);
  1023. // Create a temp to hold XMRInstanceSuperType version of arg 0.
  1024. // For most functions, arg 0 is already XMRInstanceSuperType.
  1025. // But for script-defined class instance methods, arg 0 holds
  1026. // the XMRSDTypeClObj pointer and so we read the XMRInstAbstract
  1027. // pointer from its XMRSDTypeClObj.xmrInst field then cast it to
  1028. // XMRInstanceSuperType.
  1029. if (IsSDTInstMethod())
  1030. {
  1031. instancePointer = ilGen.DeclareLocal(xmrInstSuperType, "__xmrinst");
  1032. ilGen.Emit(declFunc, OpCodes.Ldarg_0);
  1033. ilGen.Emit(declFunc, OpCodes.Ldfld, sdtXMRInstFieldInfo);
  1034. ilGen.Emit(declFunc, OpCodes.Castclass, xmrInstSuperType);
  1035. ilGen.Emit(declFunc, OpCodes.Stloc, instancePointer);
  1036. }
  1037. if (!("$globalvarinit()".Equals(declFunc.fullName)))
  1038. {
  1039. PushXMRInst();
  1040. ilGen.Emit(curDeclFunc, OpCodes.Ldfld, heapUsedFieldInfo);
  1041. curHeapSize = ilGen.DeclareLocal(typeof(int), "__curHeap");
  1042. ilGen.Emit(curDeclFunc, OpCodes.Stloc, curHeapSize);
  1043. }
  1044. // Define location of all script-level arguments so script body can access them.
  1045. // The argument indices need to have +1 added to them because XMRInstance or
  1046. // XMRSDTypeClObj is spliced in at arg 0.
  1047. TokenArgDecl argDecl = declFunc.argDecl;
  1048. for(int i = 0; i < argDecl.vars.Length; i++)
  1049. {
  1050. TokenDeclVar argVar = argDecl.vars[i];
  1051. argVar.location = new CompValuArg(argVar.type, i + 1);
  1052. }
  1053. // Output code for the statements and clean up.
  1054. GenerateFuncBody();
  1055. }
  1056. private void StartFunctionBody(TokenDeclVar declFunc)
  1057. {
  1058. // Start current function being processed.
  1059. // Set 'mightGetHere' as the code at the top is always executed.
  1060. instancePointer = null;
  1061. mightGetHere = true;
  1062. curBreakTarg = null;
  1063. curContTarg = null;
  1064. curDeclFunc = declFunc;
  1065. // Start generating code.
  1066. ((ScriptObjWriter)ilGen).BegMethod();
  1067. }
  1068. /**
  1069. * @brief Define function for a script-defined type's <typename>.$new(<argsig>) method.
  1070. * See GenerateStmtNewobj() for more info.
  1071. */
  1072. private TokenDeclVar DefineNewobjFunc(TokenDeclVar ctorDeclFunc)
  1073. {
  1074. // Set up 'static classname $new(params-same-as-ctor) { }'.
  1075. TokenDeclVar newobjDeclFunc = new (ctorDeclFunc, null, tokenScript);
  1076. newobjDeclFunc.name = new TokenName(newobjDeclFunc, "$new");
  1077. newobjDeclFunc.retType = ctorDeclFunc.sdtClass.MakeRefToken(newobjDeclFunc);
  1078. newobjDeclFunc.argDecl = ctorDeclFunc.argDecl;
  1079. newobjDeclFunc.sdtClass = ctorDeclFunc.sdtClass;
  1080. newobjDeclFunc.sdtFlags = ScriptReduce.SDT_STATIC | ctorDeclFunc.sdtFlags;
  1081. // Declare local variable named '$objptr' in a frame just under
  1082. // what the '$new(...)' function's arguments are declared in.
  1083. TokenDeclVar objptrVar = new (newobjDeclFunc, newobjDeclFunc, tokenScript)
  1084. {
  1085. type = newobjDeclFunc.retType,
  1086. name = new TokenName(newobjDeclFunc, "$objptr")
  1087. };
  1088. VarDict newFrame = new (false)
  1089. {
  1090. outerVarDict = ctorDeclFunc.argDecl.varDict
  1091. };
  1092. newFrame.AddEntry(objptrVar);
  1093. // Set up '$objptr.$ctor'
  1094. TokenLValName objptrLValName = new (objptrVar.name, newFrame);
  1095. // ref a var by giving its name
  1096. TokenLValIField objptrDotCtor = new (newobjDeclFunc)
  1097. {
  1098. baseRVal = objptrLValName, // '$objptr'
  1099. fieldName = ctorDeclFunc.name // '.' '$ctor'
  1100. }; // an instance member reference
  1101. // Set up '$objptr.$ctor(arglist)' call for use in the '$new(...)' body.
  1102. // Copy the arglist from the constructor declaration so triviality
  1103. // processing will pick the correct overloaded constructor.
  1104. TokenRValCall callCtorRVal = new (newobjDeclFunc)
  1105. {
  1106. meth = objptrDotCtor // calling $objptr.$ctor()
  1107. }; // doing a call of some sort
  1108. TokenDeclVar[] argList = newobjDeclFunc.argDecl.vars; // get args $new() was declared with
  1109. callCtorRVal.nArgs = argList.Length; // ...that is nArgs we are passing to $objptr.$ctor()
  1110. for(int i = argList.Length; --i >= 0;)
  1111. {
  1112. TokenDeclVar arg = argList[i]; // find out about one of the args
  1113. TokenLValName argLValName = new (arg.name, ctorDeclFunc.argDecl.varDict)
  1114. {
  1115. // pass arg of that name to $objptr.$ctor()
  1116. nextToken = callCtorRVal.args // link to list of args passed to $objptr.$ctor()
  1117. };
  1118. callCtorRVal.args = argLValName;
  1119. }
  1120. // Set up a funky call to the constructor for the code body.
  1121. // This will let code generator know there is some craziness.
  1122. // See GenerateStmtNewobj().
  1123. //
  1124. // This is in essence:
  1125. // {
  1126. // classname $objptr = newobj (classname);
  1127. // $objptr.$ctor (...);
  1128. // return $objptr;
  1129. // }
  1130. TokenStmtNewobj newobjStmtBody = new (ctorDeclFunc)
  1131. {
  1132. objptrVar = objptrVar,
  1133. rValCall = callCtorRVal
  1134. };
  1135. // Link that code as the body of the function.
  1136. newobjDeclFunc.body = new TokenStmtBlock(ctorDeclFunc)
  1137. {
  1138. statements = newobjStmtBody
  1139. };
  1140. // Say the function calls '$objptr.$ctor(arglist)' so we will inherit ctor's triviality.
  1141. newobjDeclFunc.unknownTrivialityCalls.AddLast(callCtorRVal);
  1142. return newobjDeclFunc;
  1143. }
  1144. private class TokenStmtNewobj: TokenStmt
  1145. {
  1146. public TokenDeclVar objptrVar;
  1147. public TokenRValCall rValCall;
  1148. public TokenStmtNewobj(Token original) : base(original) { }
  1149. }
  1150. /**
  1151. * @brief Output function body (either event handler or script-defined method).
  1152. */
  1153. private void GenerateFuncBody()
  1154. {
  1155. // We want to know if the function's code is trivial, ie,
  1156. // if it doesn't have anything that might be an infinite
  1157. // loop and that is doesn't call anything that might have
  1158. // an infinite loop. If it is, we don't need any CheckRun()
  1159. // stuff or any of the frame save/restore stuff.
  1160. bool isTrivial = curDeclFunc.IsFuncTrivial(this);
  1161. bool doheap = curDeclFunc.fullName != "$globalvarinit()";
  1162. // Clear list of all call labels.
  1163. // A call label is inserted just before every call that can possibly
  1164. // call CheckRun(), including any direct calls to CheckRun().
  1165. // Then, when restoring stack, we can just switch to this label to
  1166. // resume at the correct spot.
  1167. actCallLabels.Clear();
  1168. allCallLabels.Clear();
  1169. openCallLabel = null;
  1170. // Alloc stack space for local vars.
  1171. int stackframesize = AllocLocalVarStackSpace();
  1172. // Include argument variables in stack space for this frame.
  1173. foreach(TokenType tokType in curDeclFunc.argDecl.types)
  1174. {
  1175. stackframesize += LocalVarStackSize(tokType);
  1176. }
  1177. // Any return statements inside function body jump to this label
  1178. // after putting return value in __retval.
  1179. retLabel = ilGen.DefineLabel("__retlbl");
  1180. retValue = null;
  1181. if(curDeclFunc.retType is not TokenTypeVoid)
  1182. {
  1183. retValue = ilGen.DeclareLocal(curDeclFunc.retType.ToSysType(), "__retval");
  1184. }
  1185. // Output:
  1186. // int __mainCallNo = -1;
  1187. // instance.m_StackLeft -= stackframesize;
  1188. // try {
  1189. // if (instance.callMode != CallMode_NORMAL) goto __cmRestore;
  1190. actCallNo = null;
  1191. ScriptMyLabel cmRestore = null;
  1192. if (!isTrivial)
  1193. {
  1194. actCallNo = ilGen.DeclareLocal(typeof(int), "__mainCallNo");
  1195. SetCallNo(curDeclFunc, actCallNo, -1);
  1196. PushXMRInst();
  1197. ilGen.Emit(curDeclFunc, OpCodes.Dup);
  1198. ilGen.Emit(curDeclFunc, OpCodes.Ldfld, stackLeftFieldInfo);
  1199. ilGen.Emit(curDeclFunc, OpCodes.Ldc_I4, stackframesize);
  1200. ilGen.Emit(curDeclFunc, OpCodes.Sub);
  1201. ilGen.Emit(curDeclFunc, OpCodes.Stfld, stackLeftFieldInfo);
  1202. cmRestore = ilGen.DefineLabel("__cmRestore");
  1203. ilGen.BeginExceptionBlock();
  1204. PushXMRInst();
  1205. ilGen.Emit(curDeclFunc, OpCodes.Ldfld, ScriptCodeGen.callModeFieldInfo);
  1206. ilGen.Emit(curDeclFunc, OpCodes.Ldc_I4, XMRInstAbstract.CallMode_NORMAL);
  1207. ilGen.Emit(curDeclFunc, OpCodes.Bne_Un, cmRestore);
  1208. }
  1209. // Splice in the code optimizer for the body of the function.
  1210. ScriptCollector collector = new ((ScriptObjWriter)ilGen);
  1211. _ilGen = collector;
  1212. // If this is the default state_entry() handler, output code to set all global
  1213. // variables to their initial values. Note that every script must have a
  1214. // default state_entry() handler, we provide one if the script doesn't explicitly
  1215. // define one.
  1216. string methname = ilGen.methName;
  1217. if(methname == "default state_entry")
  1218. {
  1219. TokenDeclVar gviFunc = tokenScript.globalVarInit;
  1220. bool dogblinitcheck = gviFunc.body.statements != null;
  1221. if(!dogblinitcheck)
  1222. {
  1223. foreach (TokenDeclSDType sdType in tokenScript.sdSrcTypesValues)
  1224. {
  1225. if (sdType is TokenDeclSDTypeClass sdTypeClass)
  1226. {
  1227. TokenDeclVar sfiFunc = sdTypeClass.staticFieldInit;
  1228. if ((sfiFunc is not null) && (sfiFunc.body.statements is not null))
  1229. {
  1230. dogblinitcheck = true;
  1231. break;
  1232. }
  1233. }
  1234. }
  1235. }
  1236. if (dogblinitcheck)
  1237. {
  1238. // generate if (!doGblInit) goto skipGblInit;
  1239. ScriptMyLabel skipGblInitLabel = ilGen.DefineLabel("__skipGblInit");
  1240. PushXMRInst(); // instance
  1241. ilGen.Emit(curDeclFunc, OpCodes.Ldfld, doGblInitFieldInfo); // instance.doGblInit
  1242. ilGen.Emit(curDeclFunc, OpCodes.Brfalse, skipGblInitLabel);
  1243. // $globalvarinit();
  1244. if(gviFunc.body.statements != null)
  1245. {
  1246. gviFunc.location.CallPre(this, gviFunc);
  1247. gviFunc.location.CallPost(this, gviFunc);
  1248. }
  1249. // various $staticfieldinit();
  1250. foreach(TokenDeclSDType sdType in tokenScript.sdSrcTypesValues)
  1251. {
  1252. if(sdType is TokenDeclSDTypeClass sdTypeClass)
  1253. {
  1254. TokenDeclVar sfiFunc = sdTypeClass.staticFieldInit;
  1255. if((sfiFunc is not null) && (sfiFunc.body.statements is not null))
  1256. {
  1257. sfiFunc.location.CallPre(this, sfiFunc);
  1258. sfiFunc.location.CallPost(this, sfiFunc);
  1259. }
  1260. }
  1261. }
  1262. // doGblInit = 0;
  1263. PushXMRInst(); // instance
  1264. ilGen.Emit(curDeclFunc, OpCodes.Ldc_I4_0);
  1265. ilGen.Emit(curDeclFunc, OpCodes.Stfld, doGblInitFieldInfo); // instance.doGblInit
  1266. //skipGblInit:
  1267. ilGen.MarkLabel(skipGblInitLabel);
  1268. }
  1269. }
  1270. // If this is a script-defined type constructor, call the base constructor and call
  1271. // this class's $instfieldinit() method to initialize instance fields.
  1272. if((curDeclFunc.sdtClass != null) && curDeclFunc.funcNameSig.val.StartsWith("$ctor("))
  1273. {
  1274. if(curDeclFunc.baseCtorCall != null)
  1275. {
  1276. GenerateFromRValCall(curDeclFunc.baseCtorCall);
  1277. }
  1278. TokenDeclVar ifiFunc = ((TokenDeclSDTypeClass)curDeclFunc.sdtClass).instFieldInit;
  1279. if(ifiFunc.body.statements != null)
  1280. {
  1281. CompValu thisCompValu = new CompValuArg(ifiFunc.sdtClass.MakeRefToken(ifiFunc), 0);
  1282. CompValu ifiFuncLocn = new CompValuInstMember(ifiFunc, thisCompValu, true);
  1283. ifiFuncLocn.CallPre(this, ifiFunc);
  1284. ifiFuncLocn.CallPost(this, ifiFunc);
  1285. }
  1286. }
  1287. // See if time to suspend in case they are doing a loop with recursion.
  1288. if(!isTrivial)
  1289. EmitCallCheckRun(curDeclFunc, true);
  1290. // Output code body.
  1291. GenerateStmtBlock(curDeclFunc.body);
  1292. /*
  1293. if (doheap)
  1294. {
  1295. PushXMRInst();
  1296. ilGen.Emit(curDeclFunc, OpCodes.Ldloc, curHeapSize);
  1297. ilGen.Emit(curDeclFunc, OpCodes.Stfld, heapUsedFieldInfo);
  1298. }
  1299. */
  1300. // If code falls through to this point, means they are missing
  1301. // a return statement. And that is legal only if the function
  1302. // returns 'void'.
  1303. if (mightGetHere)
  1304. {
  1305. if(curDeclFunc.retType is not TokenTypeVoid)
  1306. {
  1307. ErrorMsg(curDeclFunc.body, "missing final return statement");
  1308. }
  1309. ilGen.Emit(curDeclFunc, OpCodes.Leave, retLabel);
  1310. }
  1311. // End of the code to be optimized.
  1312. // Do optimizations then write it all out to object file.
  1313. // After this, all code gets written directly to object file.
  1314. // Optimization must be completed before we scan the allCallLabels
  1315. // list below to look for active locals and temps.
  1316. collector.Optimize();
  1317. _ilGen = collector.WriteOutAll();
  1318. List<ScriptMyLocal> activeTemps = null;
  1319. if (!isTrivial)
  1320. {
  1321. // Build list of locals and temps active at all the call labels.
  1322. activeTemps = new List<ScriptMyLocal>();
  1323. foreach (CallLabel cl in allCallLabels)
  1324. {
  1325. foreach (ScriptMyLocal lcl in cl.callLabel.whereAmI.localsReadBeforeWritten)
  1326. {
  1327. if (!activeTemps.Contains(lcl))
  1328. {
  1329. activeTemps.Add(lcl);
  1330. }
  1331. }
  1332. }
  1333. if(doheap)
  1334. activeTemps.Add(curHeapSize);
  1335. // Output code to restore the args, locals and temps then jump to
  1336. // the call label that we were interrupted at.
  1337. ilGen.MarkLabel(cmRestore);
  1338. GenerateFrameRestoreCode(activeTemps);
  1339. }
  1340. // Output epilog that saves stack frame state if CallMode_SAVE.
  1341. //
  1342. // finally {
  1343. // instance.m_StackLeft += stackframesize;
  1344. // if (instance.callMode != CallMode_SAVE) goto __endFin;
  1345. // GenerateFrameCaptureCode();
  1346. // __endFin:
  1347. // }
  1348. if(!isTrivial)
  1349. {
  1350. ilGen.BeginFinallyBlock();
  1351. PushXMRInst();
  1352. ilGen.Emit(curDeclFunc, OpCodes.Dup);
  1353. ilGen.Emit(curDeclFunc, OpCodes.Ldfld, stackLeftFieldInfo);
  1354. ilGen.Emit(curDeclFunc, OpCodes.Ldc_I4, stackframesize);
  1355. ilGen.Emit(curDeclFunc, OpCodes.Add);
  1356. ilGen.Emit(curDeclFunc, OpCodes.Stfld, stackLeftFieldInfo);
  1357. ScriptMyLabel endFin = ilGen.DefineLabel("__endFin");
  1358. PushXMRInst();
  1359. ilGen.Emit(curDeclFunc, OpCodes.Ldfld, callModeFieldInfo);
  1360. ilGen.Emit(curDeclFunc, OpCodes.Ldc_I4, XMRInstAbstract.CallMode_SAVE);
  1361. ilGen.Emit(curDeclFunc, OpCodes.Bne_Un, endFin);
  1362. GenerateFrameCaptureCode(activeTemps);
  1363. ilGen.MarkLabel(endFin);
  1364. ilGen.Emit(curDeclFunc, OpCodes.Endfinally);
  1365. ilGen.EndExceptionBlock();
  1366. }
  1367. // Output the 'real' return opcode.
  1368. // push return value
  1369. ilGen.MarkLabel(retLabel);
  1370. if (doheap)
  1371. {
  1372. PushXMRInst();
  1373. ilGen.Emit(curDeclFunc, OpCodes.Ldloc, curHeapSize);
  1374. ilGen.Emit(curDeclFunc, OpCodes.Stfld, heapUsedFieldInfo);
  1375. }
  1376. if (curDeclFunc.retType is not TokenTypeVoid)
  1377. {
  1378. ilGen.Emit(curDeclFunc, OpCodes.Ldloc, retValue);
  1379. }
  1380. ilGen.Emit(curDeclFunc, OpCodes.Ret);
  1381. retLabel = null;
  1382. retValue = null;
  1383. // No more instructions for this method.
  1384. ((ScriptObjWriter)ilGen).EndMethod();
  1385. _ilGen = null;
  1386. // Not generating function code any more.
  1387. curBreakTarg = null;
  1388. curContTarg = null;
  1389. curDeclFunc = null;
  1390. }
  1391. /**
  1392. * @brief Allocate stack space for all local variables, regardless of
  1393. * which { } statement block they are actually defined in.
  1394. * @returns approximate stack frame size
  1395. */
  1396. private int AllocLocalVarStackSpace()
  1397. {
  1398. int stackframesize = 64; // RIP, RBX, RBP, R12..R15, one extra
  1399. foreach(TokenDeclVar localVar in curDeclFunc.localVars)
  1400. {
  1401. // Skip all 'constant' vars as they were handled by the reducer.
  1402. if(localVar.constant)
  1403. continue;
  1404. // Get a stack location for the local variable.
  1405. localVar.location = new CompValuLocalVar(localVar.type, localVar.name.val, this);
  1406. // Stack size for the local variable.
  1407. stackframesize += LocalVarStackSize(localVar.type);
  1408. }
  1409. return stackframesize;
  1410. }
  1411. private static int LocalVarStackSize(TokenType tokType)
  1412. {
  1413. Type sysType = tokType.ToSysType();
  1414. return sysType.IsValueType ? System.Runtime.InteropServices.Marshal.SizeOf(sysType) : 8;
  1415. }
  1416. /**
  1417. * @brief Generate code to write all arguments and locals to the capture stack frame.
  1418. * This includes temp variables.
  1419. * We only need to save what is active at the point of callLabels through because
  1420. * those are the only points we will jump to on restore. This saves us from saving
  1421. * all the little temp vars we create.
  1422. * @param activeTemps = list of locals and temps that we care about, ie, which
  1423. * ones get restored by GenerateFrameRestoreCode().
  1424. */
  1425. private void GenerateFrameCaptureCode(List<ScriptMyLocal> activeTemps)
  1426. {
  1427. // Compute total number of slots we need to save stuff.
  1428. // Assume we need to save all call arguments.
  1429. int nSaves = curDeclFunc.argDecl.vars.Length + activeTemps.Count;
  1430. // Output code to allocate a stack frame object with an object array.
  1431. // This also pushes the stack frame object on the instance.stackFrames list.
  1432. // It returns a pointer to the object array it allocated.
  1433. PushXMRInst();
  1434. ilGen.Emit(curDeclFunc, OpCodes.Ldstr, ilGen.methName);
  1435. GetCallNo(curDeclFunc, actCallNo);
  1436. ilGen.Emit(curDeclFunc, OpCodes.Ldc_I4, nSaves);
  1437. ilGen.Emit(curDeclFunc, OpCodes.Call, captureStackFrameMethodInfo);
  1438. // Copy arg values to object array, boxing as needed.
  1439. int i = 0;
  1440. foreach(TokenDeclVar argVar in curDeclFunc.argDecl.varDict)
  1441. {
  1442. ilGen.Emit(curDeclFunc, OpCodes.Dup);
  1443. ilGen.Emit(curDeclFunc, OpCodes.Ldc_I4, i);
  1444. argVar.location.PushVal(this, argVar.name, tokenTypeObj);
  1445. ilGen.Emit(curDeclFunc, OpCodes.Stelem_Ref);
  1446. i++;
  1447. }
  1448. // Copy local and temp values to object array, boxing as needed.
  1449. foreach(ScriptMyLocal lcl in activeTemps)
  1450. {
  1451. ilGen.Emit(curDeclFunc, OpCodes.Dup);
  1452. ilGen.Emit(curDeclFunc, OpCodes.Ldc_I4, i++);
  1453. ilGen.Emit(curDeclFunc, OpCodes.Ldloc, lcl);
  1454. Type t = lcl.type;
  1455. if(t == typeof(HeapTrackerList))
  1456. {
  1457. t = HeapTrackerList.GenPush(curDeclFunc, ilGen);
  1458. }
  1459. if(t == typeof(HeapTrackerObject))
  1460. {
  1461. t = HeapTrackerObject.GenPush(curDeclFunc, ilGen);
  1462. }
  1463. if(t == typeof(HeapTrackerString))
  1464. {
  1465. t = HeapTrackerString.GenPush(curDeclFunc, ilGen);
  1466. }
  1467. if(t.IsValueType)
  1468. {
  1469. ilGen.Emit(curDeclFunc, OpCodes.Box, t);
  1470. }
  1471. ilGen.Emit(curDeclFunc, OpCodes.Stelem_Ref);
  1472. }
  1473. ilGen.Emit(curDeclFunc, OpCodes.Pop);
  1474. }
  1475. /**
  1476. * @brief Generate code to restore all arguments and locals from the restore stack frame.
  1477. * This includes temp variables.
  1478. */
  1479. private void GenerateFrameRestoreCode(List<ScriptMyLocal> activeTemps)
  1480. {
  1481. ScriptMyLocal objArray = ilGen.DeclareLocal(typeof(object[]), "__restObjArray");
  1482. // Output code to pop stack frame from instance.stackFrames.
  1483. // It returns a pointer to the object array that contains values to be restored.
  1484. PushXMRInst();
  1485. ilGen.Emit(curDeclFunc, OpCodes.Ldstr, ilGen.methName);
  1486. ilGen.Emit(curDeclFunc, OpCodes.Ldloca, actCallNo); // __mainCallNo
  1487. ilGen.Emit(curDeclFunc, OpCodes.Call, restoreStackFrameMethodInfo);
  1488. ilGen.Emit(curDeclFunc, OpCodes.Stloc, objArray);
  1489. // Restore argument values from object array, unboxing as needed.
  1490. // Although the caller has restored them to what it called us with, it's possible that this
  1491. // function has modified them since, so we need to do our own restore.
  1492. int i = 0;
  1493. foreach(TokenDeclVar argVar in curDeclFunc.argDecl.varDict)
  1494. {
  1495. CompValu argLoc = argVar.location;
  1496. argLoc.PopPre(this, argVar.name);
  1497. ilGen.Emit(curDeclFunc, OpCodes.Ldloc, objArray);
  1498. ilGen.Emit(curDeclFunc, OpCodes.Ldc_I4, i);
  1499. ilGen.Emit(curDeclFunc, OpCodes.Ldelem_Ref);
  1500. TypeCast.CastTopOfStack(this, argVar.name, tokenTypeObj, argLoc.type, true);
  1501. argLoc.PopPost(this, argVar.name);
  1502. i++;
  1503. }
  1504. // Restore local and temp values from object array, unboxing as needed.
  1505. foreach(ScriptMyLocal lcl in activeTemps)
  1506. {
  1507. Type t = lcl.type;
  1508. Type u = t;
  1509. if(t == typeof(HeapTrackerList))
  1510. u = typeof(LSL_List);
  1511. if(t == typeof(HeapTrackerObject))
  1512. u = typeof(object);
  1513. if(t == typeof(HeapTrackerString))
  1514. u = typeof(string);
  1515. if(u != t)
  1516. {
  1517. ilGen.Emit(curDeclFunc, OpCodes.Ldloc, lcl);
  1518. }
  1519. ilGen.Emit(curDeclFunc, OpCodes.Ldloc, objArray);
  1520. ilGen.Emit(curDeclFunc, OpCodes.Ldc_I4, i++);
  1521. ilGen.Emit(curDeclFunc, OpCodes.Ldelem_Ref);
  1522. if(u.IsValueType)
  1523. {
  1524. ilGen.Emit(curDeclFunc, OpCodes.Unbox_Any, u);
  1525. }
  1526. else if(u != typeof(object))
  1527. {
  1528. ilGen.Emit(curDeclFunc, OpCodes.Castclass, u);
  1529. }
  1530. if(u != t)
  1531. {
  1532. if(t == typeof(HeapTrackerList))
  1533. HeapTrackerList.GenRestore(curDeclFunc, ilGen);
  1534. if(t == typeof(HeapTrackerObject))
  1535. HeapTrackerObject.GenRestore(curDeclFunc, ilGen);
  1536. if(t == typeof(HeapTrackerString))
  1537. HeapTrackerString.GenRestore(curDeclFunc, ilGen);
  1538. }
  1539. else
  1540. {
  1541. ilGen.Emit(curDeclFunc, OpCodes.Stloc, lcl);
  1542. }
  1543. }
  1544. OutputCallNoSwitchStmt();
  1545. }
  1546. /**
  1547. * @brief Output a switch statement with a case for each possible
  1548. * value of whatever callNo is currently active, either
  1549. * __mainCallNo or one of the try/catch/finally's callNos.
  1550. *
  1551. * switch (callNo) {
  1552. * case 0: goto __call_0;
  1553. * case 1: goto __call_1;
  1554. * ...
  1555. * }
  1556. * throw new ScriptBadCallNoException (callNo);
  1557. */
  1558. private void OutputCallNoSwitchStmt()
  1559. {
  1560. ScriptMyLabel[] callLabels = new ScriptMyLabel[actCallLabels.Count];
  1561. foreach(CallLabel cl in actCallLabels)
  1562. {
  1563. callLabels[cl.index] = cl.callLabel;
  1564. }
  1565. GetCallNo(curDeclFunc, actCallNo);
  1566. ilGen.Emit(curDeclFunc, OpCodes.Switch, callLabels);
  1567. GetCallNo(curDeclFunc, actCallNo);
  1568. ilGen.Emit(curDeclFunc, OpCodes.Newobj, scriptBadCallNoExceptionConstructorInfo);
  1569. ilGen.Emit(curDeclFunc, OpCodes.Throw);
  1570. }
  1571. /**
  1572. * @brief There is one of these per call that can possibly call CheckRun(),
  1573. * including direct calls to CheckRun().
  1574. * They mark points that the stack capture/restore code will save & restore to.
  1575. * All object-code level local vars active at the call label's point will
  1576. * be saved & restored.
  1577. *
  1578. * callNo = 5;
  1579. * __call_5:
  1580. * push call arguments from temps
  1581. * call SomethingThatCallsCheckRun()
  1582. *
  1583. * If SomethingThatCallsCheckRun() actually calls CheckRun(), our restore code
  1584. * will restore our args, locals & temps, then jump to __call_5, which will then
  1585. * call SomethingThatCallsCheckRun() again, which will restore its stuff likewise.
  1586. * When eventually the actual CheckRun() call is restored, it will turn off restore
  1587. * mode (by changing callMode from CallMode_RESTORE to CallMode_NORMAL) and return,
  1588. * allowing the code to run normally from that point.
  1589. */
  1590. public class CallLabel
  1591. {
  1592. public int index; // sequential integer, starting at 0, within actCallLabels
  1593. // - used for the switch statement
  1594. public ScriptMyLabel callLabel; // the actual label token
  1595. public CallLabel(ScriptCodeGen scg, Token errorAt)
  1596. {
  1597. if(scg.openCallLabel != null)
  1598. throw new Exception("call label already open");
  1599. if(!scg.curDeclFunc.IsFuncTrivial(scg))
  1600. {
  1601. this.index = scg.actCallLabels.Count;
  1602. string name = "__call_" + index + "_" + scg.allCallLabels.Count;
  1603. // Make sure eval stack is empty because the frame capture/restore
  1604. // code expects such (restore switch stmt has an empty stack).
  1605. int depth = ((ScriptCollector)scg.ilGen).stackDepth.Count;
  1606. if(depth > 0)
  1607. {
  1608. // maybe need to call Trivialize()
  1609. throw new Exception("call label stack depth " + depth + " at " + errorAt.SrcLoc);
  1610. }
  1611. // Eval stack is empty so the restore code can handle it.
  1612. this.index = scg.actCallLabels.Count;
  1613. scg.actCallLabels.AddLast(this);
  1614. scg.allCallLabels.AddLast(this);
  1615. this.callLabel = scg.ilGen.DefineLabel(name);
  1616. scg.SetCallNo(errorAt, scg.actCallNo, this.index);
  1617. scg.ilGen.MarkLabel(this.callLabel);
  1618. }
  1619. scg.openCallLabel = this;
  1620. }
  1621. };
  1622. /**
  1623. * @brief generate code for an arbitrary statement.
  1624. */
  1625. private void GenerateStmt(TokenStmt stmt)
  1626. {
  1627. errorMessageToken = stmt;
  1628. if(stmt is TokenDeclVar TokenDeclVarstmt)
  1629. {
  1630. GenerateDeclVar(TokenDeclVarstmt);
  1631. return;
  1632. }
  1633. if(stmt is TokenStmtBlock TokenStmtBlockstmt)
  1634. {
  1635. GenerateStmtBlock(TokenStmtBlockstmt);
  1636. return;
  1637. }
  1638. if(stmt is TokenStmtBreak TokenStmtBreakstmt)
  1639. {
  1640. GenerateStmtBreak(TokenStmtBreakstmt);
  1641. return;
  1642. }
  1643. if(stmt is TokenStmtCont TokenStmtContstmt)
  1644. {
  1645. GenerateStmtCont(TokenStmtContstmt);
  1646. return;
  1647. }
  1648. if(stmt is TokenStmtDo TokenStmtDostmt)
  1649. {
  1650. GenerateStmtDo(TokenStmtDostmt);
  1651. return;
  1652. }
  1653. if(stmt is TokenStmtFor TokenStmtForstmt)
  1654. {
  1655. GenerateStmtFor(TokenStmtForstmt);
  1656. return;
  1657. }
  1658. if(stmt is TokenStmtForEach TokenStmtForEachstmt)
  1659. {
  1660. GenerateStmtForEach(TokenStmtForEachstmt);
  1661. return;
  1662. }
  1663. if(stmt is TokenStmtIf TokenStmtIfstmt)
  1664. {
  1665. GenerateStmtIf(TokenStmtIfstmt);
  1666. return;
  1667. }
  1668. if(stmt is TokenStmtJump TokenStmtJumpstmt)
  1669. {
  1670. GenerateStmtJump(TokenStmtJumpstmt);
  1671. return;
  1672. }
  1673. if(stmt is TokenStmtLabel TokenStmtLabelstmt)
  1674. {
  1675. GenerateStmtLabel(TokenStmtLabelstmt);
  1676. return;
  1677. }
  1678. if(stmt is TokenStmtNewobj TokenStmtNewobjstmt)
  1679. {
  1680. GenerateStmtNewobj(TokenStmtNewobjstmt);
  1681. return;
  1682. }
  1683. if(stmt is TokenStmtNull)
  1684. {
  1685. return;
  1686. }
  1687. if(stmt is TokenStmtRet TokenStmtRetstmt)
  1688. {
  1689. GenerateStmtRet(TokenStmtRetstmt);
  1690. return;
  1691. }
  1692. if(stmt is TokenStmtRVal TokenStmtRValstmt)
  1693. {
  1694. GenerateStmtRVal(TokenStmtRValstmt);
  1695. return;
  1696. }
  1697. if(stmt is TokenStmtState TokenStmtStatestmt)
  1698. {
  1699. GenerateStmtState(TokenStmtStatestmt);
  1700. return;
  1701. }
  1702. if(stmt is TokenStmtSwitch TokenStmtSwitchstmt)
  1703. {
  1704. GenerateStmtSwitch(TokenStmtSwitchstmt);
  1705. return;
  1706. }
  1707. if(stmt is TokenStmtThrow TokenStmtThrowstmt)
  1708. {
  1709. GenerateStmtThrow(TokenStmtThrowstmt);
  1710. return;
  1711. }
  1712. if(stmt is TokenStmtTry TokenStmtTrystmt)
  1713. {
  1714. GenerateStmtTry(TokenStmtTrystmt);
  1715. return;
  1716. }
  1717. if(stmt is TokenStmtVarIniDef TokenStmtVarIniDefstmt)
  1718. {
  1719. GenerateStmtVarIniDef(TokenStmtVarIniDefstmt);
  1720. return;
  1721. }
  1722. if(stmt is TokenStmtWhile TokenStmtWhilestmt)
  1723. {
  1724. GenerateStmtWhile(TokenStmtWhilestmt);
  1725. return;
  1726. }
  1727. throw new Exception("unknown TokenStmt type " + stmt.GetType().ToString());
  1728. }
  1729. /**
  1730. * @brief generate statement block (ie, with braces)
  1731. */
  1732. private void GenerateStmtBlock(TokenStmtBlock stmtBlock)
  1733. {
  1734. if(!mightGetHere)
  1735. return;
  1736. // Push new current statement block pointer for anyone who cares.
  1737. TokenStmtBlock oldStmtBlock = curStmtBlock;
  1738. curStmtBlock = stmtBlock;
  1739. // Output the statements that make up the block.
  1740. for(Token t = stmtBlock.statements; t != null; t = t.nextToken)
  1741. {
  1742. GenerateStmt((TokenStmt)t);
  1743. }
  1744. // Pop the current statement block.
  1745. curStmtBlock = oldStmtBlock;
  1746. }
  1747. /**
  1748. * @brief output code for a 'break' statement
  1749. */
  1750. private void GenerateStmtBreak(TokenStmtBreak breakStmt)
  1751. {
  1752. if(!mightGetHere)
  1753. return;
  1754. // Make sure we are in a breakable situation.
  1755. if(curBreakTarg == null)
  1756. {
  1757. ErrorMsg(breakStmt, "not in a breakable situation");
  1758. return;
  1759. }
  1760. // Tell anyone who cares that the break target was actually used.
  1761. curBreakTarg.used = true;
  1762. // Output the instructions.
  1763. EmitJumpCode(curBreakTarg.label, curBreakTarg.block, breakStmt);
  1764. }
  1765. /**
  1766. * @brief output code for a 'continue' statement
  1767. */
  1768. private void GenerateStmtCont(TokenStmtCont contStmt)
  1769. {
  1770. if(!mightGetHere)
  1771. return;
  1772. // Make sure we are in a contable situation.
  1773. if(curContTarg == null)
  1774. {
  1775. ErrorMsg(contStmt, "not in a continueable situation");
  1776. return;
  1777. }
  1778. // Tell anyone who cares that the continue target was actually used.
  1779. curContTarg.used = true;
  1780. // Output the instructions.
  1781. EmitJumpCode(curContTarg.label, curContTarg.block, contStmt);
  1782. }
  1783. /**
  1784. * @brief output code for a 'do' statement
  1785. */
  1786. private void GenerateStmtDo(TokenStmtDo doStmt)
  1787. {
  1788. if(!mightGetHere)
  1789. return;
  1790. BreakContTarg oldBreakTarg = curBreakTarg;
  1791. BreakContTarg oldContTarg = curContTarg;
  1792. ScriptMyLabel loopLabel = ilGen.DefineLabel("doloop_" + doStmt.Unique);
  1793. curBreakTarg = new BreakContTarg(this, "dobreak_" + doStmt.Unique);
  1794. curContTarg = new BreakContTarg(this, "docont_" + doStmt.Unique);
  1795. ilGen.MarkLabel(loopLabel);
  1796. GenerateStmt(doStmt.bodyStmt);
  1797. if(curContTarg.used)
  1798. {
  1799. ilGen.MarkLabel(curContTarg.label);
  1800. mightGetHere = true;
  1801. }
  1802. if(mightGetHere)
  1803. {
  1804. EmitCallCheckRun(doStmt, false);
  1805. CompValu testRVal = GenerateFromRVal(doStmt.testRVal);
  1806. if(IsConstBoolExprTrue(testRVal))
  1807. {
  1808. // Unconditional looping, unconditional branch and
  1809. // say we never fall through to next statement.
  1810. ilGen.Emit(doStmt, OpCodes.Br, loopLabel);
  1811. mightGetHere = false;
  1812. }
  1813. else
  1814. {
  1815. // Conditional looping, test and brach back to top of loop.
  1816. testRVal.PushVal(this, doStmt.testRVal, tokenTypeBool);
  1817. ilGen.Emit(doStmt, OpCodes.Brtrue, loopLabel);
  1818. }
  1819. }
  1820. // If 'break' statement was used, output target label.
  1821. // And assume that since a 'break' statement was used, it's possible for the code to get here.
  1822. if(curBreakTarg.used)
  1823. {
  1824. ilGen.MarkLabel(curBreakTarg.label);
  1825. mightGetHere = true;
  1826. }
  1827. curBreakTarg = oldBreakTarg;
  1828. curContTarg = oldContTarg;
  1829. }
  1830. /**
  1831. * @brief output code for a 'for' statement
  1832. */
  1833. private void GenerateStmtFor(TokenStmtFor forStmt)
  1834. {
  1835. if(!mightGetHere)
  1836. return;
  1837. BreakContTarg oldBreakTarg = curBreakTarg;
  1838. BreakContTarg oldContTarg = curContTarg;
  1839. ScriptMyLabel loopLabel = ilGen.DefineLabel("forloop_" + forStmt.Unique);
  1840. curBreakTarg = new BreakContTarg(this, "forbreak_" + forStmt.Unique);
  1841. curContTarg = new BreakContTarg(this, "forcont_" + forStmt.Unique);
  1842. if(forStmt.initStmt != null)
  1843. {
  1844. GenerateStmt(forStmt.initStmt);
  1845. }
  1846. ilGen.MarkLabel(loopLabel);
  1847. // See if we have a test expression that is other than a constant TRUE.
  1848. // If so, test it and conditionally branch to end if false.
  1849. if(forStmt.testRVal != null)
  1850. {
  1851. CompValu testRVal = GenerateFromRVal(forStmt.testRVal);
  1852. if(!IsConstBoolExprTrue(testRVal))
  1853. {
  1854. testRVal.PushVal(this, forStmt.testRVal, tokenTypeBool);
  1855. ilGen.Emit(forStmt, OpCodes.Brfalse, curBreakTarg.label);
  1856. curBreakTarg.used = true;
  1857. }
  1858. }
  1859. // Output loop body.
  1860. GenerateStmt(forStmt.bodyStmt);
  1861. // Here's where a 'continue' statement jumps to.
  1862. if(curContTarg.used)
  1863. {
  1864. ilGen.MarkLabel(curContTarg.label);
  1865. mightGetHere = true;
  1866. }
  1867. if(mightGetHere)
  1868. {
  1869. // After checking for excessive CPU time, output increment statement, if any.
  1870. EmitCallCheckRun(forStmt, false);
  1871. if(forStmt.incrRVal != null)
  1872. {
  1873. GenerateFromRVal(forStmt.incrRVal);
  1874. }
  1875. // Unconditional branch back to beginning of loop.
  1876. ilGen.Emit(forStmt, OpCodes.Br, loopLabel);
  1877. }
  1878. // If test needs label, output label for it to jump to.
  1879. // Otherwise, clear mightGetHere as we know loop never
  1880. // falls out the bottom.
  1881. mightGetHere = curBreakTarg.used;
  1882. if(mightGetHere)
  1883. {
  1884. ilGen.MarkLabel(curBreakTarg.label);
  1885. }
  1886. curBreakTarg = oldBreakTarg;
  1887. curContTarg = oldContTarg;
  1888. }
  1889. private void GenerateStmtForEach(TokenStmtForEach forEachStmt)
  1890. {
  1891. if(!mightGetHere)
  1892. return;
  1893. BreakContTarg oldBreakTarg = curBreakTarg;
  1894. BreakContTarg oldContTarg = curContTarg;
  1895. CompValu keyLVal = null;
  1896. CompValu valLVal = null;
  1897. CompValu arrayRVal = GenerateFromRVal(forEachStmt.arrayRVal);
  1898. if(forEachStmt.keyLVal != null)
  1899. {
  1900. keyLVal = GenerateFromLVal(forEachStmt.keyLVal);
  1901. if(keyLVal.type is not TokenTypeObject)
  1902. {
  1903. ErrorMsg(forEachStmt.arrayRVal, "must be object");
  1904. }
  1905. }
  1906. if(forEachStmt.valLVal != null)
  1907. {
  1908. valLVal = GenerateFromLVal(forEachStmt.valLVal);
  1909. if(valLVal.type is not TokenTypeObject)
  1910. {
  1911. ErrorMsg(forEachStmt.arrayRVal, "must be object");
  1912. }
  1913. }
  1914. if(arrayRVal.type is not TokenTypeArray)
  1915. {
  1916. ErrorMsg(forEachStmt.arrayRVal, "must be an array");
  1917. }
  1918. curBreakTarg = new BreakContTarg(this, "foreachbreak_" + forEachStmt.Unique);
  1919. curContTarg = new BreakContTarg(this, "foreachcont_" + forEachStmt.Unique);
  1920. CompValuTemp indexVar = new (new TokenTypeInt(forEachStmt), this);
  1921. ScriptMyLabel loopLabel = ilGen.DefineLabel("foreachloop_" + forEachStmt.Unique);
  1922. // indexVar = 0
  1923. ilGen.Emit(forEachStmt, OpCodes.Ldc_I4_0);
  1924. indexVar.Pop(this, forEachStmt);
  1925. ilGen.MarkLabel(loopLabel);
  1926. // key = array.__pub_index (indexVar);
  1927. // if (key == null) goto curBreakTarg;
  1928. if(keyLVal != null)
  1929. {
  1930. keyLVal.PopPre(this, forEachStmt.keyLVal);
  1931. arrayRVal.PushVal(this, forEachStmt.arrayRVal);
  1932. indexVar.PushVal(this, forEachStmt);
  1933. ilGen.Emit(forEachStmt, OpCodes.Call, xmrArrPubIndexMethod);
  1934. keyLVal.PopPost(this, forEachStmt.keyLVal);
  1935. keyLVal.PushVal(this, forEachStmt.keyLVal);
  1936. ilGen.Emit(forEachStmt, OpCodes.Brfalse, curBreakTarg.label);
  1937. curBreakTarg.used = true;
  1938. }
  1939. // val = array._pub_value (indexVar);
  1940. // if (val == null) goto curBreakTarg;
  1941. if(valLVal != null)
  1942. {
  1943. valLVal.PopPre(this, forEachStmt.valLVal);
  1944. arrayRVal.PushVal(this, forEachStmt.arrayRVal);
  1945. indexVar.PushVal(this, forEachStmt);
  1946. ilGen.Emit(forEachStmt, OpCodes.Call, xmrArrPubValueMethod);
  1947. valLVal.PopPost(this, forEachStmt.valLVal);
  1948. if(keyLVal == null)
  1949. {
  1950. valLVal.PushVal(this, forEachStmt.valLVal);
  1951. ilGen.Emit(forEachStmt, OpCodes.Brfalse, curBreakTarg.label);
  1952. curBreakTarg.used = true;
  1953. }
  1954. }
  1955. // indexVar ++;
  1956. indexVar.PushVal(this, forEachStmt);
  1957. ilGen.Emit(forEachStmt, OpCodes.Ldc_I4_1);
  1958. ilGen.Emit(forEachStmt, OpCodes.Add);
  1959. indexVar.Pop(this, forEachStmt);
  1960. // body statement
  1961. GenerateStmt(forEachStmt.bodyStmt);
  1962. // continue label
  1963. if(curContTarg.used)
  1964. {
  1965. ilGen.MarkLabel(curContTarg.label);
  1966. mightGetHere = true;
  1967. }
  1968. // call CheckRun()
  1969. if(mightGetHere)
  1970. {
  1971. EmitCallCheckRun(forEachStmt, false);
  1972. ilGen.Emit(forEachStmt, OpCodes.Br, loopLabel);
  1973. }
  1974. // break label
  1975. ilGen.MarkLabel(curBreakTarg.label);
  1976. mightGetHere = true;
  1977. curBreakTarg = oldBreakTarg;
  1978. curContTarg = oldContTarg;
  1979. }
  1980. /**
  1981. * @brief output code for an 'if' statement
  1982. * Braces are necessary because what may be one statement for trueStmt or elseStmt in
  1983. * the script may translate to more than one statement in the resultant C# code.
  1984. */
  1985. private void GenerateStmtIf(TokenStmtIf ifStmt)
  1986. {
  1987. if(!mightGetHere)
  1988. return;
  1989. // Test condition and see if constant test expression.
  1990. CompValu testRVal = GenerateFromRVal(ifStmt.testRVal);
  1991. if (IsConstBoolExpr(testRVal, out bool constVal))
  1992. {
  1993. // Constant, output just either the true or else part.
  1994. if(constVal)
  1995. {
  1996. GenerateStmt(ifStmt.trueStmt);
  1997. }
  1998. else if(ifStmt.elseStmt != null)
  1999. {
  2000. GenerateStmt(ifStmt.elseStmt);
  2001. }
  2002. }
  2003. else if(ifStmt.elseStmt == null)
  2004. {
  2005. // This is an 'if' statement without an 'else' clause.
  2006. testRVal.PushVal(this, ifStmt.testRVal, tokenTypeBool);
  2007. ScriptMyLabel doneLabel = ilGen.DefineLabel("ifdone_" + ifStmt.Unique);
  2008. ilGen.Emit(ifStmt, OpCodes.Brfalse, doneLabel); // brfalse doneLabel
  2009. GenerateStmt(ifStmt.trueStmt); // generate true body code
  2010. ilGen.MarkLabel(doneLabel);
  2011. mightGetHere = true; // there's always a possibility of getting here
  2012. }
  2013. else
  2014. {
  2015. // This is an 'if' statement with an 'else' clause.
  2016. testRVal.PushVal(this, ifStmt.testRVal, tokenTypeBool);
  2017. ScriptMyLabel elseLabel = ilGen.DefineLabel("ifelse_" + ifStmt.Unique);
  2018. ilGen.Emit(ifStmt, OpCodes.Brfalse, elseLabel); // brfalse elseLabel
  2019. GenerateStmt(ifStmt.trueStmt); // generate true body code
  2020. bool trueMightGetHere = mightGetHere; // save whether or not true falls through
  2021. ScriptMyLabel doneLabel = ilGen.DefineLabel("ifdone_" + ifStmt.Unique);
  2022. ilGen.Emit(ifStmt, OpCodes.Br, doneLabel); // branch to done
  2023. ilGen.MarkLabel(elseLabel); // beginning of else code
  2024. mightGetHere = true; // the top of the else might be executed
  2025. GenerateStmt(ifStmt.elseStmt); // output else code
  2026. ilGen.MarkLabel(doneLabel); // where end of true clause code branches to
  2027. mightGetHere |= trueMightGetHere; // gets this far if either true or else falls through
  2028. }
  2029. }
  2030. /**
  2031. * @brief output code for a 'jump' statement
  2032. */
  2033. private void GenerateStmtJump(TokenStmtJump jumpStmt)
  2034. {
  2035. if(!mightGetHere)
  2036. return;
  2037. // Make sure the target label is defined somewhere in the function.
  2038. if (!curDeclFunc.labels.TryGetValue(jumpStmt.label.val, out TokenStmtLabel stmtLabel))
  2039. {
  2040. ErrorMsg(jumpStmt, "undefined label " + jumpStmt.label.val);
  2041. return;
  2042. }
  2043. if (!stmtLabel.labelTagged)
  2044. {
  2045. stmtLabel.labelStruct = ilGen.DefineLabel("jump_" + stmtLabel.name.val);
  2046. stmtLabel.labelTagged = true;
  2047. }
  2048. // Emit instructions to do the jump.
  2049. EmitJumpCode(stmtLabel.labelStruct, stmtLabel.block, jumpStmt);
  2050. }
  2051. /**
  2052. * @brief Emit code to jump to a label
  2053. * @param target = label being jumped to
  2054. * @param targetsBlock = { ... } the label is defined in
  2055. */
  2056. private void EmitJumpCode(ScriptMyLabel target, TokenStmtBlock targetsBlock, Token errorAt)
  2057. {
  2058. // Jumps never fall through.
  2059. mightGetHere = false;
  2060. // Find which block the target label is in. Must be in this or an outer block,
  2061. // no laterals allowed. And if we exit a try/catch block, use Leave instead of Br.
  2062. //
  2063. // jump lateral;
  2064. // {
  2065. // @lateral;
  2066. // }
  2067. bool useLeave = false;
  2068. TokenStmtBlock stmtBlock;
  2069. Stack<TokenStmtTry> finallyBlocksCalled = new ();
  2070. for(stmtBlock = curStmtBlock; stmtBlock != targetsBlock; stmtBlock = stmtBlock.outerStmtBlock)
  2071. {
  2072. if(stmtBlock == null)
  2073. {
  2074. ErrorMsg(errorAt, "no lateral jumps allowed");
  2075. return;
  2076. }
  2077. if(stmtBlock.isFinally)
  2078. {
  2079. ErrorMsg(errorAt, "cannot jump out of finally");
  2080. return;
  2081. }
  2082. if(stmtBlock.isTry || stmtBlock.isCatch)
  2083. useLeave = true;
  2084. if((stmtBlock.tryStmt != null) && (stmtBlock.tryStmt.finallyStmt != null))
  2085. {
  2086. finallyBlocksCalled.Push(stmtBlock.tryStmt);
  2087. }
  2088. }
  2089. // If popping through more than one finally block, we have to break it down for the stack
  2090. // capture and restore code, one finally block at a time.
  2091. //
  2092. // try {
  2093. // try {
  2094. // try {
  2095. // jump exit;
  2096. // } finally {
  2097. // llOwnerSay ("exiting inner");
  2098. // }
  2099. // } finally {
  2100. // llOwnerSay ("exiting middle");
  2101. // }
  2102. // } finally {
  2103. // llOwnerSay ("exiting outer");
  2104. // }
  2105. // @exit;
  2106. //
  2107. // try {
  2108. // try {
  2109. // try {
  2110. // jump intr2_exit; <<< gets its own tryNo call label so inner try knows where to restore to
  2111. // } finally {
  2112. // llOwnerSay ("exiting inner");
  2113. // }
  2114. // jump outtry2;
  2115. // @intr2_exit; jump intr1_exit; <<< gets its own tryNo call label so middle try knows where to restore to
  2116. // @outtry2;
  2117. // } finally {
  2118. // llOwnerSay ("exiting middle");
  2119. // }
  2120. // jump outtry1;
  2121. // @intr1_exit: jump exit; <<< gets its own tryNo call label so outer try knows where to restore to
  2122. // @outtry1;
  2123. // } finally {
  2124. // llOwnerSay ("exiting outer");
  2125. // }
  2126. // @exit;
  2127. int level = 0;
  2128. while(finallyBlocksCalled.Count > 1)
  2129. {
  2130. TokenStmtTry finallyBlock = finallyBlocksCalled.Pop();
  2131. string intername = "intr" + (++level) + "_" + target.name;
  2132. if (!finallyBlock.iLeaves.TryGetValue(intername, out IntermediateLeave iLeave))
  2133. {
  2134. iLeave = new IntermediateLeave
  2135. {
  2136. jumpIntoLabel = ilGen.DefineLabel(intername),
  2137. jumpAwayLabel = target
  2138. };
  2139. finallyBlock.iLeaves.Add(intername, iLeave);
  2140. }
  2141. target = iLeave.jumpIntoLabel;
  2142. }
  2143. // Finally output the branch/leave opcode.
  2144. // If using Leave, prefix with a call label in case the corresponding finally block
  2145. // calls CheckRun() and that CheckRun() captures the stack, it will have a point to
  2146. // restore to that will properly jump back into the finally block.
  2147. if(useLeave)
  2148. {
  2149. _ = new CallLabel(this, errorAt);
  2150. ilGen.Emit(errorAt, OpCodes.Leave, target);
  2151. openCallLabel = null;
  2152. }
  2153. else
  2154. {
  2155. ilGen.Emit(errorAt, OpCodes.Br, target);
  2156. }
  2157. }
  2158. /**
  2159. * @brief output code for a jump target label statement.
  2160. * If there are any backward jumps to the label, do a CheckRun() also.
  2161. */
  2162. private void GenerateStmtLabel(TokenStmtLabel labelStmt)
  2163. {
  2164. if(!labelStmt.labelTagged)
  2165. {
  2166. labelStmt.labelStruct = ilGen.DefineLabel("jump_" + labelStmt.name.val);
  2167. labelStmt.labelTagged = true;
  2168. }
  2169. ilGen.MarkLabel(labelStmt.labelStruct);
  2170. if(labelStmt.hasBkwdRefs)
  2171. {
  2172. EmitCallCheckRun(labelStmt, false);
  2173. }
  2174. // We are going to say that the label falls through.
  2175. // It would be nice if we could analyze all referencing
  2176. // goto's to see if all of them are not used but we are
  2177. // going to assume that if the script writer put a label
  2178. // somewhere, it is probably going to be used.
  2179. mightGetHere = true;
  2180. }
  2181. /**
  2182. * @brief Generate code for a script-defined type's <typename>.$new(<argsig>) method.
  2183. * It is used to malloc the object and initialize it.
  2184. * It is defined as a script-defined type static method, so the object level
  2185. * method gets the XMRInstance pointer passed as arg 0, and the method is
  2186. * supposed to return the allocated and constructed XMRSDTypeClObj
  2187. * object pointer.
  2188. */
  2189. private void GenerateStmtNewobj(TokenStmtNewobj newobjStmt)
  2190. {
  2191. // First off, malloc a new empty XMRSDTypeClObj object
  2192. // then call the XMRSDTypeClObj()-level constructor.
  2193. // Store the result in local var $objptr.
  2194. newobjStmt.objptrVar.location.PopPre(this, newobjStmt);
  2195. ilGen.Emit(newobjStmt, OpCodes.Ldarg_0);
  2196. ilGen.Emit(newobjStmt, OpCodes.Ldc_I4, curDeclFunc.sdtClass.sdTypeIndex);
  2197. ilGen.Emit(newobjStmt, OpCodes.Newobj, sdtClassConstructorInfo);
  2198. newobjStmt.objptrVar.location.PopPost(this, newobjStmt);
  2199. // Now call the script-level constructor.
  2200. // Pass the object pointer in $objptr as it's 'this' argument.
  2201. // The rest of the args are the script-visible args and are just copied from $new() call.
  2202. GenerateFromRValCall(newobjStmt.rValCall);
  2203. // Put object pointer in retval so it gets returned to caller.
  2204. newobjStmt.objptrVar.location.PushVal(this, newobjStmt);
  2205. ilGen.Emit(newobjStmt, OpCodes.Stloc, retValue);
  2206. // Exit the function like a return statement.
  2207. // And thus we don't fall through.
  2208. ilGen.Emit(newobjStmt, OpCodes.Leave, retLabel);
  2209. mightGetHere = false;
  2210. }
  2211. /**
  2212. * @brief output code for a return statement.
  2213. * @param retStmt = return statement token, including return value if any
  2214. */
  2215. private void GenerateStmtRet(TokenStmtRet retStmt)
  2216. {
  2217. if(!mightGetHere)
  2218. return;
  2219. for(TokenStmtBlock stmtBlock = curStmtBlock; stmtBlock != null; stmtBlock = stmtBlock.outerStmtBlock)
  2220. {
  2221. if(stmtBlock.isFinally)
  2222. {
  2223. ErrorMsg(retStmt, "cannot return out of finally");
  2224. return;
  2225. }
  2226. }
  2227. if(curDeclFunc.retType is TokenTypeVoid)
  2228. {
  2229. if(retStmt.rVal != null)
  2230. {
  2231. ErrorMsg(retStmt, "function returns void, no value allowed");
  2232. return;
  2233. }
  2234. }
  2235. else
  2236. {
  2237. if(retStmt.rVal == null)
  2238. {
  2239. ErrorMsg(retStmt, "function requires return value type " + curDeclFunc.retType.ToString());
  2240. return;
  2241. }
  2242. CompValu rVal = GenerateFromRVal(retStmt.rVal);
  2243. rVal.PushVal(this, retStmt.rVal, curDeclFunc.retType);
  2244. ilGen.Emit(retStmt, OpCodes.Stloc, retValue);
  2245. }
  2246. // Use a OpCodes.Leave instruction to break out of any try { } blocks.
  2247. // All Leave's inside script-defined try { } need call labels (see GenerateStmtTry()).
  2248. bool brokeOutOfTry = false;
  2249. for(TokenStmtBlock stmtBlock = curStmtBlock; stmtBlock != null; stmtBlock = stmtBlock.outerStmtBlock)
  2250. {
  2251. if(stmtBlock.isTry)
  2252. {
  2253. brokeOutOfTry = true;
  2254. break;
  2255. }
  2256. }
  2257. if(brokeOutOfTry)
  2258. _ = new CallLabel(this, retStmt);
  2259. ilGen.Emit(retStmt, OpCodes.Leave, retLabel);
  2260. if(brokeOutOfTry)
  2261. openCallLabel = null;
  2262. // 'return' statements never fall through.
  2263. mightGetHere = false;
  2264. }
  2265. /**
  2266. * @brief the statement is just an expression, most likely an assignment or a ++ or -- thing.
  2267. */
  2268. private void GenerateStmtRVal(TokenStmtRVal rValStmt)
  2269. {
  2270. if(!mightGetHere)
  2271. return;
  2272. GenerateFromRVal(rValStmt.rVal);
  2273. }
  2274. /**
  2275. * @brief generate code for a 'state' statement that transitions state.
  2276. * It sets the new state by throwing a ScriptChangeStateException.
  2277. */
  2278. private void GenerateStmtState(TokenStmtState stateStmt)
  2279. {
  2280. if(!mightGetHere)
  2281. return;
  2282. int index = 0; // 'default' state
  2283. // Set new state value by throwing an exception.
  2284. // These exceptions aren't catchable by script-level try { } catch { }.
  2285. if ((stateStmt.state != null) && !stateIndices.TryGetValue(stateStmt.state.val, out index))
  2286. {
  2287. mightGetHere = false;
  2288. // do compile time error
  2289. ErrorMsg (stateStmt, "undefined state " + stateStmt.state.val);
  2290. throw new Exception("undefined state " + stateStmt.state.val);
  2291. // before we did throw an exception only at runtime.
  2292. //ilGen.Emit(stateStmt, OpCodes.Ldstr, stateStmt.state.val);
  2293. //ilGen.Emit(stateStmt, OpCodes.Newobj, scriptUndefinedStateExceptionConstructorInfo);
  2294. }
  2295. else
  2296. {
  2297. if (curDeclFunc.fullName != "$globalvarinit()")
  2298. {
  2299. PushXMRInst();
  2300. ilGen.Emit(curDeclFunc, OpCodes.Ldloc, curHeapSize);
  2301. ilGen.Emit(curDeclFunc, OpCodes.Stfld, heapUsedFieldInfo);
  2302. }
  2303. ilGen.Emit(stateStmt, OpCodes.Ldc_I4, index); // new state's index
  2304. ilGen.Emit(stateStmt, OpCodes.Newobj, scriptChangeStateExceptionConstructorInfo);
  2305. }
  2306. ilGen.Emit(stateStmt, OpCodes.Throw);
  2307. // 'state' statements never fall through.
  2308. mightGetHere = false;
  2309. }
  2310. /**
  2311. * @brief output code for a 'switch' statement
  2312. */
  2313. private void GenerateStmtSwitch(TokenStmtSwitch switchStmt)
  2314. {
  2315. if(!mightGetHere)
  2316. return;
  2317. // Output code to calculate index.
  2318. CompValu testRVal = GenerateFromRVal(switchStmt.testRVal);
  2319. // Generate code based on string or integer index.
  2320. if((testRVal.type is TokenTypeKey) || (testRVal.type is TokenTypeStr))
  2321. GenerateStmtSwitchStr(testRVal, switchStmt);
  2322. else
  2323. GenerateStmtSwitchInt(testRVal, switchStmt);
  2324. }
  2325. private void GenerateStmtSwitchInt(CompValu testRVal, TokenStmtSwitch switchStmt)
  2326. {
  2327. testRVal.PushVal(this, switchStmt.testRVal, tokenTypeInt);
  2328. BreakContTarg oldBreakTarg = curBreakTarg;
  2329. ScriptMyLabel defaultLabel = null;
  2330. TokenSwitchCase sortedCases = null;
  2331. TokenSwitchCase defaultCase = null;
  2332. curBreakTarg = new BreakContTarg(this, "switchbreak_" + switchStmt.Unique);
  2333. // Build list of cases sorted by ascending values.
  2334. // There should not be any overlapping of values.
  2335. for(TokenSwitchCase thisCase = switchStmt.cases; thisCase != null; thisCase = thisCase.nextCase)
  2336. {
  2337. thisCase.label = ilGen.DefineLabel("case_" + thisCase.Unique);
  2338. // The default case if any, goes in its own separate slot.
  2339. if(thisCase.rVal1 == null)
  2340. {
  2341. if(defaultCase != null)
  2342. {
  2343. ErrorMsg(thisCase, "only one default case allowed");
  2344. ErrorMsg(defaultCase, "...prior default case");
  2345. return;
  2346. }
  2347. defaultCase = thisCase;
  2348. defaultLabel = thisCase.label;
  2349. continue;
  2350. }
  2351. // Evaluate case operands, they must be compile-time integer constants.
  2352. CompValu rVal = GenerateFromRVal(thisCase.rVal1);
  2353. if(!IsConstIntExpr(rVal, out thisCase.val1))
  2354. {
  2355. ErrorMsg(thisCase.rVal1, "must be compile-time char or integer constant");
  2356. return;
  2357. }
  2358. thisCase.val2 = thisCase.val1;
  2359. if(thisCase.rVal2 != null)
  2360. {
  2361. rVal = GenerateFromRVal(thisCase.rVal2);
  2362. if(!IsConstIntExpr(rVal, out thisCase.val2))
  2363. {
  2364. ErrorMsg(thisCase.rVal2, "must be compile-time char or integer constant");
  2365. return;
  2366. }
  2367. }
  2368. if(thisCase.val2 < thisCase.val1)
  2369. {
  2370. ErrorMsg(thisCase.rVal2, "must be .ge. first value for the case");
  2371. return;
  2372. }
  2373. // Insert into list, sorted by value.
  2374. // Note that both limits are inclusive.
  2375. TokenSwitchCase lastCase = null;
  2376. TokenSwitchCase nextCase;
  2377. for(nextCase = sortedCases; nextCase != null; nextCase = nextCase.nextSortedCase)
  2378. {
  2379. if(nextCase.val1 > thisCase.val2)
  2380. break;
  2381. if(nextCase.val2 >= thisCase.val1)
  2382. {
  2383. ErrorMsg(thisCase, "value used by previous case");
  2384. ErrorMsg(nextCase, "...previous case");
  2385. return;
  2386. }
  2387. lastCase = nextCase;
  2388. }
  2389. thisCase.nextSortedCase = nextCase;
  2390. if(lastCase == null)
  2391. {
  2392. sortedCases = thisCase;
  2393. }
  2394. else
  2395. {
  2396. lastCase.nextSortedCase = thisCase;
  2397. }
  2398. }
  2399. defaultLabel ??= ilGen.DefineLabel("default_" + switchStmt.Unique);
  2400. // Output code to jump to the case statement's labels based on integer index on stack.
  2401. // Note that each case still has the integer index on stack when jumped to.
  2402. int offset = 0;
  2403. for(TokenSwitchCase thisCase = sortedCases; thisCase != null;)
  2404. {
  2405. // Scan through list of cases to find the maximum number of cases who's numvalues-to-case ratio
  2406. // is from 0.5 to 2.0. If such a group is found, use a CIL switch for them. If not, just use a
  2407. // compare-and-branch for the current case.
  2408. int numCases = 0;
  2409. int numFound = 0;
  2410. int lowValue = thisCase.val1;
  2411. int numValues = 0;
  2412. for(TokenSwitchCase scanCase = thisCase; scanCase != null; scanCase = scanCase.nextSortedCase)
  2413. {
  2414. int nVals = scanCase.val2 - thisCase.val1 + 1;
  2415. double ratio = (double)nVals / (double)(++numCases);
  2416. if((ratio >= 0.5) && (ratio <= 2.0))
  2417. {
  2418. numFound = numCases;
  2419. numValues = nVals;
  2420. }
  2421. }
  2422. if(numFound > 1)
  2423. {
  2424. // There is a group of case's, starting with thisCase, that fall within our criteria, ie,
  2425. // that have a nice density of meaningful jumps.
  2426. //
  2427. // So first generate an array of jumps to the default label (explicit or implicit).
  2428. ScriptMyLabel[] labels = new ScriptMyLabel[numValues];
  2429. for(int i = 0; i < numValues; i++)
  2430. {
  2431. labels[i] = defaultLabel;
  2432. }
  2433. // Next, for each case in that group, fill in the corresponding array entries to jump to
  2434. // that case's label.
  2435. do
  2436. {
  2437. for(int i = thisCase.val1; i <= thisCase.val2; i++)
  2438. {
  2439. labels[i - lowValue] = thisCase.label;
  2440. }
  2441. thisCase = thisCase.nextSortedCase;
  2442. } while(--numFound > 0);
  2443. // Subtract the low value and do the computed jump.
  2444. // The OpCodes.Switch falls through if out of range (unsigned compare).
  2445. if(offset != lowValue)
  2446. {
  2447. ilGen.Emit(switchStmt, OpCodes.Ldc_I4, lowValue - offset);
  2448. ilGen.Emit(switchStmt, OpCodes.Sub);
  2449. offset = lowValue;
  2450. }
  2451. ilGen.Emit(switchStmt, OpCodes.Dup);
  2452. ilGen.Emit(switchStmt, OpCodes.Switch, labels);
  2453. }
  2454. else
  2455. {
  2456. // It's not economical to do with a computed jump, so output a subtract/compare/branch
  2457. // for thisCase.
  2458. if(lowValue == thisCase.val2)
  2459. {
  2460. ilGen.Emit(switchStmt, OpCodes.Dup);
  2461. ilGen.Emit(switchStmt, OpCodes.Ldc_I4, lowValue - offset);
  2462. ilGen.Emit(switchStmt, OpCodes.Beq, thisCase.label);
  2463. }
  2464. else
  2465. {
  2466. if(offset != lowValue)
  2467. {
  2468. ilGen.Emit(switchStmt, OpCodes.Ldc_I4, lowValue - offset);
  2469. ilGen.Emit(switchStmt, OpCodes.Sub);
  2470. offset = lowValue;
  2471. }
  2472. ilGen.Emit(switchStmt, OpCodes.Dup);
  2473. ilGen.Emit(switchStmt, OpCodes.Ldc_I4, thisCase.val2 - offset);
  2474. ilGen.Emit(switchStmt, OpCodes.Ble_Un, thisCase.label);
  2475. }
  2476. thisCase = thisCase.nextSortedCase;
  2477. }
  2478. }
  2479. ilGen.Emit(switchStmt, OpCodes.Br, defaultLabel);
  2480. // Output code for the cases themselves, in the order given by the programmer,
  2481. // so they fall through as programmer wants. This includes the default case, if any.
  2482. //
  2483. // Each label is jumped to with the index still on the stack. So pop it off in case
  2484. // the case body does a goto outside the switch or a return. If the case body might
  2485. // fall through to the next case or the bottom of the switch, push a zero so the stack
  2486. // matches in all cases.
  2487. for(TokenSwitchCase thisCase = switchStmt.cases; thisCase != null; thisCase = thisCase.nextCase)
  2488. {
  2489. ilGen.MarkLabel(thisCase.label); // the branch comes here
  2490. ilGen.Emit(thisCase, OpCodes.Pop); // pop the integer index off stack
  2491. mightGetHere = true; // it's possible to get here
  2492. for(TokenStmt stmt = thisCase.stmts; stmt != null; stmt = (TokenStmt)(stmt.nextToken))
  2493. {
  2494. GenerateStmt(stmt); // output the case/explicit default body
  2495. }
  2496. if(mightGetHere)
  2497. {
  2498. ilGen.Emit(thisCase, OpCodes.Ldc_I4_0);
  2499. // in case we fall through, push a dummy integer index
  2500. }
  2501. }
  2502. // If no explicit default case, output the default label here.
  2503. if(defaultCase == null)
  2504. {
  2505. ilGen.MarkLabel(defaultLabel);
  2506. mightGetHere = true;
  2507. }
  2508. // If the last case of the switch falls through out the bottom,
  2509. // we have to pop the index still on the stack.
  2510. if(mightGetHere)
  2511. {
  2512. ilGen.Emit(switchStmt, OpCodes.Pop);
  2513. }
  2514. // Output the 'break' statement target label.
  2515. // Note that the integer index is not on the stack at this point.
  2516. if(curBreakTarg.used)
  2517. {
  2518. ilGen.MarkLabel(curBreakTarg.label);
  2519. mightGetHere = true;
  2520. }
  2521. curBreakTarg = oldBreakTarg;
  2522. }
  2523. private void GenerateStmtSwitchStr(CompValu testRVal, TokenStmtSwitch switchStmt)
  2524. {
  2525. BreakContTarg oldBreakTarg = curBreakTarg;
  2526. ScriptMyLabel defaultLabel = null;
  2527. TokenSwitchCase caseTreeTop = null;
  2528. TokenSwitchCase defaultCase = null;
  2529. curBreakTarg = new BreakContTarg(this, "switchbreak_" + switchStmt.Unique);
  2530. // Make sure value is in a temp so we don't compute it more than once.
  2531. if(testRVal is not CompValuTemp)
  2532. {
  2533. CompValuTemp temp = new (testRVal.type, this);
  2534. testRVal.PushVal(this, switchStmt);
  2535. temp.Pop(this, switchStmt);
  2536. testRVal = temp;
  2537. }
  2538. // Build tree of cases.
  2539. // There should not be any overlapping of values.
  2540. for(TokenSwitchCase thisCase = switchStmt.cases; thisCase != null; thisCase = thisCase.nextCase)
  2541. {
  2542. thisCase.label = ilGen.DefineLabel("case");
  2543. // The default case if any, goes in its own separate slot.
  2544. if(thisCase.rVal1 == null)
  2545. {
  2546. if(defaultCase != null)
  2547. {
  2548. ErrorMsg(thisCase, "only one default case allowed");
  2549. ErrorMsg(defaultCase, "...prior default case");
  2550. return;
  2551. }
  2552. defaultCase = thisCase;
  2553. defaultLabel = thisCase.label;
  2554. continue;
  2555. }
  2556. // Evaluate case operands, they must be compile-time string constants.
  2557. CompValu rVal = GenerateFromRVal(thisCase.rVal1);
  2558. if(!IsConstStrExpr(rVal, out thisCase.str1))
  2559. {
  2560. ErrorMsg(thisCase.rVal1, "must be compile-time string constant");
  2561. continue;
  2562. }
  2563. thisCase.str2 = thisCase.str1;
  2564. if(thisCase.rVal2 != null)
  2565. {
  2566. rVal = GenerateFromRVal(thisCase.rVal2);
  2567. if(!IsConstStrExpr(rVal, out thisCase.str2))
  2568. {
  2569. ErrorMsg(thisCase.rVal2, "must be compile-time string constant");
  2570. continue;
  2571. }
  2572. }
  2573. if(String.Compare(thisCase.str2, thisCase.str1, StringComparison.Ordinal) < 0)
  2574. {
  2575. ErrorMsg(thisCase.rVal2, "must be .ge. first value for the case");
  2576. continue;
  2577. }
  2578. // Insert into list, sorted by value.
  2579. // Note that both limits are inclusive.
  2580. caseTreeTop = InsertCaseInTree(caseTreeTop, thisCase);
  2581. }
  2582. // Balance tree so we end up generating code that does O(log2 n) comparisons.
  2583. caseTreeTop = BalanceTree(caseTreeTop);
  2584. // Output compare and branch instructions in a tree-like fashion so we do O(log2 n) comparisons.
  2585. defaultLabel ??= ilGen.DefineLabel("default");
  2586. if(caseTreeTop is not null)
  2587. OutputStrCase(testRVal, caseTreeTop, defaultLabel);
  2588. // Output code for the cases themselves, in the order given by the programmer,
  2589. // so they fall through as programmer wants. This includes the default case, if any.
  2590. for(TokenSwitchCase thisCase = switchStmt.cases; thisCase != null; thisCase = thisCase.nextCase)
  2591. {
  2592. ilGen.MarkLabel(thisCase.label); // the branch comes here
  2593. mightGetHere = true; // it's possible to get here
  2594. for(TokenStmt stmt = thisCase.stmts; stmt != null; stmt = (TokenStmt)(stmt.nextToken))
  2595. {
  2596. GenerateStmt(stmt); // output the case/explicit default body
  2597. }
  2598. }
  2599. // If no explicit default case, output the default label here.
  2600. if(defaultCase == null)
  2601. {
  2602. ilGen.MarkLabel(defaultLabel);
  2603. mightGetHere = true;
  2604. }
  2605. // Output the 'break' statement target label.
  2606. if(curBreakTarg.used)
  2607. {
  2608. ilGen.MarkLabel(curBreakTarg.label);
  2609. mightGetHere = true;
  2610. }
  2611. curBreakTarg = oldBreakTarg;
  2612. }
  2613. /**
  2614. * @brief Insert a case in a tree of cases
  2615. * @param r = root of existing cases to insert into
  2616. * @param n = new case being inserted
  2617. * @returns new root with new case inserted
  2618. */
  2619. private TokenSwitchCase InsertCaseInTree(TokenSwitchCase r, TokenSwitchCase n)
  2620. {
  2621. if(r == null)
  2622. return n;
  2623. TokenSwitchCase t = r;
  2624. while(true)
  2625. {
  2626. if(String.Compare(n.str2, t.str1, StringComparison.Ordinal) < 0)
  2627. {
  2628. if(t.lowerCase == null)
  2629. {
  2630. t.lowerCase = n;
  2631. break;
  2632. }
  2633. t = t.lowerCase;
  2634. continue;
  2635. }
  2636. if(String.Compare(n.str1, t.str2, StringComparison.Ordinal) > 0)
  2637. {
  2638. if(t.higherCase == null)
  2639. {
  2640. t.higherCase = n;
  2641. break;
  2642. }
  2643. t = t.higherCase;
  2644. continue;
  2645. }
  2646. ErrorMsg(n, "duplicate case");
  2647. ErrorMsg(r, "...duplicate of");
  2648. break;
  2649. }
  2650. return r;
  2651. }
  2652. /**
  2653. * @brief Balance a tree so left & right halves contain same number within +-1
  2654. * @param r = root of tree to balance
  2655. * @returns new root
  2656. */
  2657. private static TokenSwitchCase BalanceTree(TokenSwitchCase r)
  2658. {
  2659. if(r == null)
  2660. return r;
  2661. int lc = CountTree(r.lowerCase);
  2662. int hc = CountTree(r.higherCase);
  2663. TokenSwitchCase n, x;
  2664. // If lower side is heavy, move highest nodes from lower side to
  2665. // higher side until balanced.
  2666. while(lc > hc + 1)
  2667. {
  2668. x = ExtractHighest(r.lowerCase, out n);
  2669. n.lowerCase = x;
  2670. n.higherCase = r;
  2671. r.lowerCase = null;
  2672. r = n;
  2673. lc--;
  2674. hc++;
  2675. }
  2676. // If higher side is heavy, move lowest nodes from higher side to
  2677. // lower side until balanced.
  2678. while(hc > lc + 1)
  2679. {
  2680. x = ExtractLowest(r.higherCase, out n);
  2681. n.higherCase = x;
  2682. n.lowerCase = r;
  2683. r.higherCase = null;
  2684. r = n;
  2685. lc++;
  2686. hc--;
  2687. }
  2688. // Now balance each side because they can be lopsided individually.
  2689. r.lowerCase = BalanceTree(r.lowerCase);
  2690. r.higherCase = BalanceTree(r.higherCase);
  2691. return r;
  2692. }
  2693. /**
  2694. * @brief Get number of nodes in a tree
  2695. * @param n = root of tree to count
  2696. * @returns number of nodes including root
  2697. */
  2698. private static int CountTree(TokenSwitchCase n)
  2699. {
  2700. if(n == null)
  2701. return 0;
  2702. return 1 + CountTree(n.lowerCase) + CountTree(n.higherCase);
  2703. }
  2704. // Extract highest node from a tree
  2705. // @param r = root of tree to extract highest from
  2706. // @returns new root after node has been extracted
  2707. // n = node that was extracted from tree
  2708. private static TokenSwitchCase ExtractHighest(TokenSwitchCase r, out TokenSwitchCase n)
  2709. {
  2710. if(r.higherCase == null)
  2711. {
  2712. n = r;
  2713. return r.lowerCase;
  2714. }
  2715. r.higherCase = ExtractHighest(r.higherCase, out n);
  2716. return r;
  2717. }
  2718. // Extract lowest node from a tree
  2719. // @param r = root of tree to extract lowest from
  2720. // @returns new root after node has been extracted
  2721. // n = node that was extracted from tree
  2722. private static TokenSwitchCase ExtractLowest(TokenSwitchCase r, out TokenSwitchCase n)
  2723. {
  2724. if(r.lowerCase == null)
  2725. {
  2726. n = r;
  2727. return r.higherCase;
  2728. }
  2729. r.lowerCase = ExtractLowest(r.lowerCase, out n);
  2730. return r;
  2731. }
  2732. /**
  2733. * Output code for string-style case of a switch/case to jump to the script code associated with the case.
  2734. * @param testRVal = value being switched on
  2735. * @param thisCase = case that the code is being output for
  2736. * @param defaultLabel = where the default clause is (or past all cases if none)
  2737. * Note:
  2738. * Outputs code for this case and the lowerCase and higherCases if any.
  2739. * If no lowerCase or higherCase, outputs a br to defaultLabel so this code never falls through.
  2740. */
  2741. private void OutputStrCase(CompValu testRVal, TokenSwitchCase thisCase, ScriptMyLabel defaultLabel)
  2742. {
  2743. // If nothing lower on tree and there is a single case value,
  2744. // just do one compare for equality.
  2745. if((thisCase.lowerCase == null) && (thisCase.higherCase == null) && (thisCase.str1 == thisCase.str2))
  2746. {
  2747. testRVal.PushVal(this, thisCase, tokenTypeStr);
  2748. ilGen.Emit(thisCase, OpCodes.Ldstr, thisCase.str1);
  2749. ilGen.Emit(thisCase, OpCodes.Call, stringCompareMethodInfo);
  2750. ilGen.Emit(thisCase, OpCodes.Brfalse, thisCase.label);
  2751. ilGen.Emit(thisCase, OpCodes.Br, defaultLabel);
  2752. return;
  2753. }
  2754. // Determine where to jump if switch value is lower than lower case value.
  2755. ScriptMyLabel lowerLabel = defaultLabel;
  2756. if(thisCase.lowerCase != null)
  2757. {
  2758. lowerLabel = ilGen.DefineLabel("lower");
  2759. }
  2760. // If single case value, put comparison result in this temp.
  2761. CompValuTemp cmpv1 = null;
  2762. if(thisCase.str1 == thisCase.str2)
  2763. {
  2764. cmpv1 = new CompValuTemp(tokenTypeInt, this);
  2765. }
  2766. // If switch value .lt. lower case value, jump to lower label.
  2767. // Maybe save comparison result in a temp.
  2768. testRVal.PushVal(this, thisCase, tokenTypeStr);
  2769. ilGen.Emit(thisCase, OpCodes.Ldstr, thisCase.str1);
  2770. ilGen.Emit(thisCase, OpCodes.Call, stringCompareMethodInfo);
  2771. if(cmpv1 != null)
  2772. {
  2773. ilGen.Emit(thisCase, OpCodes.Dup);
  2774. cmpv1.Pop(this, thisCase);
  2775. }
  2776. ilGen.Emit(thisCase, OpCodes.Ldc_I4_0);
  2777. ilGen.Emit(thisCase, OpCodes.Blt, lowerLabel);
  2778. // If switch value .le. higher case value, jump to case code.
  2779. // Maybe get comparison from the temp.
  2780. if(cmpv1 == null)
  2781. {
  2782. testRVal.PushVal(this, thisCase, tokenTypeStr);
  2783. ilGen.Emit(thisCase, OpCodes.Ldstr, thisCase.str2);
  2784. ilGen.Emit(thisCase, OpCodes.Call, stringCompareMethodInfo);
  2785. }
  2786. else
  2787. {
  2788. cmpv1.PushVal(this, thisCase);
  2789. }
  2790. ilGen.Emit(thisCase, OpCodes.Ldc_I4_0);
  2791. ilGen.Emit(thisCase, OpCodes.Ble, thisCase.label);
  2792. // Output code for higher comparison if any.
  2793. if(thisCase.higherCase == null)
  2794. {
  2795. ilGen.Emit(thisCase, OpCodes.Br, defaultLabel);
  2796. }
  2797. else
  2798. {
  2799. OutputStrCase(testRVal, thisCase.higherCase, defaultLabel);
  2800. }
  2801. // Output code for lower comparison if any.
  2802. if(thisCase.lowerCase != null)
  2803. {
  2804. ilGen.MarkLabel(lowerLabel);
  2805. OutputStrCase(testRVal, thisCase.lowerCase, defaultLabel);
  2806. }
  2807. }
  2808. /**
  2809. * @brief output code for a throw statement.
  2810. * @param throwStmt = throw statement token, including value to be thrown
  2811. */
  2812. private void GenerateStmtThrow(TokenStmtThrow throwStmt)
  2813. {
  2814. if(!mightGetHere)
  2815. return;
  2816. // 'throw' statements never fall through.
  2817. mightGetHere = false;
  2818. // Output code for either a throw or a rethrow.
  2819. if(throwStmt.rVal == null)
  2820. {
  2821. for(TokenStmtBlock blk = curStmtBlock; blk != null; blk = blk.outerStmtBlock)
  2822. {
  2823. if(curStmtBlock.isCatch)
  2824. {
  2825. ilGen.Emit(throwStmt, OpCodes.Rethrow);
  2826. return;
  2827. }
  2828. }
  2829. ErrorMsg(throwStmt, "rethrow allowed only in catch clause");
  2830. }
  2831. else
  2832. {
  2833. CompValu rVal = GenerateFromRVal(throwStmt.rVal);
  2834. rVal.PushVal(this, throwStmt.rVal, tokenTypeObj);
  2835. ilGen.Emit(throwStmt, OpCodes.Call, thrownExceptionWrapMethodInfo);
  2836. ilGen.Emit(throwStmt, OpCodes.Throw);
  2837. }
  2838. }
  2839. /**
  2840. * @brief output code for a try/catch/finally block
  2841. */
  2842. private void GenerateStmtTry(TokenStmtTry tryStmt)
  2843. {
  2844. if(!mightGetHere)
  2845. return;
  2846. /*
  2847. * Reducer should make sure we have exactly one of catch or finally.
  2848. */
  2849. if((tryStmt.catchStmt == null) && (tryStmt.finallyStmt == null))
  2850. {
  2851. throw new Exception("must have a catch or a finally on try");
  2852. }
  2853. if((tryStmt.catchStmt != null) && (tryStmt.finallyStmt != null))
  2854. {
  2855. throw new Exception("can't have both catch and finally on same try");
  2856. }
  2857. // Stack the call labels.
  2858. // Try blocks have their own series of call labels.
  2859. ScriptMyLocal saveCallNo = actCallNo;
  2860. LinkedList<CallLabel> saveCallLabels = actCallLabels;
  2861. // Generate code for either try { } catch { } or try { } finally { }.
  2862. if(tryStmt.catchStmt != null)
  2863. GenerateStmtTryCatch(tryStmt);
  2864. if(tryStmt.finallyStmt != null)
  2865. GenerateStmtTryFinally(tryStmt);
  2866. // Restore call labels.
  2867. actCallNo = saveCallNo;
  2868. actCallLabels = saveCallLabels;
  2869. }
  2870. /**
  2871. * @brief output code for a try/catch block
  2872. *
  2873. * int __tryCallNo = -1; // call number within try { } subblock
  2874. * int __catCallNo = -1; // call number within catch { } subblock
  2875. * Exception __catThrown = null; // caught exception
  2876. * <oldCallLabel>: // the outside world jumps here to restore us no matter ...
  2877. * try { // ... where we actually were inside of try/catch
  2878. * if (__tryCallNo >= 0) goto tryCallSw; // maybe go do restore
  2879. * <try body using __tryCallNo> // execute script-defined code
  2880. * // ...stack capture WILL run catch { } subblock
  2881. * leave tryEnd; // exits
  2882. * tryThrow:<tryCallLabel>:
  2883. * throw new ScriptRestoreCatchException(__catThrown); // catch { } was running, jump to its beginning
  2884. * tryCallSw: // restoring...
  2885. * switch (__tryCallNo) back up into <try body> // not catching, jump back inside try
  2886. * } catch (Exception exc) {
  2887. * exc = ScriptRestoreCatchException.Unwrap(exc); // unwrap possible ScriptRestoreCatchException
  2888. * if (exc == null) goto catchRetro; // rethrow if IXMRUncatchable (eg, StackCaptureException)
  2889. * __catThrown = exc; // save what was thrown so restoring try { } will throw it again
  2890. * catchVar = exc; // set up script-visible variable
  2891. * __tryCallNo = tryThrow:<tryCallLabel>
  2892. * if (__catCallNo >= 0) goto catchCallSw; // if restoring, go check below
  2893. * <catch body using __catCallNo> // normal, execute script-defined code
  2894. * leave tryEnd; // all done, exit catch { }
  2895. * catchRetro:
  2896. * rethrow;
  2897. * catchCallSw:
  2898. * switch (__catCallNo) back up into <catch body> // restart catch { } code wherever it was
  2899. * }
  2900. * tryEnd:
  2901. */
  2902. private void GenerateStmtTryCatch(TokenStmtTry tryStmt)
  2903. {
  2904. CompValuTemp tryCallNo = new (tokenTypeInt, this);
  2905. CompValuTemp catCallNo = new (tokenTypeInt, this);
  2906. CompValuTemp catThrown = new (tokenTypeExc, this);
  2907. ScriptMyLabel tryCallSw = ilGen.DefineLabel("__tryCallSw_" + tryStmt.Unique);
  2908. ScriptMyLabel catchRetro = ilGen.DefineLabel("__catchRetro_" + tryStmt.Unique);
  2909. ScriptMyLabel catchCallSw = ilGen.DefineLabel("__catchCallSw_" + tryStmt.Unique);
  2910. ScriptMyLabel tryEnd = ilGen.DefineLabel("__tryEnd_" + tryStmt.Unique);
  2911. SetCallNo(tryStmt, tryCallNo, -1);
  2912. SetCallNo(tryStmt, catCallNo, -1);
  2913. ilGen.Emit(tryStmt, OpCodes.Ldnull);
  2914. catThrown.Pop(this, tryStmt);
  2915. _ = new CallLabel(this, tryStmt); // <oldcalllabel>:
  2916. ilGen.BeginExceptionBlock(); // try {
  2917. openCallLabel = null;
  2918. GetCallNo(tryStmt, tryCallNo); // if (__tryCallNo >= 0) goto tryCallSw;
  2919. ilGen.Emit(tryStmt, OpCodes.Ldc_I4_0);
  2920. ilGen.Emit(tryStmt, OpCodes.Bge, tryCallSw);
  2921. actCallNo = tryCallNo.localBuilder; // set up __tryCallNo for call labels
  2922. actCallLabels = new LinkedList<CallLabel>();
  2923. GenerateStmtBlock(tryStmt.tryStmt); // output the try block statement subblock
  2924. bool tryBlockFallsOutBottom = mightGetHere;
  2925. if(tryBlockFallsOutBottom)
  2926. {
  2927. _ = new CallLabel(this, tryStmt); // <tryCallLabel>:
  2928. ilGen.Emit(tryStmt, OpCodes.Leave, tryEnd); // leave tryEnd;
  2929. openCallLabel = null;
  2930. }
  2931. CallLabel tryThrow = new (this, tryStmt); // tryThrow:<tryCallLabel>:
  2932. catThrown.PushVal(this, tryStmt); // throw new ScriptRestoreCatchException (__catThrown);
  2933. ilGen.Emit(tryStmt, OpCodes.Newobj, scriptRestoreCatchExceptionConstructorInfo);
  2934. ilGen.Emit(tryStmt, OpCodes.Throw);
  2935. openCallLabel = null;
  2936. ilGen.MarkLabel(tryCallSw); // tryCallSw:
  2937. OutputCallNoSwitchStmt(); // switch (tryCallNo) ...
  2938. CompValuLocalVar catchVarLocExc = null;
  2939. CompValuTemp catchVarLocStr = null;
  2940. if(tryStmt.catchVar.type.ToSysType() == typeof(Exception))
  2941. {
  2942. catchVarLocExc = new CompValuLocalVar(tryStmt.catchVar.type, tryStmt.catchVar.name.val, this);
  2943. }
  2944. else if(tryStmt.catchVar.type.ToSysType() == typeof(String))
  2945. {
  2946. catchVarLocStr = new CompValuTemp(tryStmt.catchVar.type, this);
  2947. }
  2948. ScriptMyLocal excLocal = ilGen.DeclareLocal(typeof(String), "catchstr_" + tryStmt.Unique);
  2949. ilGen.BeginCatchBlock(typeof(Exception)); // start of the catch block that can catch any exception
  2950. ilGen.Emit(tryStmt.catchStmt, OpCodes.Call, scriptRestoreCatchExceptionUnwrap);
  2951. // exc = ScriptRestoreCatchException.Unwrap (exc);
  2952. ilGen.Emit(tryStmt.catchStmt, OpCodes.Dup); // rethrow if IXMRUncatchable (eg, StackCaptureException)
  2953. ilGen.Emit(tryStmt.catchStmt, OpCodes.Brfalse, catchRetro);
  2954. if(tryStmt.catchVar.type.ToSysType() == typeof(Exception))
  2955. {
  2956. tryStmt.catchVar.location = catchVarLocExc;
  2957. ilGen.Emit(tryStmt.catchStmt, OpCodes.Dup);
  2958. catThrown.Pop(this, tryStmt); // store exception object in catThrown
  2959. catchVarLocExc.Pop(this, tryStmt.catchVar.name); // also store in script-visible variable
  2960. }
  2961. else if(tryStmt.catchVar.type.ToSysType() == typeof(String))
  2962. {
  2963. tryStmt.catchVar.location = catchVarLocStr;
  2964. ilGen.Emit(tryStmt.catchStmt, OpCodes.Dup);
  2965. catThrown.Pop(this, tryStmt); // store exception object in catThrown
  2966. ilGen.Emit(tryStmt.catchStmt, OpCodes.Call, catchExcToStrMethodInfo);
  2967. ilGen.Emit(tryStmt.catchStmt, OpCodes.Stloc, excLocal);
  2968. catchVarLocStr.PopPre(this, tryStmt.catchVar.name);
  2969. ilGen.Emit(tryStmt.catchStmt, OpCodes.Ldloc, excLocal);
  2970. catchVarLocStr.PopPost(this, tryStmt.catchVar.name, tokenTypeStr);
  2971. }
  2972. else
  2973. {
  2974. throw new Exception("bad catch var type " + tryStmt.catchVar.type.ToString());
  2975. }
  2976. SetCallNo(tryStmt, tryCallNo, tryThrow.index); // __tryCallNo = tryThrow so it knows to do 'throw catThrown' on restore
  2977. GetCallNo(tryStmt, catCallNo); // if (__catCallNo >= 0) goto catchCallSw;
  2978. ilGen.Emit(tryStmt.catchStmt, OpCodes.Ldc_I4_0);
  2979. ilGen.Emit(tryStmt.catchStmt, OpCodes.Bge, catchCallSw);
  2980. actCallNo = catCallNo.localBuilder; // set up __catCallNo for call labels
  2981. actCallLabels.Clear();
  2982. mightGetHere = true; // if we can get to the 'try' assume we can get to the 'catch'
  2983. GenerateStmtBlock(tryStmt.catchStmt); // output catch clause statement subblock
  2984. if(mightGetHere)
  2985. {
  2986. _ = new CallLabel(this, tryStmt.catchStmt);
  2987. ilGen.Emit(tryStmt.catchStmt, OpCodes.Leave, tryEnd);
  2988. openCallLabel = null;
  2989. }
  2990. ilGen.MarkLabel(catchRetro); // not a script-visible exception, rethrow it
  2991. ilGen.Emit(tryStmt.catchStmt, OpCodes.Pop);
  2992. ilGen.Emit(tryStmt.catchStmt, OpCodes.Rethrow);
  2993. ilGen.MarkLabel(catchCallSw);
  2994. OutputCallNoSwitchStmt(); // restoring, jump back inside script-defined body
  2995. ilGen.EndExceptionBlock();
  2996. ilGen.MarkLabel(tryEnd);
  2997. mightGetHere |= tryBlockFallsOutBottom; // also get here if try body falls out bottom
  2998. }
  2999. /**
  3000. * @brief output code for a try/finally block
  3001. *
  3002. * This is such a mess because there is hidden state for the finally { } that we have to recreate.
  3003. * The finally { } can be entered either via an exception being thrown in the try { } or a leave
  3004. * being executed in the try { } whose target is outside the try { } finally { }.
  3005. *
  3006. * For the thrown exception case, we slip in a try { } catch { } wrapper around the original try { }
  3007. * body. This will sense any thrown exception that would execute the finally { }. Then we have our
  3008. * try { } throw the exception on restore which gets the finally { } called and on its way again.
  3009. *
  3010. * For the leave case, we prefix all leave instructions with a call label and we explicitly chain
  3011. * all leaves through each try { } that has an associated finally { } that the leave would unwind
  3012. * through. This gets each try { } to simply jump to the correct leave instruction which immediately
  3013. * invokes the corresponding finally { } and then chains to the next leave instruction on out until
  3014. * it gets to its target.
  3015. *
  3016. * int __finCallNo = -1; // call number within finally { } subblock
  3017. * int __tryCallNo = -1; // call number within try { } subblock
  3018. * Exception __catThrown = null; // caught exception
  3019. * <oldCallLabel>: // the outside world jumps here to restore us no matter ...
  3020. * try { // ... where we actually were inside of try/finally
  3021. * try {
  3022. * if (__tryCallNo >= 0) goto tryCallSw; // maybe go do restore
  3023. * <try body using __tryCallNo> // execute script-defined code
  3024. * // ...stack capture WILL run catch/finally { } subblock
  3025. * leave tryEnd; // executes finally { } subblock and exits
  3026. * tryThrow:<tryCallLabel>:
  3027. * throw new ScriptRestoreCatchException(__catThrown); // catch { } was running, jump to its beginning
  3028. * tryCallSw: // restoring...
  3029. * switch (__tryCallNo) back up into <try body> // jump back inside try, ...
  3030. * // ... maybe to a leave if we were doing finally { } subblock
  3031. * } catch (Exception exc) { // in case we're getting to finally { } via a thrown exception:
  3032. * exc = ScriptRestoreCatchException.Unwrap(exc); // unwrap possible ScriptRestoreCatchException
  3033. * if (callMode == CallMode_SAVE) goto catchRetro; // don't touch anything if capturing stack
  3034. * __catThrown = exc; // save exception so try { } can throw it on restore
  3035. * __tryCallNo = tryThrow:<tryCallLabel>; // tell try { } to throw it on restore
  3036. * catchRetro:
  3037. * rethrow; // in any case, go on to finally { } subblock now
  3038. * }
  3039. * } finally {
  3040. * if (callMode == CallMode_SAVE) goto finEnd; // don't touch anything if capturing stack
  3041. * if (__finCallNo >= 0) goto finCallSw; // maybe go do restore
  3042. * <finally body using __finCallNo> // normal, execute script-defined code
  3043. * finEnd:
  3044. * endfinally // jump to leave/throw target or next outer finally { }
  3045. * finCallSw:
  3046. * switch (__finCallNo) back up into <finally body> // restoring, restart finally { } code wherever it was
  3047. * }
  3048. * tryEnd:
  3049. */
  3050. private void GenerateStmtTryFinally(TokenStmtTry tryStmt)
  3051. {
  3052. CompValuTemp finCallNo = new (tokenTypeInt, this);
  3053. CompValuTemp tryCallNo = new (tokenTypeInt, this);
  3054. CompValuTemp catThrown = new (tokenTypeExc, this);
  3055. ScriptMyLabel tryCallSw = ilGen.DefineLabel("__tryCallSw_" + tryStmt.Unique);
  3056. ScriptMyLabel catchRetro = ilGen.DefineLabel("__catchRetro_" + tryStmt.Unique);
  3057. ScriptMyLabel finCallSw = ilGen.DefineLabel("__finCallSw_" + tryStmt.Unique);
  3058. BreakContTarg finEnd = new (this, "__finEnd_" + tryStmt.Unique);
  3059. ScriptMyLabel tryEnd = ilGen.DefineLabel("__tryEnd_" + tryStmt.Unique);
  3060. SetCallNo(tryStmt, finCallNo, -1);
  3061. SetCallNo(tryStmt, tryCallNo, -1);
  3062. ilGen.Emit(tryStmt, OpCodes.Ldnull);
  3063. catThrown.Pop(this, tryStmt);
  3064. _ = new CallLabel(this, tryStmt); // <oldcalllabel>:
  3065. ilGen.BeginExceptionBlock(); // try {
  3066. ilGen.BeginExceptionBlock(); // try {
  3067. openCallLabel = null;
  3068. GetCallNo(tryStmt, tryCallNo); // if (__tryCallNo >= 0) goto tryCallSw;
  3069. ilGen.Emit(tryStmt, OpCodes.Ldc_I4_0);
  3070. ilGen.Emit(tryStmt, OpCodes.Bge, tryCallSw);
  3071. actCallNo = tryCallNo.localBuilder; // set up __tryCallNo for call labels
  3072. actCallLabels = new LinkedList<CallLabel>();
  3073. GenerateStmtBlock(tryStmt.tryStmt); // output the try block statement subblock
  3074. if(mightGetHere)
  3075. {
  3076. _ = new CallLabel(this, tryStmt); // <newCallLabel>:
  3077. ilGen.Emit(tryStmt, OpCodes.Leave, tryEnd); // leave tryEnd;
  3078. openCallLabel = null;
  3079. }
  3080. foreach(IntermediateLeave iLeave in tryStmt.iLeaves.Values)
  3081. {
  3082. ilGen.MarkLabel(iLeave.jumpIntoLabel); // intr2_exit:
  3083. _ = new CallLabel(this, tryStmt); // tryCallNo = n;
  3084. ilGen.Emit(tryStmt, OpCodes.Leave, iLeave.jumpAwayLabel); // __callNo_n_: leave int1_exit;
  3085. openCallLabel = null;
  3086. }
  3087. CallLabel tryThrow = new (this, tryStmt); // tryThrow:<tryCallLabel>:
  3088. catThrown.PushVal(this, tryStmt); // throw new ScriptRestoreCatchException (__catThrown);
  3089. ilGen.Emit(tryStmt, OpCodes.Newobj, scriptRestoreCatchExceptionConstructorInfo);
  3090. ilGen.Emit(tryStmt, OpCodes.Throw);
  3091. openCallLabel = null;
  3092. ilGen.MarkLabel(tryCallSw); // tryCallSw:
  3093. OutputCallNoSwitchStmt(); // switch (tryCallNo) ...
  3094. // }
  3095. ilGen.BeginCatchBlock(typeof(Exception)); // start of the catch block that can catch any exception
  3096. ilGen.Emit(tryStmt, OpCodes.Call, scriptRestoreCatchExceptionUnwrap); // exc = ScriptRestoreCatchException.Unwrap (exc);
  3097. PushXMRInst(); // if (callMode == CallMode_SAVE) goto catchRetro;
  3098. ilGen.Emit(tryStmt, OpCodes.Ldfld, callModeFieldInfo);
  3099. ilGen.Emit(tryStmt, OpCodes.Ldc_I4, XMRInstAbstract.CallMode_SAVE);
  3100. ilGen.Emit(tryStmt, OpCodes.Beq, catchRetro);
  3101. catThrown.Pop(this, tryStmt); // __catThrown = exc;
  3102. SetCallNo(tryStmt, tryCallNo, tryThrow.index); // __tryCallNo = tryThrow:<tryCallLabel>;
  3103. ilGen.Emit(tryStmt, OpCodes.Rethrow);
  3104. ilGen.MarkLabel(catchRetro); // catchRetro:
  3105. ilGen.Emit(tryStmt, OpCodes.Pop);
  3106. ilGen.Emit(tryStmt, OpCodes.Rethrow); // rethrow;
  3107. ilGen.EndExceptionBlock(); // }
  3108. ilGen.BeginFinallyBlock(); // start of the finally block
  3109. PushXMRInst(); // if (callMode == CallMode_SAVE) goto finEnd;
  3110. ilGen.Emit(tryStmt, OpCodes.Ldfld, callModeFieldInfo);
  3111. ilGen.Emit(tryStmt, OpCodes.Ldc_I4, XMRInstAbstract.CallMode_SAVE);
  3112. ilGen.Emit(tryStmt, OpCodes.Beq, finEnd.label);
  3113. GetCallNo(tryStmt, finCallNo); // if (__finCallNo >= 0) goto finCallSw;
  3114. ilGen.Emit(tryStmt, OpCodes.Ldc_I4_0);
  3115. ilGen.Emit(tryStmt, OpCodes.Bge, finCallSw);
  3116. actCallNo = finCallNo.localBuilder; // set up __finCallNo for call labels
  3117. actCallLabels.Clear();
  3118. mightGetHere = true; // if we can get to the 'try' assume we can get to the 'finally'
  3119. GenerateStmtBlock(tryStmt.finallyStmt); // output finally clause statement subblock
  3120. ilGen.MarkLabel(finEnd.label); // finEnd:
  3121. ilGen.Emit(tryStmt, OpCodes.Endfinally); // return out to next finally { } or catch { } or leave target
  3122. ilGen.MarkLabel(finCallSw); // restore mode, switch (finCallNo) ...
  3123. OutputCallNoSwitchStmt();
  3124. ilGen.EndExceptionBlock();
  3125. ilGen.MarkLabel(tryEnd);
  3126. mightGetHere |= finEnd.used; // get here if finally body falls through or has a break statement
  3127. }
  3128. /**
  3129. * @brief Generate code to initialize a variable to its default value.
  3130. */
  3131. private void GenerateStmtVarIniDef(TokenStmtVarIniDef varIniDefStmt)
  3132. {
  3133. if(!mightGetHere)
  3134. return;
  3135. CompValu left = GenerateFromLVal(varIniDefStmt.var);
  3136. left.PopPre(this, varIniDefStmt);
  3137. PushDefaultValue(left.type);
  3138. left.PopPost(this, varIniDefStmt);
  3139. }
  3140. /**
  3141. * @brief generate code for a 'while' statement including the loop body.
  3142. */
  3143. private void GenerateStmtWhile(TokenStmtWhile whileStmt)
  3144. {
  3145. if(!mightGetHere)
  3146. return;
  3147. BreakContTarg oldBreakTarg = curBreakTarg;
  3148. BreakContTarg oldContTarg = curContTarg;
  3149. ScriptMyLabel loopLabel = ilGen.DefineLabel("whileloop_" + whileStmt.Unique);
  3150. curBreakTarg = new BreakContTarg(this, "whilebreak_" + whileStmt.Unique);
  3151. curContTarg = new BreakContTarg(this, "whilecont_" + whileStmt.Unique);
  3152. ilGen.MarkLabel(loopLabel); // loop:
  3153. CompValu testRVal = GenerateFromRVal(whileStmt.testRVal); // testRVal = while test expression
  3154. if(!IsConstBoolExprTrue(testRVal))
  3155. {
  3156. testRVal.PushVal(this, whileStmt.testRVal, tokenTypeBool); // if (!testRVal)
  3157. ilGen.Emit(whileStmt, OpCodes.Brfalse, curBreakTarg.label); // goto break
  3158. curBreakTarg.used = true;
  3159. }
  3160. GenerateStmt(whileStmt.bodyStmt); // while body statement
  3161. if(curContTarg.used)
  3162. {
  3163. ilGen.MarkLabel(curContTarg.label); // cont:
  3164. mightGetHere = true;
  3165. }
  3166. if(mightGetHere)
  3167. {
  3168. EmitCallCheckRun(whileStmt, false); // __sw.CheckRun()
  3169. ilGen.Emit(whileStmt, OpCodes.Br, loopLabel); // goto loop
  3170. }
  3171. mightGetHere = curBreakTarg.used;
  3172. if(mightGetHere)
  3173. {
  3174. ilGen.MarkLabel(curBreakTarg.label); // done:
  3175. }
  3176. curBreakTarg = oldBreakTarg;
  3177. curContTarg = oldContTarg;
  3178. }
  3179. /**
  3180. * @brief process a local variable declaration statement, possibly with initialization expression.
  3181. * Note that the function header processing allocated stack space (CompValuTemp) for the
  3182. * variable and now all we do is write its initialization value.
  3183. */
  3184. private void GenerateDeclVar(TokenDeclVar declVar)
  3185. {
  3186. // Script gave us an initialization value, so just store init value in var like an assignment statement.
  3187. // If no init given, set it to its default value.
  3188. CompValu local = declVar.location;
  3189. if(declVar.init != null)
  3190. {
  3191. CompValu rVal = GenerateFromRVal(declVar.init, local.GetArgTypes());
  3192. local.PopPre(this, declVar);
  3193. rVal.PushVal(this, declVar.init, declVar.type);
  3194. local.PopPost(this, declVar);
  3195. }
  3196. else
  3197. {
  3198. local.PopPre(this, declVar);
  3199. PushDefaultValue(declVar.type);
  3200. local.PopPost(this, declVar);
  3201. }
  3202. }
  3203. /**
  3204. * @brief Get the type and location of an L-value (eg, variable)
  3205. * @param lVal = L-value expression to evaluate
  3206. * @param argsig = null: it's a field/property
  3207. * else: select overload method that fits these arg types
  3208. */
  3209. private CompValu GenerateFromLVal(TokenLVal lVal)
  3210. {
  3211. return GenerateFromLVal(lVal, null);
  3212. }
  3213. private CompValu GenerateFromLVal(TokenLVal lVal, TokenType[] argsig)
  3214. {
  3215. if(lVal is TokenLValArEle TokenLValArElelVal)
  3216. return GenerateFromLValArEle(TokenLValArElelVal);
  3217. if(lVal is TokenLValBaseField TokenLValBaseFieldlVal)
  3218. return GenerateFromLValBaseField(TokenLValBaseFieldlVal, argsig);
  3219. if(lVal is TokenLValIField TokenLValIFieldlVal)
  3220. return GenerateFromLValIField(TokenLValIFieldlVal, argsig);
  3221. if(lVal is TokenLValName TokenLValNamelVal)
  3222. return GenerateFromLValName(TokenLValNamelVal, argsig);
  3223. if(lVal is TokenLValSField TokenLValSFieldlVal)
  3224. return GenerateFromLValSField(TokenLValSFieldlVal, argsig);
  3225. throw new Exception("bad lval class");
  3226. }
  3227. /**
  3228. * @brief we have an L-value token that is an element within an array.
  3229. * @returns a CompValu giving the type and location of the element of the array.
  3230. */
  3231. private CompValu GenerateFromLValArEle(TokenLValArEle lVal)
  3232. {
  3233. CompValu subCompValu;
  3234. // Compute location of array itself.
  3235. CompValu baseCompValu = GenerateFromRVal(lVal.baseRVal);
  3236. // Maybe it is a fixed array access.
  3237. string basetypestring = baseCompValu.type.ToString();
  3238. if(basetypestring.EndsWith(']'))
  3239. {
  3240. TokenRVal subRVal = lVal.subRVal;
  3241. int nSubs = 1;
  3242. if(subRVal is TokenRValList list)
  3243. {
  3244. nSubs = list.nItems;
  3245. subRVal = list.rVal;
  3246. }
  3247. int rank = basetypestring.IndexOf(']') - basetypestring.IndexOf('[');
  3248. if(nSubs != rank)
  3249. {
  3250. ErrorMsg(lVal.baseRVal, "expect " + rank + " subscript" + ((rank == 1) ? "" : "s") + " but have " + nSubs);
  3251. }
  3252. CompValu[] subCompValus = new CompValu[rank];
  3253. int i;
  3254. for(i = 0; (subRVal != null) && (i < rank); i++)
  3255. {
  3256. subCompValus[i] = GenerateFromRVal(subRVal);
  3257. subRVal = (TokenRVal)subRVal.nextToken;
  3258. }
  3259. while(i < rank)
  3260. subCompValus[i++] = new CompValuInteger(new TokenTypeInt(lVal.subRVal), 0);
  3261. return new CompValuFixArEl(this, baseCompValu, subCompValus);
  3262. }
  3263. // Maybe it is accessing the $idxprop property of a script-defined class.
  3264. if(baseCompValu.type is TokenTypeSDTypeClass typeclass)
  3265. {
  3266. TokenName name = new (lVal, "$idxprop");
  3267. TokenTypeSDTypeClass sdtType = typeclass;
  3268. TokenDeclSDTypeClass sdtDecl = sdtType.decl;
  3269. TokenDeclVar idxProp = FindThisMember(sdtDecl, name, null);
  3270. if(idxProp == null)
  3271. {
  3272. ErrorMsg(lVal, "no index property in class " + sdtDecl.longName.val);
  3273. return new CompValuVoid(lVal);
  3274. }
  3275. if((idxProp.sdtFlags & ScriptReduce.SDT_STATIC) != 0)
  3276. {
  3277. ErrorMsg(lVal, "non-static reference to static member " + idxProp.name.val);
  3278. return new CompValuVoid(idxProp);
  3279. }
  3280. CheckAccess(idxProp, name);
  3281. TokenType[] argTypes = IdxPropArgTypes(idxProp);
  3282. CompValu[] compValus = IdxPropCompValus(lVal, argTypes.Length);
  3283. return new CompValuIdxProp(idxProp, baseCompValu, argTypes, compValus);
  3284. }
  3285. // Maybe they are accessing $idxprop property of a script-defined interface.
  3286. if(baseCompValu.type is TokenTypeSDTypeInterface TokenTypeSDTypeInterfacebaseCompValutype)
  3287. {
  3288. TokenName name = new (lVal, "$idxprop");
  3289. TokenTypeSDTypeInterface sdtType = TokenTypeSDTypeInterfacebaseCompValutype;
  3290. TokenDeclVar idxProp = FindInterfaceMember(sdtType, name, null, ref baseCompValu);
  3291. if(idxProp == null)
  3292. {
  3293. ErrorMsg(lVal, "no index property defined for interface " + sdtType.decl.longName.val);
  3294. return baseCompValu;
  3295. }
  3296. TokenType[] argTypes = IdxPropArgTypes(idxProp);
  3297. CompValu[] compValus = IdxPropCompValus(lVal, argTypes.Length);
  3298. return new CompValuIdxProp(idxProp, baseCompValu, argTypes, compValus);
  3299. }
  3300. // Maybe it is extracting a character from a string.
  3301. if((baseCompValu.type is TokenTypeKey) || (baseCompValu.type is TokenTypeStr))
  3302. {
  3303. subCompValu = GenerateFromRVal(lVal.subRVal);
  3304. return new CompValuStrChr(new TokenTypeChar(lVal), baseCompValu, subCompValu);
  3305. }
  3306. // Maybe it is extracting an element from a list.
  3307. if(baseCompValu.type is TokenTypeList)
  3308. {
  3309. subCompValu = GenerateFromRVal(lVal.subRVal);
  3310. return new CompValuListEl(new TokenTypeObject(lVal), baseCompValu, subCompValu);
  3311. }
  3312. // Access should be to XMR_Array otherwise.
  3313. if(baseCompValu.type is not TokenTypeArray)
  3314. {
  3315. ErrorMsg(lVal, "taking subscript of non-array");
  3316. return baseCompValu;
  3317. }
  3318. subCompValu = GenerateFromRVal(lVal.subRVal);
  3319. return new CompValuArEle(new TokenTypeObject(lVal), baseCompValu, subCompValu);
  3320. }
  3321. /**
  3322. * @brief Get number and type of arguments required by an index property.
  3323. */
  3324. private static TokenType[] IdxPropArgTypes(TokenDeclVar idxProp)
  3325. {
  3326. TokenType[] argTypes;
  3327. if(idxProp.getProp != null)
  3328. {
  3329. int nArgs = idxProp.getProp.argDecl.varDict.Count;
  3330. argTypes = new TokenType[nArgs];
  3331. foreach(TokenDeclVar var in idxProp.getProp.argDecl.varDict)
  3332. {
  3333. argTypes[var.vTableIndex] = var.type;
  3334. }
  3335. }
  3336. else
  3337. {
  3338. int nArgs = idxProp.setProp.argDecl.varDict.Count - 1;
  3339. argTypes = new TokenType[nArgs];
  3340. foreach(TokenDeclVar var in idxProp.setProp.argDecl.varDict)
  3341. {
  3342. if(var.vTableIndex < nArgs)
  3343. {
  3344. argTypes[var.vTableIndex] = var.type;
  3345. }
  3346. }
  3347. }
  3348. return argTypes;
  3349. }
  3350. /**
  3351. * @brief Get number and computed value of index property arguments.
  3352. * @param lVal = list of arguments
  3353. * @param nArgs = number of arguments required
  3354. * @returns null: argument count mismatch
  3355. * else: array of index property argument values
  3356. */
  3357. private CompValu[] IdxPropCompValus(TokenLValArEle lVal, int nArgs)
  3358. {
  3359. TokenRVal subRVal = lVal.subRVal;
  3360. int nSubs = 1;
  3361. if(subRVal is TokenRValList list)
  3362. {
  3363. nSubs = list.nItems;
  3364. subRVal = list.rVal;
  3365. }
  3366. if(nSubs != nArgs)
  3367. {
  3368. ErrorMsg(lVal, "index property requires " + nArgs + " subscript(s)");
  3369. return null;
  3370. }
  3371. CompValu[] subCompValus = new CompValu[nArgs];
  3372. for(int i = 0; i < nArgs; i++)
  3373. {
  3374. subCompValus[i] = GenerateFromRVal(subRVal);
  3375. subRVal = (TokenRVal)subRVal.nextToken;
  3376. }
  3377. return subCompValus;
  3378. }
  3379. /**
  3380. * @brief using 'base' within a script-defined instance method to refer to an instance field/method
  3381. * of the class being extended.
  3382. */
  3383. private CompValu GenerateFromLValBaseField(TokenLValBaseField baseField, TokenType[] argsig)
  3384. {
  3385. string fieldName = baseField.fieldName.val;
  3386. TokenDeclSDType sdtDecl = curDeclFunc.sdtClass;
  3387. if((sdtDecl == null) || ((curDeclFunc.sdtFlags & ScriptReduce.SDT_STATIC) != 0))
  3388. {
  3389. ErrorMsg(baseField, "cannot use 'base' outside instance method body");
  3390. return new CompValuVoid(baseField);
  3391. }
  3392. if(!IsSDTInstMethod())
  3393. {
  3394. ErrorMsg(baseField, "cannot access instance member of base class from static method");
  3395. return new CompValuVoid(baseField);
  3396. }
  3397. TokenDeclVar declVar = FindThisMember(sdtDecl.extends, baseField.fieldName, argsig);
  3398. if(declVar != null)
  3399. {
  3400. CheckAccess(declVar, baseField.fieldName);
  3401. TokenType baseType = declVar.sdtClass.MakeRefToken(baseField);
  3402. CompValu basePtr = new CompValuArg(baseType, 0);
  3403. return AccessInstanceMember(declVar, basePtr, baseField, true);
  3404. }
  3405. ErrorMsg(baseField, "no member " + fieldName + ArgSigString(argsig) + " rootward of " + sdtDecl.longName.val);
  3406. return new CompValuVoid(baseField);
  3407. }
  3408. /**
  3409. * @brief We have an L-value token that is an instance field/method within a struct.
  3410. * @returns a CompValu giving the type and location of the field/method in the struct.
  3411. */
  3412. private CompValu GenerateFromLValIField(TokenLValIField lVal, TokenType[] argsig)
  3413. {
  3414. CompValu baseRVal = GenerateFromRVal(lVal.baseRVal);
  3415. string fieldName = lVal.fieldName.val + ArgSigString(argsig);
  3416. // Maybe they are accessing an instance field, method or property of a script-defined class.
  3417. if(baseRVal.type is TokenTypeSDTypeClass)
  3418. {
  3419. TokenTypeSDTypeClass sdtType = (TokenTypeSDTypeClass)baseRVal.type;
  3420. TokenDeclSDTypeClass sdtDecl = sdtType.decl;
  3421. TokenDeclVar declVar = FindThisMember(sdtDecl, lVal.fieldName, argsig);
  3422. if(declVar != null)
  3423. {
  3424. CheckAccess(declVar, lVal.fieldName);
  3425. return AccessInstanceMember(declVar, baseRVal, lVal, false);
  3426. }
  3427. ErrorMsg(lVal.fieldName, "no member " + fieldName + " in class " + sdtDecl.longName.val);
  3428. return new CompValuVoid(lVal.fieldName);
  3429. }
  3430. // Maybe they are accessing a method or property of a script-defined interface.
  3431. if(baseRVal.type is TokenTypeSDTypeInterface)
  3432. {
  3433. TokenTypeSDTypeInterface sdtType = (TokenTypeSDTypeInterface)baseRVal.type;
  3434. TokenDeclVar declVar = FindInterfaceMember(sdtType, lVal.fieldName, argsig, ref baseRVal);
  3435. if(declVar != null)
  3436. {
  3437. return new CompValuIntfMember(declVar, baseRVal);
  3438. }
  3439. ErrorMsg(lVal.fieldName, "no member " + fieldName + " in interface " + sdtType.decl.longName.val);
  3440. return new CompValuVoid(lVal.fieldName);
  3441. }
  3442. // Since we only have a few built-in types with fields, just pound them out.
  3443. if(baseRVal.type is TokenTypeArray)
  3444. {
  3445. // no arguments, no parentheses, just the field name, returning integer
  3446. // but internally, it is a call to a method()
  3447. if(fieldName == "count")
  3448. {
  3449. return new CompValuIntInstROProp(tokenTypeInt, baseRVal, arrayCountMethodInfo);
  3450. }
  3451. // no arguments but with the parentheses, returning void
  3452. if(fieldName == "clear()")
  3453. {
  3454. return new CompValuIntInstMeth(XMR_Array.clearDelegate, baseRVal, arrayClearMethodInfo);
  3455. }
  3456. // single integer argument, returning an object
  3457. if(fieldName == "index(integer)")
  3458. {
  3459. return new CompValuIntInstMeth(XMR_Array.indexDelegate, baseRVal, arrayIndexMethodInfo);
  3460. }
  3461. if(fieldName == "value(integer)")
  3462. {
  3463. return new CompValuIntInstMeth(XMR_Array.valueDelegate, baseRVal, arrayValueMethodInfo);
  3464. }
  3465. }
  3466. if(baseRVal.type is TokenTypeRot)
  3467. {
  3468. FieldInfo fi = null;
  3469. if(fieldName == "x")
  3470. fi = rotationXFieldInfo;
  3471. if(fieldName == "y")
  3472. fi = rotationYFieldInfo;
  3473. if(fieldName == "z")
  3474. fi = rotationZFieldInfo;
  3475. if(fieldName == "s")
  3476. fi = rotationSFieldInfo;
  3477. if(fi != null)
  3478. {
  3479. return new CompValuField(new TokenTypeFloat(lVal), baseRVal, fi);
  3480. }
  3481. }
  3482. if(baseRVal.type is TokenTypeVec)
  3483. {
  3484. FieldInfo fi = null;
  3485. if(fieldName == "x")
  3486. fi = vectorXFieldInfo;
  3487. if(fieldName == "y")
  3488. fi = vectorYFieldInfo;
  3489. if(fieldName == "z")
  3490. fi = vectorZFieldInfo;
  3491. if(fi != null)
  3492. {
  3493. return new CompValuField(new TokenTypeFloat(lVal), baseRVal, fi);
  3494. }
  3495. }
  3496. ErrorMsg(lVal, "type " + baseRVal.type.ToString() + " does not define member " + fieldName);
  3497. return baseRVal;
  3498. }
  3499. /**
  3500. * @brief We have an L-value token that is a function, method or variable name.
  3501. * @param lVal = name we are looking for
  3502. * @param argsig = null: just look for name as a variable
  3503. * else: look for name as a function/method being called with the given argument types
  3504. * eg, "(string,integer,list)"
  3505. * @returns a CompValu giving the type and location of the function, method or variable.
  3506. */
  3507. private CompValu GenerateFromLValName(TokenLValName lVal, TokenType[] argsig)
  3508. {
  3509. // Look in variable stack then look for built-in constants and functions.
  3510. TokenDeclVar var = FindNamedVar(lVal, argsig);
  3511. if(var == null)
  3512. {
  3513. ErrorMsg(lVal, "undefined constant/function/variable " + lVal.name.val + ArgSigString(argsig));
  3514. return new CompValuVoid(lVal);
  3515. }
  3516. // Maybe it has an implied 'this.' on the front.
  3517. if((var.sdtClass != null) && ((var.sdtFlags & ScriptReduce.SDT_STATIC) == 0))
  3518. {
  3519. if(!IsSDTInstMethod())
  3520. {
  3521. ErrorMsg(lVal, "cannot access instance member of class from static method");
  3522. return new CompValuVoid(lVal);
  3523. }
  3524. // Don't allow something such as:
  3525. //
  3526. // class A {
  3527. // integer I;
  3528. // class B {
  3529. // Print ()
  3530. // {
  3531. // llOwnerSay ("I=" + (string)I); <- access to I not allowed inside class B.
  3532. // explicit reference required as we don't
  3533. // have a valid reference to class A.
  3534. // }
  3535. // }
  3536. // }
  3537. //
  3538. // But do allow something such as:
  3539. //
  3540. // class A {
  3541. // integer I;
  3542. // }
  3543. // class B : A {
  3544. // Print ()
  3545. // {
  3546. // llOwnerSay ("I=" + (string)I);
  3547. // }
  3548. // }
  3549. for(TokenDeclSDType c = curDeclFunc.sdtClass; c != var.sdtClass; c = c.extends)
  3550. {
  3551. if(c == null)
  3552. {
  3553. // our arg0 points to an instance of curDeclFunc.sdtClass, not var.sdtClass
  3554. ErrorMsg(lVal, "cannot access instance member of outer class with implied 'this'");
  3555. break;
  3556. }
  3557. }
  3558. CompValu thisCompValu = new CompValuArg(var.sdtClass.MakeRefToken(lVal), 0);
  3559. return AccessInstanceMember(var, thisCompValu, lVal, false);
  3560. }
  3561. // It's a local variable, static field, global, constant, etc.
  3562. return var.location;
  3563. }
  3564. /**
  3565. * @brief Access a script-defined type's instance member
  3566. * @param declVar = which member (field,method,property) to access
  3567. * @param basePtr = points to particular object instance
  3568. * @param ignoreVirt = true: access declVar's method directly; else: maybe use vTable
  3569. * @returns where the field/method/property is located
  3570. */
  3571. private CompValu AccessInstanceMember(TokenDeclVar declVar, CompValu basePtr, Token errorAt, bool ignoreVirt)
  3572. {
  3573. if((declVar.sdtFlags & ScriptReduce.SDT_STATIC) != 0)
  3574. {
  3575. ErrorMsg(errorAt, "non-static reference to static member " + declVar.name.val);
  3576. return new CompValuVoid(declVar);
  3577. }
  3578. return new CompValuInstMember(declVar, basePtr, ignoreVirt);
  3579. }
  3580. /**
  3581. * @brief we have an L-value token that is a static member within a struct.
  3582. * @returns a CompValu giving the type and location of the member in the struct.
  3583. */
  3584. private CompValu GenerateFromLValSField(TokenLValSField lVal, TokenType[] argsig)
  3585. {
  3586. TokenType stType = lVal.baseType;
  3587. string fieldName = lVal.fieldName.val + ArgSigString(argsig);
  3588. // Maybe they are accessing a static member of a script-defined class.
  3589. if (stType is TokenTypeSDTypeClass sdtType)
  3590. {
  3591. TokenDeclVar declVar = FindThisMember(sdtType.decl, lVal.fieldName, argsig);
  3592. if (declVar != null)
  3593. {
  3594. CheckAccess(declVar, lVal.fieldName);
  3595. if ((declVar.sdtFlags & ScriptReduce.SDT_STATIC) == 0)
  3596. {
  3597. ErrorMsg(lVal.fieldName, "static reference to non-static member " + fieldName);
  3598. return new CompValuVoid(lVal.fieldName);
  3599. }
  3600. return declVar.location;
  3601. }
  3602. }
  3603. ErrorMsg(lVal.fieldName, "no member " + fieldName + " in " + stType.ToString());
  3604. return new CompValuVoid(lVal.fieldName);
  3605. }
  3606. /**
  3607. * @brief generate code from an RVal expression and return its type and where the result is stored.
  3608. * For anything that has side-effects, statements are generated that perform the computation then
  3609. * the result it put in a temp var and the temp var name is returned.
  3610. * For anything without side-effects, they are returned as an equivalent sequence of Emits.
  3611. * @param rVal = rVal token to be evaluated
  3612. * @param argsig = null: not being used in an function/method context
  3613. * else: string giving argument types, eg, "(string,integer,list,vector)"
  3614. * that can be used to select among overloaded methods
  3615. * @returns resultant type and location
  3616. */
  3617. private CompValu GenerateFromRVal(TokenRVal rVal)
  3618. {
  3619. return GenerateFromRVal(rVal, null);
  3620. }
  3621. private CompValu GenerateFromRVal(TokenRVal rVal, TokenType[] argsig)
  3622. {
  3623. errorMessageToken = rVal;
  3624. // Maybe the expression can be converted to a constant.
  3625. bool didOne;
  3626. try
  3627. {
  3628. do
  3629. {
  3630. didOne = false;
  3631. rVal = rVal.TryComputeConstant(LookupBodyConstants, ref didOne);
  3632. } while(didOne);
  3633. }
  3634. catch(Exception ex)
  3635. {
  3636. ErrorMsg(errorMessageToken, ex.Message);
  3637. throw;
  3638. }
  3639. // Generate code for the computation and return resulting type and location.
  3640. CompValu cVal = null;
  3641. if(rVal is TokenRValAsnPost TokenRValAsnPostrVal)
  3642. cVal = GenerateFromRValAsnPost(TokenRValAsnPostrVal);
  3643. else if (rVal is TokenRValAsnPre TokenRValAsnPrerVal)
  3644. cVal = GenerateFromRValAsnPre(TokenRValAsnPrerVal);
  3645. else if (rVal is TokenRValCall TokenRValCallrVal)
  3646. cVal = GenerateFromRValCall(TokenRValCallrVal);
  3647. else if (rVal is TokenRValCast TokenRValCastrVal)
  3648. cVal = GenerateFromRValCast(TokenRValCastrVal);
  3649. else if (rVal is TokenRValCondExpr TokenRValCondExprrVal)
  3650. cVal = GenerateFromRValCondExpr(TokenRValCondExprrVal);
  3651. else if (rVal is TokenRValConst TokenRValConstrVal)
  3652. cVal = GenerateFromRValConst(TokenRValConstrVal);
  3653. else if (rVal is TokenRValInitDef TokenRValInitDefrVal)
  3654. cVal = GenerateFromRValInitDef(TokenRValInitDefrVal);
  3655. else if (rVal is TokenRValIsType TokenRValIsTyperVal)
  3656. cVal = GenerateFromRValIsType(TokenRValIsTyperVal);
  3657. else if (rVal is TokenRValList TokenRValListrVal)
  3658. cVal = GenerateFromRValList(TokenRValListrVal);
  3659. else if (rVal is TokenRValNewArIni TokenRValNewArInirVal)
  3660. cVal = GenerateFromRValNewArIni(TokenRValNewArInirVal);
  3661. else if (rVal is TokenRValOpBin TokenRValOpBinrVal)
  3662. cVal = GenerateFromRValOpBin(TokenRValOpBinrVal);
  3663. else if (rVal is TokenRValOpUn TokenRValOpUnrVal)
  3664. cVal = GenerateFromRValOpUn(TokenRValOpUnrVal);
  3665. else if (rVal is TokenRValParen TokenRValParenrVal)
  3666. cVal = GenerateFromRValParen(TokenRValParenrVal);
  3667. else if (rVal is TokenRValRot TokenRValRotrVal)
  3668. cVal = GenerateFromRValRot(TokenRValRotrVal);
  3669. else if (rVal is TokenRValThis TokenRValThisrVal)
  3670. cVal = GenerateFromRValThis(TokenRValThisrVal);
  3671. else if (rVal is TokenRValUndef TokenRValUndefrVal)
  3672. cVal = GenerateFromRValUndef(TokenRValUndefrVal);
  3673. else if (rVal is TokenRValVec TokenRValVecrVal)
  3674. cVal = GenerateFromRValVec(TokenRValVecrVal);
  3675. else if (rVal is TokenLVal TokenLValrVal)
  3676. cVal = GenerateFromLVal(TokenLValrVal, argsig);
  3677. if(cVal == null)
  3678. throw new Exception("bad rval class " + rVal.GetType().ToString());
  3679. // Sanity check.
  3680. if(!youveAnError)
  3681. {
  3682. if(cVal.type == null)
  3683. throw new Exception("cVal has no type " + cVal.GetType());
  3684. string cValType = cVal.type.ToString();
  3685. string rValType = rVal.GetRValType(this, argsig).ToString();
  3686. if(cValType == "bool")
  3687. cValType = "integer";
  3688. if(rValType == "bool")
  3689. rValType = "integer";
  3690. if(cValType != rValType)
  3691. {
  3692. throw new Exception("cVal.type " + cValType + " != rVal.type " + rValType +
  3693. " (" + rVal.GetType().Name + " " + rVal.SrcLoc + ")");
  3694. }
  3695. }
  3696. return cVal;
  3697. }
  3698. /**
  3699. * @brief compute the result of a binary operator (eg, add, subtract, multiply, lessthan)
  3700. * @param token = binary operator token, includes the left and right operands
  3701. * @returns where the resultant R-value is as something that doesn't have side effects
  3702. */
  3703. private CompValu GenerateFromRValOpBin(TokenRValOpBin token)
  3704. {
  3705. CompValu left, right;
  3706. string opcodeIndex = token.opcode.ToString();
  3707. // Comma operators are special, as they say to compute the left-hand value and
  3708. // discard it, then compute the right-hand argument and that is the result.
  3709. if(opcodeIndex == ",")
  3710. {
  3711. // Compute left-hand operand but throw away result.
  3712. GenerateFromRVal(token.rValLeft);
  3713. // Compute right-hand operand and that is the value of the expression.
  3714. return GenerateFromRVal(token.rValRight);
  3715. }
  3716. // Simple overwriting assignments are their own special case,
  3717. // as we want to cast the R-value to the type of the L-value.
  3718. // And in the case of delegates, we want to use the arg signature
  3719. // of the delegate to select which overloaded method to use.
  3720. if(opcodeIndex == "=")
  3721. {
  3722. if(token.rValLeft is not TokenLVal)
  3723. {
  3724. ErrorMsg(token, "invalid L-value for =");
  3725. return GenerateFromRVal(token.rValLeft);
  3726. }
  3727. left = GenerateFromLVal((TokenLVal)token.rValLeft);
  3728. right = Trivialize(GenerateFromRVal(token.rValRight, left.GetArgTypes()), token.rValRight);
  3729. left.PopPre(this, token.rValLeft);
  3730. right.PushVal(this, token.rValRight, left.type); // push (left.type)right
  3731. left.PopPost(this, token.rValLeft); // pop to left
  3732. return left;
  3733. }
  3734. // There are String.Concat() methods available for 2, 3 and 4 operands.
  3735. // So see if we have a string concat op and optimize if so.
  3736. if((opcodeIndex == "+") ||
  3737. ((opcodeIndex == "+=") &&
  3738. (token.rValLeft is TokenLVal) &&
  3739. (token.rValLeft.GetRValType(this, null) is TokenTypeStr)))
  3740. {
  3741. // We are adding something. Maybe it's a bunch of strings together.
  3742. List<TokenRVal> scorvs = new ();
  3743. if(StringConcatOperands(token.rValLeft, token.rValRight, scorvs, token.opcode))
  3744. {
  3745. // Evaluate all the operands, right-to-left on purpose per LSL scripting.
  3746. int i;
  3747. int n = scorvs.Count;
  3748. CompValu[] scocvs = new CompValu[n];
  3749. for(i = n; --i >= 0;)
  3750. {
  3751. scocvs[i] = GenerateFromRVal(scorvs[i]);
  3752. if(i > 0)
  3753. scocvs[i] = Trivialize(scocvs[i], scorvs[i]);
  3754. }
  3755. /*
  3756. * Figure out where to put the result.
  3757. * A temp if '+', or back in original L-value if '+='.
  3758. */
  3759. CompValu retcv;
  3760. if(opcodeIndex == "+")
  3761. {
  3762. retcv = new CompValuTemp(new TokenTypeStr(token.opcode), this);
  3763. }
  3764. else
  3765. {
  3766. retcv = GenerateFromLVal((TokenLVal)token.rValLeft);
  3767. }
  3768. retcv.PopPre(this, token);
  3769. // Call the String.Concat() methods, passing operands in left-to-right order.
  3770. // Force a cast to string (retcv.type) for each operand.
  3771. ++i;
  3772. scocvs[i].PushVal(this, scorvs[i], retcv.type);
  3773. while(i + 3 < n)
  3774. {
  3775. ++i;
  3776. scocvs[i].PushVal(this, scorvs[i], retcv.type);
  3777. ++i;
  3778. scocvs[i].PushVal(this, scorvs[i], retcv.type);
  3779. ++i;
  3780. scocvs[i].PushVal(this, scorvs[i], retcv.type);
  3781. ilGen.Emit(scorvs[i], OpCodes.Call, stringConcat4MethodInfo);
  3782. }
  3783. if(i + 2 < n)
  3784. {
  3785. ++i;
  3786. scocvs[i].PushVal(this, scorvs[i], retcv.type);
  3787. ++i;
  3788. scocvs[i].PushVal(this, scorvs[i], retcv.type);
  3789. ilGen.Emit(scorvs[i], OpCodes.Call, stringConcat3MethodInfo);
  3790. }
  3791. if(i + 1 < n)
  3792. {
  3793. ++i;
  3794. scocvs[i].PushVal(this, scorvs[i], retcv.type);
  3795. ilGen.Emit(scorvs[i], OpCodes.Call, stringConcat2MethodInfo);
  3796. }
  3797. // Put the result where we want it and return where we put it.
  3798. retcv.PopPost(this, token);
  3799. return retcv;
  3800. }
  3801. }
  3802. // If "&&&", it is a short-circuiting AND.
  3803. // Compute left-hand operand and if true, compute right-hand operand.
  3804. if(opcodeIndex == "&&&")
  3805. {
  3806. bool rightVal;
  3807. left = GenerateFromRVal(token.rValLeft);
  3808. if(!IsConstBoolExpr(left, out bool leftVal))
  3809. {
  3810. ScriptMyLabel falseLabel = ilGen.DefineLabel("ssandfalse");
  3811. left.PushVal(this, tokenTypeBool);
  3812. ilGen.Emit(token, OpCodes.Brfalse, falseLabel);
  3813. right = GenerateFromRVal(token.rValRight);
  3814. if(!IsConstBoolExpr(right, out rightVal))
  3815. {
  3816. right.PushVal(this, tokenTypeBool);
  3817. goto donessand;
  3818. }
  3819. if(!rightVal)
  3820. {
  3821. ilGen.MarkLabel(falseLabel);
  3822. return new CompValuInteger(new TokenTypeInt(token.rValLeft), 0);
  3823. }
  3824. ilGen.Emit(token, OpCodes.Ldc_I4_1);
  3825. donessand:
  3826. ScriptMyLabel doneLabel = ilGen.DefineLabel("ssanddone");
  3827. ilGen.Emit(token, OpCodes.Br, doneLabel);
  3828. ilGen.MarkLabel(falseLabel);
  3829. ilGen.Emit(token, OpCodes.Ldc_I4_0);
  3830. ilGen.MarkLabel(doneLabel);
  3831. CompValuTemp retRVal = new (new TokenTypeInt(token), this);
  3832. retRVal.Pop(this, token);
  3833. return retRVal;
  3834. }
  3835. if(!leftVal)
  3836. {
  3837. return new CompValuInteger(new TokenTypeInt(token.rValLeft), 0);
  3838. }
  3839. right = GenerateFromRVal(token.rValRight);
  3840. if(!IsConstBoolExpr(right, out rightVal))
  3841. {
  3842. right.PushVal(this, tokenTypeBool);
  3843. CompValuTemp retRVal = new (new TokenTypeInt(token), this);
  3844. retRVal.Pop(this, token);
  3845. return retRVal;
  3846. }
  3847. return new CompValuInteger(new TokenTypeInt(token), rightVal ? 1 : 0);
  3848. }
  3849. // If "|||", it is a short-circuiting OR.
  3850. // Compute left-hand operand and if false, compute right-hand operand.
  3851. if(opcodeIndex == "|||")
  3852. {
  3853. bool rightVal;
  3854. left = GenerateFromRVal(token.rValLeft);
  3855. if(!IsConstBoolExpr(left, out bool leftVal))
  3856. {
  3857. ScriptMyLabel trueLabel = ilGen.DefineLabel("ssortrue");
  3858. left.PushVal(this, tokenTypeBool);
  3859. ilGen.Emit(token, OpCodes.Brtrue, trueLabel);
  3860. right = GenerateFromRVal(token.rValRight);
  3861. if(!IsConstBoolExpr(right, out rightVal))
  3862. {
  3863. right.PushVal(this, tokenTypeBool);
  3864. goto donessor;
  3865. }
  3866. if(rightVal)
  3867. {
  3868. ilGen.MarkLabel(trueLabel);
  3869. return new CompValuInteger(new TokenTypeInt(token.rValLeft), 1);
  3870. }
  3871. ilGen.Emit(token, OpCodes.Ldc_I4_0);
  3872. donessor:
  3873. ScriptMyLabel doneLabel = ilGen.DefineLabel("ssanddone");
  3874. ilGen.Emit(token, OpCodes.Br, doneLabel);
  3875. ilGen.MarkLabel(trueLabel);
  3876. ilGen.Emit(token, OpCodes.Ldc_I4_1);
  3877. ilGen.MarkLabel(doneLabel);
  3878. CompValuTemp retRVal = new (new TokenTypeInt(token), this);
  3879. retRVal.Pop(this, token);
  3880. return retRVal;
  3881. }
  3882. if(leftVal)
  3883. {
  3884. return new CompValuInteger(new TokenTypeInt(token.rValLeft), 1);
  3885. }
  3886. right = GenerateFromRVal(token.rValRight);
  3887. if(!IsConstBoolExpr(right, out rightVal))
  3888. {
  3889. right.PushVal(this, tokenTypeBool);
  3890. CompValuTemp retRVal = new (new TokenTypeInt(token), this);
  3891. retRVal.Pop(this, token);
  3892. return retRVal;
  3893. }
  3894. return new CompValuInteger(new TokenTypeInt(token), rightVal ? 1 : 0);
  3895. }
  3896. // Computation of some sort, compute right-hand operand value then left-hand value
  3897. // because LSL is supposed to be right-to-left evaluation.
  3898. right = Trivialize(GenerateFromRVal(token.rValRight), token.rValRight);
  3899. // If left is a script-defined class and there is a method with the operator's name,
  3900. // convert this to a call to that method with the right value as its single parameter.
  3901. // Except don't if the right value is 'undef' so they can always compare to undef.
  3902. TokenType leftType = token.rValLeft.GetRValType(this, null);
  3903. if((leftType is TokenTypeSDTypeClass sdtType) && right.type is not TokenTypeUndef)
  3904. {
  3905. TokenDeclSDTypeClass sdtDecl = sdtType.decl;
  3906. TokenType[] argsig = [right.type];
  3907. TokenName funcName = new (token.opcode, "$op" + opcodeIndex);
  3908. TokenDeclVar declFunc = FindThisMember(sdtDecl, funcName, argsig);
  3909. if(declFunc != null)
  3910. {
  3911. CheckAccess(declFunc, funcName);
  3912. left = GenerateFromRVal(token.rValLeft);
  3913. CompValu method = AccessInstanceMember(declFunc, left, token, false);
  3914. CompValu[] argRVals = [right];
  3915. return GenerateACall(method, argRVals, token);
  3916. }
  3917. }
  3918. // Formulate key string for binOpStrings = (lefttype)(operator)(righttype)
  3919. string leftIndex = leftType.ToString();
  3920. string rightIndex = right.type.ToString();
  3921. string key = leftIndex + opcodeIndex + rightIndex;
  3922. // If that key exists in table, then the operation is defined between those types
  3923. // ... and it produces an R-value of type as given in the table.
  3924. if (BinOpStr.defined.TryGetValue(key, out BinOpStr binOpStr))
  3925. {
  3926. // If table contained an explicit assignment type like +=, output the statement without
  3927. // casting the L-value, then return the L-value as the resultant value.
  3928. //
  3929. // Make sure we don't include comparisons (such as ==, >=, etc).
  3930. // Nothing like +=, -=, %=, etc, generate a boolean, only the comparisons.
  3931. if ((binOpStr.outtype != typeof(bool)) && opcodeIndex.EndsWith('=') && (opcodeIndex != "!="))
  3932. {
  3933. if (token.rValLeft is not TokenLVal)
  3934. {
  3935. ErrorMsg(token.rValLeft, "invalid L-value");
  3936. return GenerateFromRVal(token.rValLeft);
  3937. }
  3938. left = GenerateFromLVal((TokenLVal)token.rValLeft);
  3939. binOpStr.emitBO(this, token, left, right, left);
  3940. return left;
  3941. }
  3942. // It's of the form left binop right.
  3943. // Compute left, perform operation then put result in a temp.
  3944. left = GenerateFromRVal(token.rValLeft);
  3945. CompValu retRVal = new CompValuTemp(TokenType.FromSysType(token.opcode, binOpStr.outtype), this);
  3946. binOpStr.emitBO(this, token, left, right, retRVal);
  3947. return retRVal;
  3948. }
  3949. // Nothing in the table, check for comparing object pointers because of the myriad of types possible.
  3950. // This will compare list pointers, null pointers, script-defined type pointers, array pointers, etc.
  3951. // It will show equal iff the memory addresses are equal and that is good enough.
  3952. if (!leftType.ToSysType().IsValueType && !right.type.ToSysType().IsValueType && ((opcodeIndex == "==") || (opcodeIndex == "!=")))
  3953. {
  3954. CompValuTemp retRVal = new (new TokenTypeInt(token), this);
  3955. left = GenerateFromRVal(token.rValLeft);
  3956. left.PushVal(this, token.rValLeft);
  3957. right.PushVal(this, token.rValRight);
  3958. ilGen.Emit(token, OpCodes.Ceq);
  3959. if(opcodeIndex == "!=")
  3960. {
  3961. ilGen.Emit(token, OpCodes.Ldc_I4_1);
  3962. ilGen.Emit(token, OpCodes.Xor);
  3963. }
  3964. retRVal.Pop(this, token);
  3965. return retRVal;
  3966. }
  3967. // If the opcode ends with "=", it may be something like "+=".
  3968. // So look up the key as if we didn't have the "=" to tell us if the operation is legal.
  3969. // Also, the binary operation's output type must be the same as the L-value type.
  3970. // Likewise, integer += float not allowed because result is float, but float += integer is ok.
  3971. if(opcodeIndex.EndsWith('='))
  3972. {
  3973. string op = opcodeIndex[..^1];
  3974. key = leftIndex + op + rightIndex;
  3975. if(BinOpStr.defined.TryGetValue(key, out binOpStr))
  3976. {
  3977. if(token.rValLeft is not TokenLVal)
  3978. {
  3979. ErrorMsg(token, "invalid L-value for <op>=");
  3980. return GenerateFromRVal(token.rValLeft);
  3981. }
  3982. if(!binOpStr.rmwOK)
  3983. {
  3984. ErrorMsg(token, "<op>= not allowed: " + leftIndex + " " + opcodeIndex + " " + rightIndex);
  3985. return new CompValuVoid(token);
  3986. }
  3987. // Now we know for something like %= that left%right is legal for the types given.
  3988. left = GenerateFromLVal((TokenLVal)token.rValLeft);
  3989. if(binOpStr.outtype == leftType.ToSysType())
  3990. {
  3991. binOpStr.emitBO(this, token, left, right, left);
  3992. }
  3993. else
  3994. {
  3995. CompValu temp = new CompValuTemp(TokenType.FromSysType(token, binOpStr.outtype), this);
  3996. binOpStr.emitBO(this, token, left, right, temp);
  3997. left.PopPre(this, token);
  3998. if(op == "*")
  3999. temp.PushVal(this, token, leftType, true);
  4000. else
  4001. temp.PushVal(this, token, leftType);
  4002. left.PopPost(this, token);
  4003. }
  4004. return left;
  4005. }
  4006. }
  4007. // Can't find it, oh well.
  4008. ErrorMsg(token, "op not defined: " + leftIndex + " " + opcodeIndex + " " + rightIndex);
  4009. return new CompValuVoid(token);
  4010. }
  4011. /**
  4012. * @brief Queue the given operands to the end of the scos list.
  4013. * If it can be broken down into more string concat operands, do so.
  4014. * Otherwise, just push it as one operand.
  4015. * @param leftRVal = left-hand operand of a '+' operation
  4016. * @param rightRVal = right-hand operand of a '+' operation
  4017. * @param scos = left-to-right list of operands for the string concat so far
  4018. * @param addop = the add operator token (either '+' or '+=')
  4019. * @returns false: neither operand is a string, nothing added to scos
  4020. * true: scos = updated with leftRVal then rightRVal added onto the end, possibly broken down further
  4021. */
  4022. private bool StringConcatOperands(TokenRVal leftRVal, TokenRVal rightRVal, List<TokenRVal> scos, TokenKw addop)
  4023. {
  4024. /*
  4025. * If neither operand is a string (eg, float+integer), then the result isn't going to be a string.
  4026. */
  4027. TokenType leftType = leftRVal.GetRValType(this, null);
  4028. TokenType rightType = rightRVal.GetRValType(this, null);
  4029. if(leftType is not TokenTypeStr && rightType is not TokenTypeStr)
  4030. return false;
  4031. // Also, list+string => list so reject that too.
  4032. // Also, string+list => list so reject that too.
  4033. if(leftType is TokenTypeList)
  4034. return false;
  4035. if(rightType is TokenTypeList)
  4036. return false;
  4037. // Append values to the end of the list in left-to-right order.
  4038. // If value is formed from a something+something => string,
  4039. // push them as separate values, otherwise push as one value.
  4040. StringConcatOperand(leftType, leftRVal, scos);
  4041. StringConcatOperand(rightType, rightRVal, scos);
  4042. // Maybe constant strings can be concatted.
  4043. try
  4044. {
  4045. int len;
  4046. while(((len = scos.Count) >= 2) &&
  4047. ((leftRVal = scos[len - 2]) is TokenRValConst) &&
  4048. ((rightRVal = scos[len - 1]) is TokenRValConst))
  4049. {
  4050. object sum = addop.binOpConst(((TokenRValConst)leftRVal).val,
  4051. ((TokenRValConst)rightRVal).val);
  4052. scos[len - 2] = new TokenRValConst(addop, sum);
  4053. scos.RemoveAt(len - 1);
  4054. }
  4055. }
  4056. catch
  4057. {
  4058. }
  4059. // We pushed some string stuff.
  4060. return true;
  4061. }
  4062. /**
  4063. * @brief Queue the given operand to the end of the scos list.
  4064. * If it can be broken down into more string concat operands, do so.
  4065. * Otherwise, just push it as one operand.
  4066. * @param type = rVal's resultant type
  4067. * @param rVal = operand to examine
  4068. * @param scos = left-to-right list of operands for the string concat so far
  4069. * @returns with scos = updated with rVal added onto the end, possibly broken down further
  4070. */
  4071. private void StringConcatOperand(TokenType type, TokenRVal rVal, List<TokenRVal> scos)
  4072. {
  4073. bool didOne;
  4074. do
  4075. {
  4076. didOne = false;
  4077. rVal = rVal.TryComputeConstant(LookupBodyConstants, ref didOne);
  4078. } while(didOne);
  4079. if(type is not TokenTypeStr)
  4080. goto pushasis;
  4081. if(rVal is not TokenRValOpBin)
  4082. goto pushasis;
  4083. TokenRValOpBin rValOpBin = (TokenRValOpBin)rVal;
  4084. if(rValOpBin.opcode is not TokenKwAdd)
  4085. goto pushasis;
  4086. if(StringConcatOperands(rValOpBin.rValLeft, rValOpBin.rValRight, scos, rValOpBin.opcode))
  4087. return;
  4088. pushasis:
  4089. scos.Add(rVal);
  4090. }
  4091. /**
  4092. * @brief compute the result of an unary operator
  4093. * @param token = unary operator token, includes the operand
  4094. * @returns where the resultant R-value is
  4095. */
  4096. private CompValu GenerateFromRValOpUn(TokenRValOpUn token)
  4097. {
  4098. CompValu inRVal = GenerateFromRVal(token.rVal);
  4099. // Script-defined types can define their own methods to handle unary operators.
  4100. if (inRVal.type is TokenTypeSDTypeClass sdtType)
  4101. {
  4102. TokenDeclSDTypeClass sdtDecl = sdtType.decl;
  4103. TokenName funcName = new (token.opcode, "$op" + token.opcode.ToString());
  4104. TokenDeclVar declFunc = FindThisMember(sdtDecl, funcName, zeroArgs);
  4105. if (declFunc != null)
  4106. {
  4107. CheckAccess(declFunc, funcName);
  4108. CompValu method = AccessInstanceMember(declFunc, inRVal, token, false);
  4109. return GenerateACall(method, zeroCompValus, token);
  4110. }
  4111. }
  4112. // Otherwise use the default.
  4113. return UnOpGenerate(inRVal, token.opcode);
  4114. }
  4115. /**
  4116. * @brief postfix operator -- this returns the type and location of the resultant value
  4117. */
  4118. private CompValu GenerateFromRValAsnPost(TokenRValAsnPost asnPost)
  4119. {
  4120. CompValu lVal = GenerateFromLVal(asnPost.lVal);
  4121. // Make up a temp to save original value in.
  4122. CompValuTemp result = new (lVal.type, this);
  4123. // Prepare to pop incremented value back into variable being incremented.
  4124. lVal.PopPre(this, asnPost.lVal);
  4125. // Copy original value to temp and leave value on stack.
  4126. lVal.PushVal(this, asnPost.lVal);
  4127. ilGen.Emit(asnPost.lVal, OpCodes.Dup);
  4128. result.Pop(this, asnPost.lVal);
  4129. // Perform the ++/--.
  4130. if((lVal.type is TokenTypeChar) || (lVal.type is TokenTypeInt))
  4131. {
  4132. ilGen.Emit(asnPost, OpCodes.Ldc_I4_1);
  4133. }
  4134. else if(lVal.type is TokenTypeFloat)
  4135. {
  4136. ilGen.Emit(asnPost, OpCodes.Ldc_R4, 1.0f);
  4137. }
  4138. else
  4139. {
  4140. lVal.PopPost(this, asnPost.lVal);
  4141. ErrorMsg(asnPost, "invalid type for " + asnPost.postfix.ToString());
  4142. return lVal;
  4143. }
  4144. switch(asnPost.postfix.ToString())
  4145. {
  4146. case "++":
  4147. {
  4148. ilGen.Emit(asnPost, OpCodes.Add);
  4149. break;
  4150. }
  4151. case "--":
  4152. {
  4153. ilGen.Emit(asnPost, OpCodes.Sub);
  4154. break;
  4155. }
  4156. default:
  4157. throw new Exception("unknown asnPost op");
  4158. }
  4159. // Store new value in original variable.
  4160. lVal.PopPost(this, asnPost.lVal);
  4161. return result;
  4162. }
  4163. /**
  4164. * @brief prefix operator -- this returns the type and location of the resultant value
  4165. */
  4166. private CompValu GenerateFromRValAsnPre(TokenRValAsnPre asnPre)
  4167. {
  4168. CompValu lVal = GenerateFromLVal(asnPre.lVal);
  4169. // Make up a temp to put result in.
  4170. CompValuTemp result = new (lVal.type, this);
  4171. // Prepare to pop incremented value back into variable being incremented.
  4172. lVal.PopPre(this, asnPre.lVal);
  4173. // Push original value.
  4174. lVal.PushVal(this, asnPre.lVal);
  4175. // Perform the ++/--.
  4176. if((lVal.type is TokenTypeChar) || (lVal.type is TokenTypeInt))
  4177. {
  4178. ilGen.Emit(asnPre, OpCodes.Ldc_I4_1);
  4179. }
  4180. else if(lVal.type is TokenTypeFloat)
  4181. {
  4182. ilGen.Emit(asnPre, OpCodes.Ldc_R4, 1.0f);
  4183. }
  4184. else
  4185. {
  4186. lVal.PopPost(this, asnPre.lVal);
  4187. ErrorMsg(asnPre, "invalid type for " + asnPre.prefix.ToString());
  4188. return lVal;
  4189. }
  4190. switch(asnPre.prefix.ToString())
  4191. {
  4192. case "++":
  4193. {
  4194. ilGen.Emit(asnPre, OpCodes.Add);
  4195. break;
  4196. }
  4197. case "--":
  4198. {
  4199. ilGen.Emit(asnPre, OpCodes.Sub);
  4200. break;
  4201. }
  4202. default:
  4203. throw new Exception("unknown asnPre op");
  4204. }
  4205. // Store new value in temp variable, keeping new value on stack.
  4206. ilGen.Emit(asnPre.lVal, OpCodes.Dup);
  4207. result.Pop(this, asnPre.lVal);
  4208. // Store new value in original variable.
  4209. lVal.PopPost(this, asnPre.lVal);
  4210. return result;
  4211. }
  4212. /**
  4213. * @brief Generate code that calls a function or object's method.
  4214. * @returns where the call's return value is stored (a TokenTypeVoid if void)
  4215. */
  4216. private CompValu GenerateFromRValCall(TokenRValCall call)
  4217. {
  4218. CompValu method;
  4219. CompValu[] argRVals;
  4220. int i, nargs;
  4221. TokenRVal arg;
  4222. TokenType[] argTypes;
  4223. // Compute the values of all the function's call arguments.
  4224. // Save where the computation results are in the argRVals[] array.
  4225. // Might as well build the argument signature from the argument types, too.
  4226. nargs = call.nArgs;
  4227. argRVals = new CompValu[nargs];
  4228. argTypes = new TokenType[nargs];
  4229. if(nargs > 0)
  4230. {
  4231. i = 0;
  4232. for(arg = call.args; arg != null; arg = (TokenRVal)arg.nextToken)
  4233. {
  4234. argRVals[i] = GenerateFromRVal(arg);
  4235. argTypes[i] = argRVals[i].type;
  4236. i++;
  4237. }
  4238. }
  4239. // Get function/method's entrypoint that matches the call argument types.
  4240. method = GenerateFromRVal(call.meth, argTypes);
  4241. if(method == null)
  4242. return null;
  4243. return GenerateACall(method, argRVals, call);
  4244. }
  4245. /**
  4246. * @brief Generate call to a function/method.
  4247. * @param method = function/method being called
  4248. * @param argVRVals = its call parameters (zero length if none)
  4249. * @param call = where in source code call is being made from (for error messages)
  4250. * @returns type and location of return value (CompValuVoid if none)
  4251. */
  4252. private CompValu GenerateACall(CompValu method, CompValu[] argRVals, Token call)
  4253. {
  4254. CompValuTemp result;
  4255. int i, nArgs;
  4256. TokenType retType;
  4257. TokenType[] argTypes;
  4258. // Must be some kind of callable.
  4259. retType = method.GetRetType(); // TokenTypeVoid if void; null means a variable
  4260. if(retType == null)
  4261. {
  4262. ErrorMsg(call, "must be a delegate, function or method");
  4263. return new CompValuVoid(call);
  4264. }
  4265. // Get a location for return value.
  4266. if(retType is TokenTypeVoid)
  4267. {
  4268. result = new CompValuVoid(call);
  4269. }
  4270. else
  4271. {
  4272. result = new CompValuTemp(retType, this);
  4273. }
  4274. // Make sure all arguments are trivial, ie, don't involve their own call labels.
  4275. // For any that aren't, output code to calculate the arg and put in a temporary.
  4276. nArgs = argRVals.Length;
  4277. for(i = 0; i < nArgs; i++)
  4278. {
  4279. if(!argRVals[i].IsReadTrivial(this, call))
  4280. {
  4281. argRVals[i] = Trivialize(argRVals[i], call);
  4282. }
  4283. }
  4284. // Inline functions know how to generate their own call.
  4285. if (method is CompValuInline inline)
  4286. {
  4287. inline.declInline.CodeGen(this, call, result, argRVals);
  4288. return result;
  4289. }
  4290. // Push whatever the function/method needs as a this argument, if anything.
  4291. method.CallPre(this, call);
  4292. // Push the script-visible args, left-to-right.
  4293. argTypes = method.GetArgTypes();
  4294. for(i = 0; i < nArgs; i++)
  4295. {
  4296. if(argTypes == null)
  4297. {
  4298. argRVals[i].PushVal(this, call);
  4299. }
  4300. else
  4301. {
  4302. argRVals[i].PushVal(this, call, argTypes[i]);
  4303. }
  4304. }
  4305. // Now output call instruction.
  4306. method.CallPost(this, call);
  4307. // Deal with the return value (if any), by putting it in 'result'.
  4308. result.Pop(this, call, retType);
  4309. return result;
  4310. }
  4311. /**
  4312. * @brief This is needed to avoid nesting call labels around non-trivial properties.
  4313. * It should be used for the second (and later) operands.
  4314. * Note that a 'call' is considered an operator, so all arguments of a call
  4315. * should be trivialized, but the method itself does not need to be.
  4316. */
  4317. public CompValu Trivialize(CompValu operand, Token errorAt)
  4318. {
  4319. if(operand.IsReadTrivial(this, errorAt))
  4320. return operand;
  4321. CompValuTemp temp = new (operand.type, this);
  4322. operand.PushVal(this, errorAt);
  4323. temp.Pop(this, errorAt);
  4324. return temp;
  4325. }
  4326. /**
  4327. * @brief Generate code that casts a value to a particular type.
  4328. * @returns where the result of the conversion is stored.
  4329. */
  4330. private CompValu GenerateFromRValCast(TokenRValCast cast)
  4331. {
  4332. // If casting to a delegate type, use the argment signature
  4333. // of the delegate to help select the function/method, eg,
  4334. // '(delegate string(integer))ToString'
  4335. // will select 'string ToString(integer x)'
  4336. // instaead of 'string ToString(float x)' or anything else
  4337. TokenType[] argsig = null;
  4338. TokenType outType = cast.castTo;
  4339. if(outType is TokenTypeSDTypeDelegate TokenTypeSDTypeDelegateoutType)
  4340. {
  4341. argsig = TokenTypeSDTypeDelegateoutType.decl.GetArgTypes();
  4342. }
  4343. // Generate the value that is being cast.
  4344. // If the value is already the requested type, just use it as is.
  4345. CompValu inRVal = GenerateFromRVal(cast.rVal, argsig);
  4346. if(inRVal.type == outType)
  4347. return inRVal;
  4348. // Different type, generate casting code, putting the result in a temp of the output type.
  4349. CompValu outRVal = new CompValuTemp(outType, this);
  4350. outRVal.PopPre(this, cast);
  4351. inRVal.PushVal(this, cast, outType, true);
  4352. outRVal.PopPost(this, cast);
  4353. return outRVal;
  4354. }
  4355. /**
  4356. * @brief Compute conditional expression value.
  4357. * @returns type and location of computed value.
  4358. */
  4359. private CompValu GenerateFromRValCondExpr(TokenRValCondExpr rValCondExpr)
  4360. {
  4361. CompValu condValu = GenerateFromRVal(rValCondExpr.condExpr);
  4362. if (IsConstBoolExpr(condValu, out bool condVal))
  4363. {
  4364. return GenerateFromRVal(condVal ? rValCondExpr.trueExpr : rValCondExpr.falseExpr);
  4365. }
  4366. ScriptMyLabel falseLabel = ilGen.DefineLabel("condexfalse");
  4367. ScriptMyLabel doneLabel = ilGen.DefineLabel("condexdone");
  4368. condValu.PushVal(this, rValCondExpr.condExpr, tokenTypeBool);
  4369. ilGen.Emit(rValCondExpr, OpCodes.Brfalse, falseLabel);
  4370. CompValu trueValu = GenerateFromRVal(rValCondExpr.trueExpr);
  4371. trueValu.PushVal(this, rValCondExpr.trueExpr);
  4372. ilGen.Emit(rValCondExpr, OpCodes.Br, doneLabel);
  4373. ilGen.MarkLabel(falseLabel);
  4374. CompValu falseValu = GenerateFromRVal(rValCondExpr.falseExpr);
  4375. falseValu.PushVal(this, rValCondExpr.falseExpr);
  4376. if(trueValu.type.GetType() != falseValu.type.GetType())
  4377. {
  4378. ErrorMsg(rValCondExpr, "? operands " + trueValu.type.ToString() + " : " +
  4379. falseValu.type.ToString() + " must be of same type");
  4380. }
  4381. ilGen.MarkLabel(doneLabel);
  4382. CompValuTemp retRVal = new (trueValu.type, this);
  4383. retRVal.Pop(this, rValCondExpr);
  4384. return retRVal;
  4385. }
  4386. /**
  4387. * @brief Constant in the script somewhere
  4388. * @returns where the constants value is stored
  4389. */
  4390. private static CompValu GenerateFromRValConst(TokenRValConst rValConst)
  4391. {
  4392. switch(rValConst.type)
  4393. {
  4394. case TokenRValConstType.CHAR:
  4395. {
  4396. return new CompValuChar(new TokenTypeChar(rValConst), (char)(rValConst.val));
  4397. }
  4398. case TokenRValConstType.FLOAT:
  4399. {
  4400. return new CompValuFloat(new TokenTypeFloat(rValConst), (double)(rValConst.val));
  4401. }
  4402. case TokenRValConstType.INT:
  4403. {
  4404. return new CompValuInteger(new TokenTypeInt(rValConst), (int)(rValConst.val));
  4405. }
  4406. case TokenRValConstType.KEY:
  4407. {
  4408. return new CompValuString(new TokenTypeKey(rValConst), (string)(rValConst.val));
  4409. }
  4410. case TokenRValConstType.STRING:
  4411. {
  4412. return new CompValuString(new TokenTypeStr(rValConst), (string)(rValConst.val));
  4413. }
  4414. }
  4415. throw new Exception("unknown constant type " + rValConst.val.GetType());
  4416. }
  4417. /**
  4418. * @brief generate a new list object
  4419. * @param rValList = an rVal to create it from
  4420. */
  4421. private CompValu GenerateFromRValList(TokenRValList rValList)
  4422. {
  4423. // Compute all element values and remember where we put them.
  4424. // Do it right-to-left as customary for LSL scripts.
  4425. int i = 0;
  4426. TokenRVal lastRVal = null;
  4427. for(TokenRVal val = rValList.rVal; val != null; val = (TokenRVal)val.nextToken)
  4428. {
  4429. i++;
  4430. val.prevToken = lastRVal;
  4431. lastRVal = val;
  4432. }
  4433. CompValu[] vals = new CompValu[i];
  4434. for(TokenRVal val = lastRVal; val != null; val = (TokenRVal)val.prevToken)
  4435. {
  4436. vals[--i] = GenerateFromRVal(val);
  4437. }
  4438. // This is the temp that will hold the created list.
  4439. CompValuTemp newList = new (new TokenTypeList(rValList.rVal), this);
  4440. // Create a temp object[] array to hold all the initial values.
  4441. ilGen.Emit(rValList, OpCodes.Ldc_I4, rValList.nItems);
  4442. ilGen.Emit(rValList, OpCodes.Newarr, typeof(object));
  4443. // Populate the array.
  4444. i = 0;
  4445. for(TokenRVal val = rValList.rVal; val != null; val = (TokenRVal)val.nextToken)
  4446. {
  4447. // Get pointer to temp array object.
  4448. ilGen.Emit(rValList, OpCodes.Dup);
  4449. // Get index in that array.
  4450. ilGen.Emit(rValList, OpCodes.Ldc_I4, i);
  4451. // Store initialization value in array location.
  4452. // However, floats and ints need to be converted to LSL_Float and LSL_Integer,
  4453. // or things like llSetPayPrice() will puque when they try to cast the elements
  4454. // to LSL_Float or LSL_Integer. Likewise with string/LSL_String.
  4455. //
  4456. // Maybe it's already LSL-boxed so we don't do anything with it except make sure
  4457. // it is an object, not a struct.
  4458. CompValu eRVal = vals[i++];
  4459. eRVal.PushVal(this, val);
  4460. if(eRVal.type.ToLSLWrapType() == null)
  4461. {
  4462. if(eRVal.type is TokenTypeFloat)
  4463. {
  4464. ilGen.Emit(val, OpCodes.Newobj, lslFloatConstructorInfo);
  4465. ilGen.Emit(val, OpCodes.Box, typeof(LSL_Float));
  4466. }
  4467. else if (eRVal.type is TokenTypeInt)
  4468. {
  4469. ilGen.Emit(val, OpCodes.Newobj, lslIntegerConstructorInfo);
  4470. ilGen.Emit(val, OpCodes.Box, typeof(LSL_Integer));
  4471. }
  4472. else if (eRVal.type is TokenTypeBool)
  4473. {
  4474. ilGen.Emit(val, OpCodes.Newobj, lslIntegerConstructorInfo);
  4475. ilGen.Emit(val, OpCodes.Box, typeof(LSL_Integer));
  4476. }
  4477. else if ((eRVal.type is TokenTypeKey) || (eRVal.type is TokenTypeStr))
  4478. {
  4479. ilGen.Emit(val, OpCodes.Newobj, lslStringConstructorInfo);
  4480. ilGen.Emit(val, OpCodes.Box, typeof(LSL_String));
  4481. }
  4482. else if(eRVal.type.ToSysType().IsValueType)
  4483. {
  4484. ilGen.Emit(val, OpCodes.Box, eRVal.type.ToSysType());
  4485. }
  4486. }
  4487. else if(eRVal.type.ToLSLWrapType().IsValueType)
  4488. {
  4489. // Convert the LSL value structs to an object of the LSL-boxed type
  4490. ilGen.Emit(val, OpCodes.Box, eRVal.type.ToLSLWrapType());
  4491. }
  4492. ilGen.Emit(val, OpCodes.Stelem, typeof(object));
  4493. }
  4494. // Create new list object from temp initial value array (whose ref is still on the stack).
  4495. ilGen.Emit(rValList, OpCodes.Newobj, lslListConstructorInfo);
  4496. newList.Pop(this, rValList);
  4497. return newList;
  4498. }
  4499. /**
  4500. * @brief New array allocation with initializer expressions.
  4501. */
  4502. private CompValu GenerateFromRValNewArIni(TokenRValNewArIni rValNewArIni)
  4503. {
  4504. return MallocAndInitArray(rValNewArIni.arrayType, rValNewArIni.valueList);
  4505. }
  4506. /**
  4507. * @brief Mallocate and initialize an array from its initialization list.
  4508. * @param arrayType = type of the array to be allocated and initialized
  4509. * @param values = initialization value list used to size and initialize the array.
  4510. * @returns memory location of the resultant initialized array.
  4511. */
  4512. private CompValu MallocAndInitArray(TokenType arrayType, TokenList values)
  4513. {
  4514. TokenDeclSDTypeClass arrayDecl = ((TokenTypeSDTypeClass)arrayType).decl;
  4515. TokenType eleType = arrayDecl.arrayOfType;
  4516. int rank = arrayDecl.arrayOfRank;
  4517. // Get size of each of the dimensions by scanning the initialization value list
  4518. int[] dimSizes = new int[rank];
  4519. FillInDimSizes(dimSizes, 0, rank, values);
  4520. // Figure out where the array's $new() method is
  4521. TokenType[] newargsig = new TokenType[rank];
  4522. for(int k = 0; k < rank; k++)
  4523. {
  4524. newargsig[k] = tokenTypeInt;
  4525. }
  4526. TokenDeclVar newMeth = FindThisMember(arrayDecl, new TokenName(null, "$new"), newargsig);
  4527. // Output a call to malloc the array with all default values
  4528. // array = ArrayType.$new (dimSizes[0], dimSizes[1], ...)
  4529. CompValuTemp array = new (arrayType, this);
  4530. PushXMRInst();
  4531. for(int k = 0; k < rank; k++)
  4532. {
  4533. ilGen.Emit(values, OpCodes.Ldc_I4, dimSizes[k]);
  4534. }
  4535. ilGen.Emit(values, OpCodes.Call, newMeth.ilGen);
  4536. array.Pop(this, arrayType);
  4537. // Figure out where the array's Set() method is
  4538. TokenType[] setargsig = new TokenType[rank + 1];
  4539. for(int k = 0; k < rank; k++)
  4540. {
  4541. setargsig[k] = tokenTypeInt;
  4542. }
  4543. setargsig[rank] = eleType;
  4544. TokenDeclVar setMeth = FindThisMember(arrayDecl, new TokenName(null, "Set"), setargsig);
  4545. // Fill in the array with the initializer values
  4546. FillInInitVals(array, setMeth, dimSizes, 0, rank, values, eleType);
  4547. // The array is our resultant value
  4548. return array;
  4549. }
  4550. /**
  4551. * @brief Compute an array's dimensions given its initialization value list
  4552. * @param dimSizes = filled in with array's dimensions
  4553. * @param dimNo = what dimension the 'values' list applies to
  4554. * @param rank = total number of dimensions of the array
  4555. * @param values = list of values to initialize the array's 'dimNo' dimension with
  4556. * @returns with dimSizes[dimNo..rank-1] filled in
  4557. */
  4558. private static void FillInDimSizes(int[] dimSizes, int dimNo, int rank, TokenList values)
  4559. {
  4560. // the size of a dimension is the largest number of initializer elements at this level
  4561. // for dimNo 0, this is the number of elements in the top-level list
  4562. if(dimSizes[dimNo] < values.tl.Count)
  4563. dimSizes[dimNo] = values.tl.Count;
  4564. // see if there is another dimension to calculate
  4565. if(++dimNo < rank)
  4566. {
  4567. // its size is the size of the largest initializer list at the next inner level
  4568. foreach(Token val in values.tl)
  4569. {
  4570. if (val is TokenList subvals)
  4571. {
  4572. FillInDimSizes(dimSizes, dimNo, rank, subvals);
  4573. }
  4574. }
  4575. }
  4576. }
  4577. /**
  4578. * @brief Output code to fill in array's initialization values
  4579. * @param array = array to be filled in
  4580. * @param setMeth = the array's Set() method
  4581. * @param subscripts = holds subscripts being built
  4582. * @param dimNo = which dimension the 'values' are for
  4583. * @param values = list of initialization values for dimension 'dimNo'
  4584. * @param rank = number of dimensions of 'array'
  4585. * @param values = list of values to initialize the array's 'dimNo' dimension with
  4586. * @param eleType = the element's type
  4587. * @returns with code emitted to initialize array's [subscripts[0], ..., subscripts[dimNo-1], *, *, ...]
  4588. * dimNo and up completely filled ---^
  4589. */
  4590. private void FillInInitVals(CompValu array, TokenDeclVar setMeth, int[] subscripts, int dimNo, int rank, TokenList values, TokenType eleType)
  4591. {
  4592. subscripts[dimNo] = 0;
  4593. foreach(Token val in values.tl)
  4594. {
  4595. CompValu initValue = null;
  4596. // If it is a sublist, process it.
  4597. // If we don't have enough subscripts yet, hopefully that sublist will have enough.
  4598. // If we already have enough subscripts, then that sublist can be for an element of this supposedly jagged array.
  4599. if (val is TokenList sublist)
  4600. {
  4601. if (dimNo + 1 < rank)
  4602. {
  4603. // We don't have enough subscripts yet, hopefully the sublist has the rest.
  4604. FillInInitVals(array, setMeth, subscripts, dimNo + 1, rank, sublist, eleType);
  4605. }
  4606. else if ((eleType is TokenTypeSDTypeClass eleTypeclass) && (eleTypeclass.decl.arrayOfType is null))
  4607. {
  4608. // If we aren't a jagged array either, we can't do anything with the sublist.
  4609. ErrorMsg(val, "too many brace levels");
  4610. }
  4611. else
  4612. {
  4613. // We are a jagged array, so malloc a subarray and initialize it with the sublist.
  4614. // Then we can use that subarray to fill this array's element.
  4615. initValue = MallocAndInitArray(eleType, sublist);
  4616. }
  4617. }
  4618. // If it is a value expression, then output code to compute the value.
  4619. if (val is TokenRVal val1)
  4620. {
  4621. if(dimNo + 1 < rank)
  4622. {
  4623. ErrorMsg((Token)val, "not enough brace levels");
  4624. }
  4625. else
  4626. {
  4627. initValue = GenerateFromRVal(val1);
  4628. }
  4629. }
  4630. // If there is an initValue, output "array.Set (subscript[0], subscript[1], ..., initValue)"
  4631. if(initValue != null)
  4632. {
  4633. array.PushVal(this, val);
  4634. for(int i = 0; i <= dimNo; i++)
  4635. {
  4636. ilGen.Emit(val, OpCodes.Ldc_I4, subscripts[i]);
  4637. }
  4638. initValue.PushVal(this, val, eleType);
  4639. ilGen.Emit(val, OpCodes.Call, setMeth.ilGen);
  4640. }
  4641. // That subscript is processed one way or another, on to the next.
  4642. subscripts[dimNo]++;
  4643. }
  4644. }
  4645. /**
  4646. * @brief parenthesized expression
  4647. * @returns type and location of the result of the computation.
  4648. */
  4649. private CompValu GenerateFromRValParen(TokenRValParen rValParen)
  4650. {
  4651. return GenerateFromRVal(rValParen.rVal);
  4652. }
  4653. /**
  4654. * @brief create a rotation object from the x,y,z,w value expressions.
  4655. */
  4656. private CompValu GenerateFromRValRot(TokenRValRot rValRot)
  4657. {
  4658. CompValu xRVal, yRVal, zRVal, wRVal;
  4659. xRVal = Trivialize(GenerateFromRVal(rValRot.xRVal), rValRot);
  4660. yRVal = Trivialize(GenerateFromRVal(rValRot.yRVal), rValRot);
  4661. zRVal = Trivialize(GenerateFromRVal(rValRot.zRVal), rValRot);
  4662. wRVal = Trivialize(GenerateFromRVal(rValRot.wRVal), rValRot);
  4663. return new CompValuRot(new TokenTypeRot(rValRot), xRVal, yRVal, zRVal, wRVal);
  4664. }
  4665. /**
  4666. * @brief Using 'this' as a pointer to the current script-defined instance object.
  4667. * The value is located in arg #0 of the current instance method.
  4668. */
  4669. private CompValu GenerateFromRValThis(TokenRValThis zhis)
  4670. {
  4671. if(!IsSDTInstMethod())
  4672. {
  4673. ErrorMsg(zhis, "cannot access instance member of class from static method");
  4674. return new CompValuVoid(zhis);
  4675. }
  4676. return new CompValuArg(curDeclFunc.sdtClass.MakeRefToken(zhis), 0);
  4677. }
  4678. /**
  4679. * @brief 'undefined' constant.
  4680. * If this constant gets written to an array element, it will delete that element from the array.
  4681. * If the script retrieves an element by key that is not defined, it will get this value.
  4682. * This value can be stored in and retrieved from variables of type 'object' or script-defined classes.
  4683. * It is a runtime error to cast this value to any other type, eg,
  4684. * we don't allow list or string variables to be null pointers.
  4685. */
  4686. private static CompValu GenerateFromRValUndef(TokenRValUndef rValUndef)
  4687. {
  4688. return new CompValuNull(new TokenTypeUndef(rValUndef));
  4689. }
  4690. /**
  4691. * @brief create a vector object from the x,y,z value expressions.
  4692. */
  4693. private CompValu GenerateFromRValVec(TokenRValVec rValVec)
  4694. {
  4695. CompValu xRVal, yRVal, zRVal;
  4696. xRVal = Trivialize(GenerateFromRVal(rValVec.xRVal), rValVec);
  4697. yRVal = Trivialize(GenerateFromRVal(rValVec.yRVal), rValVec);
  4698. zRVal = Trivialize(GenerateFromRVal(rValVec.zRVal), rValVec);
  4699. return new CompValuVec(new TokenTypeVec(rValVec), xRVal, yRVal, zRVal);
  4700. }
  4701. /**
  4702. * @brief Generate code to get the default initialization value for a variable.
  4703. */
  4704. private CompValu GenerateFromRValInitDef(TokenRValInitDef rValInitDef)
  4705. {
  4706. TokenType type = rValInitDef.type;
  4707. if(type is TokenTypeChar)
  4708. {
  4709. return new CompValuChar(type, (char)0);
  4710. }
  4711. if(type is TokenTypeRot)
  4712. {
  4713. CompValuFloat x = new (type, ScriptBaseClass.ZERO_ROTATION.x);
  4714. CompValuFloat y = new (type, ScriptBaseClass.ZERO_ROTATION.y);
  4715. CompValuFloat z = new (type, ScriptBaseClass.ZERO_ROTATION.z);
  4716. CompValuFloat s = new (type, ScriptBaseClass.ZERO_ROTATION.s);
  4717. return new CompValuRot(type, x, y, z, s);
  4718. }
  4719. if((type is TokenTypeKey) || (type is TokenTypeStr))
  4720. {
  4721. return new CompValuString(type, "");
  4722. }
  4723. if(type is TokenTypeVec)
  4724. {
  4725. CompValuFloat x = new (type, ScriptBaseClass.ZERO_VECTOR.x);
  4726. CompValuFloat y = new (type, ScriptBaseClass.ZERO_VECTOR.y);
  4727. CompValuFloat z = new (type, ScriptBaseClass.ZERO_VECTOR.z);
  4728. return new CompValuVec(type, x, y, z);
  4729. }
  4730. if(type is TokenTypeInt)
  4731. {
  4732. return new CompValuInteger(type, 0);
  4733. }
  4734. if(type is TokenTypeFloat)
  4735. {
  4736. return new CompValuFloat(type, 0);
  4737. }
  4738. if(type is TokenTypeVoid)
  4739. {
  4740. return new CompValuVoid(type);
  4741. }
  4742. // Default for 'object' type is 'undef'.
  4743. // Likewise for script-defined classes and interfaces.
  4744. if((type is TokenTypeObject) || (type is TokenTypeSDTypeClass) || (type is TokenTypeSDTypeDelegate) ||
  4745. (type is TokenTypeSDTypeInterface) || (type is TokenTypeExc))
  4746. {
  4747. return new CompValuNull(type);
  4748. }
  4749. // array and list
  4750. CompValuTemp temp = new (type, this);
  4751. PushDefaultValue(type);
  4752. temp.Pop(this, rValInitDef, type);
  4753. return temp;
  4754. }
  4755. /**
  4756. * @brief Generate code to process an <rVal> is <type> expression, and produce a boolean value.
  4757. */
  4758. private CompValu GenerateFromRValIsType(TokenRValIsType rValIsType)
  4759. {
  4760. // Expression we want to know the type of.
  4761. CompValu val = GenerateFromRVal(rValIsType.rValExp);
  4762. // Pass it in to top-level type expression decoder.
  4763. return GenerateFromTypeExp(val, rValIsType.typeExp);
  4764. }
  4765. /**
  4766. * @brief See if the type of the given value matches the type expression.
  4767. * @param val = where the value to be evaluated is stored
  4768. * @param typeExp = script tokens representing type expression
  4769. * @returns location where the boolean result is stored
  4770. */
  4771. private CompValu GenerateFromTypeExp(CompValu val, TokenTypeExp typeExp)
  4772. {
  4773. if(typeExp is TokenTypeExpBinOp op1)
  4774. {
  4775. CompValu left = GenerateFromTypeExp(val, op1.leftOp);
  4776. CompValu right = GenerateFromTypeExp(val, op1.rightOp);
  4777. CompValuTemp result = new (tokenTypeBool, this);
  4778. Token op = op1.binOp;
  4779. left.PushVal(this, op1.leftOp);
  4780. right.PushVal(this, op1.rightOp);
  4781. if(op is TokenKwAnd)
  4782. {
  4783. ilGen.Emit(typeExp, OpCodes.And);
  4784. }
  4785. else if(op is TokenKwOr)
  4786. {
  4787. ilGen.Emit(typeExp, OpCodes.Or);
  4788. }
  4789. else
  4790. {
  4791. throw new Exception("unknown TokenTypeExpBinOp " + op.GetType());
  4792. }
  4793. result.Pop(this, typeExp);
  4794. return result;
  4795. }
  4796. if(typeExp is TokenTypeExpNot expnot)
  4797. {
  4798. CompValu interm = GenerateFromTypeExp(val, expnot.typeExp);
  4799. CompValuTemp result = new (tokenTypeBool, this);
  4800. interm.PushVal(this, expnot.typeExp, tokenTypeBool);
  4801. ilGen.Emit(typeExp, OpCodes.Ldc_I4_1);
  4802. ilGen.Emit(typeExp, OpCodes.Xor);
  4803. result.Pop(this, typeExp);
  4804. return result;
  4805. }
  4806. if(typeExp is TokenTypeExpPar TokenTypeExpPartypeExp)
  4807. {
  4808. return GenerateFromTypeExp(val, TokenTypeExpPartypeExp.typeExp);
  4809. }
  4810. if(typeExp is TokenTypeExpType TokenTypeExpTypetypeExp)
  4811. {
  4812. CompValuTemp result = new (tokenTypeBool, this);
  4813. val.PushVal(this, typeExp);
  4814. ilGen.Emit(typeExp, OpCodes.Isinst, TokenTypeExpTypetypeExp.typeToken.ToSysType());
  4815. ilGen.Emit(typeExp, OpCodes.Ldnull);
  4816. ilGen.Emit(typeExp, OpCodes.Ceq);
  4817. ilGen.Emit(typeExp, OpCodes.Ldc_I4_1);
  4818. ilGen.Emit(typeExp, OpCodes.Xor);
  4819. result.Pop(this, typeExp);
  4820. return result;
  4821. }
  4822. if(typeExp is TokenTypeExpUndef)
  4823. {
  4824. CompValuTemp result = new (tokenTypeBool, this);
  4825. val.PushVal(this, typeExp);
  4826. ilGen.Emit(typeExp, OpCodes.Ldnull);
  4827. ilGen.Emit(typeExp, OpCodes.Ceq);
  4828. result.Pop(this, typeExp);
  4829. return result;
  4830. }
  4831. throw new Exception("unknown TokenTypeExp type " + typeExp.GetType());
  4832. }
  4833. /**
  4834. * @brief Push the default (null) value for a particular variable
  4835. * @param var = variable to get the default value for
  4836. * @returns with value pushed on stack
  4837. */
  4838. public void PushVarDefaultValue(TokenDeclVar var)
  4839. {
  4840. PushDefaultValue(var.type);
  4841. }
  4842. public void PushDefaultValue(TokenType type)
  4843. {
  4844. if(type is TokenTypeArray)
  4845. {
  4846. PushXMRInst(); // instance
  4847. ilGen.Emit(type, OpCodes.Newobj, xmrArrayConstructorInfo);
  4848. return;
  4849. }
  4850. if(type is TokenTypeChar)
  4851. {
  4852. ilGen.Emit(type, OpCodes.Ldc_I4_0);
  4853. return;
  4854. }
  4855. if(type is TokenTypeList)
  4856. {
  4857. ilGen.Emit(type, OpCodes.Ldc_I4_0);
  4858. ilGen.Emit(type, OpCodes.Newarr, typeof(object));
  4859. ilGen.Emit(type, OpCodes.Newobj, lslListConstructorInfo);
  4860. return;
  4861. }
  4862. if(type is TokenTypeRot)
  4863. {
  4864. // Mono is tOO stOOpid to allow: ilGen.Emit (OpCodes.Ldsfld, zeroRotationFieldInfo);
  4865. ilGen.Emit(type, OpCodes.Ldc_R8, ScriptBaseClass.ZERO_ROTATION.x);
  4866. ilGen.Emit(type, OpCodes.Ldc_R8, ScriptBaseClass.ZERO_ROTATION.y);
  4867. ilGen.Emit(type, OpCodes.Ldc_R8, ScriptBaseClass.ZERO_ROTATION.z);
  4868. ilGen.Emit(type, OpCodes.Ldc_R8, ScriptBaseClass.ZERO_ROTATION.s);
  4869. ilGen.Emit(type, OpCodes.Newobj, lslRotationConstructorInfo);
  4870. return;
  4871. }
  4872. if((type is TokenTypeKey) || (type is TokenTypeStr))
  4873. {
  4874. ilGen.Emit(type, OpCodes.Ldstr, "");
  4875. return;
  4876. }
  4877. if(type is TokenTypeVec)
  4878. {
  4879. // Mono is tOO stOOpid to allow: ilGen.Emit (OpCodes.Ldsfld, zeroVectorFieldInfo);
  4880. ilGen.Emit(type, OpCodes.Ldc_R8, ScriptBaseClass.ZERO_VECTOR.x);
  4881. ilGen.Emit(type, OpCodes.Ldc_R8, ScriptBaseClass.ZERO_VECTOR.y);
  4882. ilGen.Emit(type, OpCodes.Ldc_R8, ScriptBaseClass.ZERO_VECTOR.z);
  4883. ilGen.Emit(type, OpCodes.Newobj, lslVectorConstructorInfo);
  4884. return;
  4885. }
  4886. if(type is TokenTypeInt)
  4887. {
  4888. ilGen.Emit(type, OpCodes.Ldc_I4_0);
  4889. return;
  4890. }
  4891. if(type is TokenTypeFloat)
  4892. {
  4893. ilGen.Emit(type, OpCodes.Ldc_R4, 0.0f);
  4894. return;
  4895. }
  4896. // Default for 'object' type is 'undef'.
  4897. // Likewise for script-defined classes and interfaces.
  4898. if((type is TokenTypeObject) || (type is TokenTypeSDTypeClass) || (type is TokenTypeSDTypeInterface) || (type is TokenTypeExc))
  4899. {
  4900. ilGen.Emit(type, OpCodes.Ldnull);
  4901. return;
  4902. }
  4903. // Void is pushed as the default return value of a void function.
  4904. // So just push nothing as expected of void functions.
  4905. if(type is TokenTypeVoid)
  4906. {
  4907. return;
  4908. }
  4909. // Default for 'delegate' type is 'undef'.
  4910. if(type is TokenTypeSDTypeDelegate)
  4911. {
  4912. ilGen.Emit(type, OpCodes.Ldnull);
  4913. return;
  4914. }
  4915. throw new Exception("unknown type " + type.GetType().ToString());
  4916. }
  4917. /**
  4918. * @brief Determine if the expression has a constant boolean value
  4919. * and if so, if the value is true or false.
  4920. * @param expr = expression to evaluate
  4921. * @returns true: expression is contant and has boolean value true
  4922. * false: otherwise
  4923. */
  4924. private static bool IsConstBoolExprTrue(CompValu expr)
  4925. {
  4926. return IsConstBoolExpr(expr, out bool constVal) && constVal;
  4927. }
  4928. private static bool IsConstBoolExpr(CompValu expr, out bool constVal)
  4929. {
  4930. if(expr is CompValuChar CompValuCharexpr)
  4931. {
  4932. constVal = CompValuCharexpr.x != 0;
  4933. return true;
  4934. }
  4935. if(expr is CompValuFloat CompValuFloatexpr)
  4936. {
  4937. constVal = CompValuFloatexpr.x != 0;
  4938. return true;
  4939. }
  4940. if(expr is CompValuInteger CompValuIntegerexpr)
  4941. {
  4942. constVal = CompValuIntegerexpr.x != 0;
  4943. return true;
  4944. }
  4945. if(expr is CompValuString CompValuStringexpr)
  4946. {
  4947. string s = CompValuStringexpr.x;
  4948. constVal = s != "";
  4949. if(constVal && (expr.type is TokenTypeKey))
  4950. {
  4951. constVal = s != ScriptBaseClass.NULL_KEY;
  4952. }
  4953. return true;
  4954. }
  4955. constVal = false;
  4956. return false;
  4957. }
  4958. /**
  4959. * @brief Determine if the expression has a constant integer value
  4960. * and if so, return the integer value.
  4961. * @param expr = expression to evaluate
  4962. * @returns true: expression is contant and has integer value
  4963. * false: otherwise
  4964. */
  4965. private static bool IsConstIntExpr(CompValu expr, out int constVal)
  4966. {
  4967. if(expr is CompValuChar CompValuCharexpr)
  4968. {
  4969. constVal = (int)CompValuCharexpr.x;
  4970. return true;
  4971. }
  4972. if(expr is CompValuInteger CompValuIntegerexpr)
  4973. {
  4974. constVal = CompValuIntegerexpr.x;
  4975. return true;
  4976. }
  4977. constVal = 0;
  4978. return false;
  4979. }
  4980. /**
  4981. * @brief Determine if the expression has a constant string value
  4982. * and if so, return the string value.
  4983. * @param expr = expression to evaluate
  4984. * @returns true: expression is contant and has string value
  4985. * false: otherwise
  4986. */
  4987. private static bool IsConstStrExpr(CompValu expr, out string constVal)
  4988. {
  4989. if(expr is CompValuString exprstring)
  4990. {
  4991. constVal = exprstring.x;
  4992. return true;
  4993. }
  4994. constVal = "";
  4995. return false;
  4996. }
  4997. /**
  4998. * @brief create table of legal event handler prototypes.
  4999. * This is used to make sure script's event handler declrations are valid.
  5000. */
  5001. private static VarDict CreateLegalEventHandlers()
  5002. {
  5003. // Get handler prototypes with full argument lists.
  5004. VarDict leh = new InternalFuncDict(typeof(IEventHandlers), false);
  5005. // We want the scripts to be able to declare their handlers with
  5006. // fewer arguments than the full argument lists. So define additional
  5007. // prototypes with fewer arguments.
  5008. TokenDeclVar[] fullArgProtos = new TokenDeclVar[leh.Count];
  5009. int i = 0;
  5010. foreach(TokenDeclVar fap in leh)
  5011. fullArgProtos[i++] = fap;
  5012. foreach(TokenDeclVar fap in fullArgProtos)
  5013. {
  5014. TokenArgDecl fal = fap.argDecl;
  5015. int fullArgCount = fal.vars.Length;
  5016. for(i = 0; i < fullArgCount; i++)
  5017. {
  5018. TokenArgDecl shortArgList = new (null);
  5019. for(int j = 0; j < i; j++)
  5020. {
  5021. TokenDeclVar var = fal.vars[j];
  5022. shortArgList.AddArg(var.type, var.name);
  5023. }
  5024. TokenDeclVar shortArgProto = new (null, null, null)
  5025. {
  5026. name = new TokenName(null, fap.GetSimpleName()),
  5027. retType = fap.retType,
  5028. argDecl = shortArgList
  5029. };
  5030. leh.AddEntry(shortArgProto);
  5031. }
  5032. }
  5033. return leh;
  5034. }
  5035. /**
  5036. * @brief Emit a call to CheckRun(), (voluntary multitasking switch)
  5037. */
  5038. public void EmitCallCheckRun(Token errorAt, bool stack)
  5039. {
  5040. if(curDeclFunc.IsFuncTrivial(this))
  5041. throw new Exception(curDeclFunc.fullName + " is supposed to be trivial");
  5042. _ = new CallLabel(this, errorAt); // jump here when stack restored
  5043. PushXMRInst(); // instance
  5044. ilGen.Emit(errorAt, OpCodes.Call, stack ? checkRunStackMethInfo : checkRunQuickMethInfo);
  5045. openCallLabel = null;
  5046. }
  5047. /**
  5048. * @brief Emit code to push a callNo var on the stack.
  5049. */
  5050. public void GetCallNo(Token errorAt, ScriptMyLocal callNoVar)
  5051. {
  5052. ilGen.Emit(errorAt, OpCodes.Ldloc, callNoVar);
  5053. //ilGen.Emit (errorAt, OpCodes.Ldloca, callNoVar);
  5054. //ilGen.Emit (errorAt, OpCodes.Volatile);
  5055. //ilGen.Emit (errorAt, OpCodes.Ldind_I4);
  5056. }
  5057. public void GetCallNo(Token errorAt, CompValu callNoVar)
  5058. {
  5059. callNoVar.PushVal(this, errorAt);
  5060. //callNoVar.PushRef (this, errorAt);
  5061. //ilGen.Emit (errorAt, OpCodes.Volatile);
  5062. //ilGen.Emit (errorAt, OpCodes.Ldind_I4);
  5063. }
  5064. /**
  5065. * @brief Emit code to set a callNo var to a given constant.
  5066. */
  5067. public void SetCallNo(Token errorAt, ScriptMyLocal callNoVar, int val)
  5068. {
  5069. ilGen.Emit(errorAt, OpCodes.Ldc_I4, val);
  5070. ilGen.Emit(errorAt, OpCodes.Stloc, callNoVar);
  5071. //ilGen.Emit (errorAt, OpCodes.Ldloca, callNoVar);
  5072. //ilGen.Emit (errorAt, OpCodes.Ldc_I4, val);
  5073. //ilGen.Emit (errorAt, OpCodes.Volatile);
  5074. //ilGen.Emit (errorAt, OpCodes.Stind_I4);
  5075. }
  5076. public void SetCallNo(Token errorAt, CompValu callNoVar, int val)
  5077. {
  5078. callNoVar.PopPre(this, errorAt);
  5079. ilGen.Emit(errorAt, OpCodes.Ldc_I4, val);
  5080. callNoVar.PopPost(this, errorAt);
  5081. //callNoVar.PushRef (this, errorAt);
  5082. //ilGen.Emit (errorAt, OpCodes.Ldc_I4, val);
  5083. //ilGen.Emit (errorAt, OpCodes.Volatile);
  5084. //ilGen.Emit (errorAt, OpCodes.Stind_I4);
  5085. }
  5086. /**
  5087. * @brief handle a unary operator, such as -x.
  5088. */
  5089. private CompValu UnOpGenerate(CompValu inRVal, Token opcode)
  5090. {
  5091. // - Negate
  5092. if(opcode is TokenKwSub)
  5093. {
  5094. if(inRVal.type is TokenTypeFloat)
  5095. {
  5096. CompValuTemp outRVal = new (new TokenTypeFloat(opcode), this);
  5097. inRVal.PushVal(this, opcode, outRVal.type); // push value to negate, make sure not LSL-boxed
  5098. ilGen.Emit(opcode, OpCodes.Neg); // compute the negative
  5099. outRVal.Pop(this, opcode); // pop into result
  5100. return outRVal; // tell caller where we put it
  5101. }
  5102. if(inRVal.type is TokenTypeInt)
  5103. {
  5104. CompValuTemp outRVal = new (new TokenTypeInt(opcode), this);
  5105. inRVal.PushVal(this, opcode, outRVal.type); // push value to negate, make sure not LSL-boxed
  5106. ilGen.Emit(opcode, OpCodes.Neg); // compute the negative
  5107. outRVal.Pop(this, opcode); // pop into result
  5108. return outRVal; // tell caller where we put it
  5109. }
  5110. if(inRVal.type is TokenTypeRot)
  5111. {
  5112. CompValuTemp outRVal = new (inRVal.type, this);
  5113. inRVal.PushVal(this, opcode); // push rotation, then call negate routine
  5114. ilGen.Emit(opcode, OpCodes.Call, lslRotationNegateMethodInfo);
  5115. outRVal.Pop(this, opcode); // pop into result
  5116. return outRVal; // tell caller where we put it
  5117. }
  5118. if(inRVal.type is TokenTypeVec)
  5119. {
  5120. CompValuTemp outRVal = new (inRVal.type, this);
  5121. inRVal.PushVal(this, opcode); // push vector, then call negate routine
  5122. ilGen.Emit(opcode, OpCodes.Call, lslVectorNegateMethodInfo);
  5123. outRVal.Pop(this, opcode); // pop into result
  5124. return outRVal; // tell caller where we put it
  5125. }
  5126. if (inRVal.type is TokenTypeBool)
  5127. {
  5128. CompValuTemp outRVal = new (new TokenTypeInt(opcode), this);
  5129. inRVal.PushVal(this, opcode, outRVal.type); // push value to negate, make sure not LSL-boxed
  5130. ilGen.Emit(opcode, OpCodes.Neg); // compute the negative
  5131. outRVal.Pop(this, opcode); // pop into result
  5132. return outRVal; // tell caller where we put it
  5133. }
  5134. ErrorMsg(opcode, "can't negate a " + inRVal.type.ToString());
  5135. return inRVal;
  5136. }
  5137. // ~ Complement (bitwise integer)
  5138. if(opcode is TokenKwTilde)
  5139. {
  5140. if(inRVal.type is TokenTypeInt)
  5141. {
  5142. CompValuTemp outRVal = new (new TokenTypeInt(opcode), this);
  5143. inRVal.PushVal(this, opcode, outRVal.type); // push value to negate, make sure not LSL-boxed
  5144. ilGen.Emit(opcode, OpCodes.Not); // compute the complement
  5145. outRVal.Pop(this, opcode); // pop into result
  5146. return outRVal; // tell caller where we put it
  5147. }
  5148. ErrorMsg(opcode, "can't complement a " + inRVal.type.ToString());
  5149. return inRVal;
  5150. }
  5151. // ! Not (boolean)
  5152. //
  5153. // We stuff the 0/1 result in an int because I've seen x+!y in scripts
  5154. // and we don't want to have to create tables to handle int+bool and
  5155. // everything like that.
  5156. if(opcode is TokenKwExclam)
  5157. {
  5158. CompValuTemp outRVal = new (new TokenTypeInt(opcode), this);
  5159. inRVal.PushVal(this, opcode, tokenTypeBool); // anything converts to boolean
  5160. ilGen.Emit(opcode, OpCodes.Ldc_I4_1); // then XOR with 1 to flip it
  5161. ilGen.Emit(opcode, OpCodes.Xor);
  5162. outRVal.Pop(this, opcode); // pop into result
  5163. return outRVal; // tell caller where we put it
  5164. }
  5165. throw new Exception("unhandled opcode " + opcode.ToString());
  5166. }
  5167. /**
  5168. * @brief This is called while trying to compute the value of constant initializers.
  5169. * It is passed a name and that name is looked up in the constant tables.
  5170. */
  5171. private TokenRVal LookupInitConstants(TokenRVal rVal, ref bool didOne)
  5172. {
  5173. // If it is a static field of a script-defined type, look it up and hopefully we find a constant there.
  5174. TokenDeclVar gblVar;
  5175. if (rVal is TokenLValSField lvsf)
  5176. {
  5177. if (lvsf.baseType is TokenTypeSDTypeClass basetypeclass)
  5178. {
  5179. TokenDeclSDTypeClass sdtClass = basetypeclass.decl;
  5180. gblVar = sdtClass.members.FindExact(lvsf.fieldName.val, null);
  5181. if (gblVar != null)
  5182. {
  5183. if (gblVar.constant && (gblVar.init is TokenRValConst))
  5184. {
  5185. didOne = true;
  5186. return gblVar.init;
  5187. }
  5188. }
  5189. }
  5190. return rVal;
  5191. }
  5192. // Only other thing we handle is stand-alone names.
  5193. if (rVal is not TokenLValName)
  5194. return rVal;
  5195. string name = ((TokenLValName)rVal).name.val;
  5196. // If we are doing the initializations for a script-defined type,
  5197. // look for the constant among the fields for that type.
  5198. if(currentSDTClass != null)
  5199. {
  5200. gblVar = currentSDTClass.members.FindExact(name, null);
  5201. if(gblVar != null)
  5202. {
  5203. if(gblVar.constant && (gblVar.init is TokenRValConst))
  5204. {
  5205. didOne = true;
  5206. return gblVar.init;
  5207. }
  5208. return rVal;
  5209. }
  5210. }
  5211. // Look it up as a script-defined global variable.
  5212. // Then if the variable is defined as a constant and has a constant value,
  5213. // we are successful. If it is defined as something else, return failure.
  5214. gblVar = tokenScript.variablesStack.FindExact(name, null);
  5215. if(gblVar != null)
  5216. {
  5217. if(gblVar.constant && (gblVar.init is TokenRValConst))
  5218. {
  5219. didOne = true;
  5220. return gblVar.init;
  5221. }
  5222. return rVal;
  5223. }
  5224. // Maybe it is a built-in symbolic constant.
  5225. ScriptConst scriptConst = ScriptConst.Lookup(name);
  5226. if(scriptConst != null)
  5227. {
  5228. rVal = CompValuConst2RValConst(scriptConst.rVal, rVal);
  5229. if(rVal is TokenRValConst)
  5230. {
  5231. didOne = true;
  5232. return rVal;
  5233. }
  5234. }
  5235. // Don't know what it is, return failure.
  5236. return rVal;
  5237. }
  5238. /**
  5239. * @brief This is called while trying to compute the value of constant expressions.
  5240. * It is passed a name and that name is looked up in the constant tables.
  5241. */
  5242. private TokenRVal LookupBodyConstants(TokenRVal rVal, ref bool didOne)
  5243. {
  5244. // If it is a static field of a script-defined type, look it up and hopefully we find a constant there.
  5245. TokenDeclVar gblVar;
  5246. if(rVal is TokenLValSField lvsf)
  5247. {
  5248. if(lvsf.baseType is TokenTypeSDTypeClass TokenTypeSDTypeClasslvsfbaseType)
  5249. {
  5250. TokenDeclSDTypeClass sdtClass = TokenTypeSDTypeClasslvsfbaseType.decl;
  5251. gblVar = sdtClass.members.FindExact(lvsf.fieldName.val, null);
  5252. if((gblVar != null) && gblVar.constant && (gblVar.init is TokenRValConst))
  5253. {
  5254. didOne = true;
  5255. return gblVar.init;
  5256. }
  5257. }
  5258. return rVal;
  5259. }
  5260. // Only other thing we handle is stand-alone names.
  5261. if(rVal is not TokenLValName)
  5262. return rVal;
  5263. string name = ((TokenLValName)rVal).name.val;
  5264. // Scan through the variable stack and hopefully we find a constant there.
  5265. // But we stop as soon as we get a match because that's what the script is referring to.
  5266. CompValu val;
  5267. for(VarDict vars = ((TokenLValName)rVal).stack; vars != null; vars = vars.outerVarDict)
  5268. {
  5269. TokenDeclVar var = vars.FindExact(name, null);
  5270. if(var != null)
  5271. {
  5272. val = var.location;
  5273. goto foundit;
  5274. }
  5275. TokenDeclSDTypeClass baseClass = vars.thisClass;
  5276. if(baseClass != null)
  5277. {
  5278. while((baseClass = baseClass.extends) != null)
  5279. {
  5280. var = baseClass.members.FindExact(name, null);
  5281. if(var != null)
  5282. {
  5283. val = var.location;
  5284. goto foundit;
  5285. }
  5286. }
  5287. }
  5288. }
  5289. // Maybe it is a built-in symbolic constant.
  5290. ScriptConst scriptConst = ScriptConst.Lookup(name);
  5291. if(scriptConst != null)
  5292. {
  5293. val = scriptConst.rVal;
  5294. goto foundit;
  5295. }
  5296. // Don't know what it is, return failure.
  5297. return rVal;
  5298. // Found a CompValu. If it's a simple constant, then use it.
  5299. // Otherwise tell caller we failed to simplify.
  5300. foundit:
  5301. rVal = CompValuConst2RValConst(val, rVal);
  5302. if(rVal is TokenRValConst)
  5303. {
  5304. didOne = true;
  5305. }
  5306. return rVal;
  5307. }
  5308. private static TokenRVal CompValuConst2RValConst(CompValu val, TokenRVal rVal)
  5309. {
  5310. if(val is CompValuChar CompValuCharval)
  5311. rVal = new TokenRValConst(rVal, CompValuCharval.x);
  5312. if(val is CompValuFloat CompValuFloatval)
  5313. rVal = new TokenRValConst(rVal, CompValuFloatval.x);
  5314. if(val is CompValuInteger CompValuIntegerval)
  5315. rVal = new TokenRValConst(rVal, CompValuIntegerval.x);
  5316. if(val is CompValuString CompValuStringval)
  5317. rVal = new TokenRValConst(rVal, CompValuStringval.x);
  5318. return rVal;
  5319. }
  5320. /**
  5321. * @brief Generate code to push XMRInstanceSuperType pointer on stack.
  5322. */
  5323. public void PushXMRInst()
  5324. {
  5325. if(instancePointer == null)
  5326. {
  5327. ilGen.Emit(null, OpCodes.Ldarg_0);
  5328. }
  5329. else
  5330. {
  5331. ilGen.Emit(null, OpCodes.Ldloc, instancePointer);
  5332. }
  5333. }
  5334. /**
  5335. * @returns true: Ldarg_0 gives XMRSDTypeClObj pointer
  5336. * - this is the case for instance methods
  5337. * false: Ldarg_0 gives XMR_Instance pointer
  5338. * - this is the case for both global functions and static methods
  5339. */
  5340. public bool IsSDTInstMethod()
  5341. {
  5342. return (curDeclFunc.sdtClass != null) &&
  5343. ((curDeclFunc.sdtFlags & ScriptReduce.SDT_STATIC) == 0);
  5344. }
  5345. /**
  5346. * @brief Look for a simply named function or variable (not a field or method)
  5347. */
  5348. public TokenDeclVar FindNamedVar(TokenLValName lValName, TokenType[] argsig)
  5349. {
  5350. // Look in variable stack for the given name.
  5351. for(VarDict vars = lValName.stack; vars != null; vars = vars.outerVarDict)
  5352. {
  5353. // first look for it possibly with an argument signature
  5354. // so we pick the correct overloaded method
  5355. TokenDeclVar var = FindSingleMember(vars, lValName.name, argsig);
  5356. if(var != null)
  5357. return var;
  5358. // if that fails, try it without the argument signature.
  5359. // delegates get entered like any other variable, ie,
  5360. // no signature on their name.
  5361. if(argsig != null)
  5362. {
  5363. var = FindSingleMember(vars, lValName.name, null);
  5364. if(var != null)
  5365. return var;
  5366. }
  5367. // if this is the frame for some class members, try searching base class members too
  5368. TokenDeclSDTypeClass baseClass = vars.thisClass;
  5369. if(baseClass != null)
  5370. {
  5371. while((baseClass = baseClass.extends) != null)
  5372. {
  5373. var = FindSingleMember(baseClass.members, lValName.name, argsig);
  5374. if(var != null)
  5375. return var;
  5376. if(argsig != null)
  5377. {
  5378. var = FindSingleMember(baseClass.members, lValName.name, null);
  5379. if(var != null)
  5380. return var;
  5381. }
  5382. }
  5383. }
  5384. }
  5385. // If not found, try one of the built-in constants or functions.
  5386. if(argsig == null)
  5387. {
  5388. ScriptConst scriptConst = ScriptConst.Lookup(lValName.name.val);
  5389. if(scriptConst != null)
  5390. {
  5391. TokenDeclVar var = new (lValName.name, null, tokenScript)
  5392. {
  5393. name = lValName.name,
  5394. type = scriptConst.rVal.type,
  5395. location = scriptConst.rVal
  5396. };
  5397. return var;
  5398. }
  5399. }
  5400. else
  5401. {
  5402. TokenDeclVar inline = FindSingleMember(TokenDeclInline.inlineFunctions, lValName.name, argsig);
  5403. if(inline != null)
  5404. return inline;
  5405. }
  5406. return null;
  5407. }
  5408. /**
  5409. * @brief Find a member of an interface.
  5410. * @param sdType = interface type
  5411. * @param name = name of member to find
  5412. * @param argsig = null: field/property; else: script-visible method argument types
  5413. * @param baseRVal = pointer to interface object
  5414. * @returns null: no such member
  5415. * else: pointer to member
  5416. * baseRVal = possibly modified to point to type-casted interface object
  5417. */
  5418. private TokenDeclVar FindInterfaceMember(TokenTypeSDTypeInterface sdtType, TokenName name, TokenType[] argsig, ref CompValu baseRVal)
  5419. {
  5420. TokenDeclSDTypeInterface sdtDecl = sdtType.decl;
  5421. TokenDeclVar declVar = sdtDecl.FindIFaceMember(this, name, argsig, out TokenDeclSDTypeInterface impl);
  5422. if ((declVar != null) && (impl != sdtDecl))
  5423. {
  5424. // Accessing a method or propterty of another interface that the primary interface says it implements.
  5425. // In this case, we have to cast from the primary interface to that secondary interface.
  5426. //
  5427. // interface IEnumerable {
  5428. // IEnumerator GetEnumerator ();
  5429. // }
  5430. // interface ICountable : IEnumerable {
  5431. // integer GetCount ();
  5432. // }
  5433. // class List : ICountable {
  5434. // public GetCount () : ICountable { ... }
  5435. // public GetEnumerator () : IEnumerable { ... }
  5436. // }
  5437. //
  5438. // ICountable aList = new List ();
  5439. // IEnumerator anEnumer = aList.GetEnumerator (); << we are here
  5440. // << baseRVal = aList
  5441. // << sdtDecl = ICountable
  5442. // << impl = IEnumerable
  5443. // << name = GetEnumerator
  5444. // << argsig = ()
  5445. // So we have to cast aList from ICountable to IEnumerable.
  5446. // make type token for the secondary interface type
  5447. TokenType subIntfType = impl.MakeRefToken(name);
  5448. // make a temp variable of the secondary interface type
  5449. CompValuTemp castBase = new (subIntfType, this);
  5450. // output code to cast from the primary interface to the secondary interface
  5451. // this is 2 basic steps:
  5452. // 1) cast from primary interface object -> class object
  5453. // ...gets it from interfaceObject.delegateArray[0].Target
  5454. // 2) cast from class object -> secondary interface object
  5455. // ...gets it from classObject.sdtcITable[interfaceIndex]
  5456. baseRVal.PushVal(this, name, subIntfType);
  5457. // save result of casting in temp
  5458. castBase.Pop(this, name);
  5459. // return temp reference
  5460. baseRVal = castBase;
  5461. }
  5462. return declVar;
  5463. }
  5464. /**
  5465. * @brief Find a member of a script-defined type class.
  5466. * @param sdtType = reference to class declaration
  5467. * @param name = name of member to find
  5468. * @param argsig = argument signature used to select among overloaded members
  5469. * @returns null: no such member found
  5470. * else: the member found
  5471. */
  5472. public TokenDeclVar FindThisMember(TokenTypeSDTypeClass sdtType, TokenName name, TokenType[] argsig)
  5473. {
  5474. return FindThisMember(sdtType.decl, name, argsig);
  5475. }
  5476. public TokenDeclVar FindThisMember(TokenDeclSDTypeClass sdtDecl, TokenName name, TokenType[] argsig)
  5477. {
  5478. for(TokenDeclSDTypeClass sdtd = sdtDecl; sdtd != null; sdtd = sdtd.extends)
  5479. {
  5480. TokenDeclVar declVar = FindSingleMember(sdtd.members, name, argsig);
  5481. if(declVar != null)
  5482. return declVar;
  5483. }
  5484. return null;
  5485. }
  5486. /**
  5487. * @brief Look for a single member that matches the given name and argument signature
  5488. * @param where = which dictionary to look in
  5489. * @param name = basic name of the field or method, eg, "Printable"
  5490. * @param argsig = argument types the method is being called with, eg, "(string)"
  5491. * or null to find a field
  5492. * @returns null: no member found
  5493. * else: the member found
  5494. */
  5495. public TokenDeclVar FindSingleMember(VarDict where, TokenName name, TokenType[] argsig)
  5496. {
  5497. TokenDeclVar[] members = where.FindCallables(name.val, argsig);
  5498. if(members == null)
  5499. return null;
  5500. if(members.Length > 1)
  5501. {
  5502. ErrorMsg(name, "more than one matching member");
  5503. for(int i = 0; i < members.Length; i++)
  5504. {
  5505. ErrorMsg(members[i], " " + members[i].argDecl.GetArgSig());
  5506. }
  5507. }
  5508. return members[0];
  5509. }
  5510. /**
  5511. * @brief Find an exact function name and argument signature match.
  5512. * Also verify that the return value type is an exact match.
  5513. * @param where = which method dictionary to look in
  5514. * @param name = basic name of the method, eg, "Printable"
  5515. * @param ret = expected return value type
  5516. * @param argsig = argument types the method is being called with, eg, "(string)"
  5517. * @returns null: no exact match found
  5518. * else: the matching function
  5519. */
  5520. private TokenDeclVar FindExactWithRet(VarDict where, TokenName name, TokenType ret, TokenType[] argsig)
  5521. {
  5522. TokenDeclVar func = where.FindExact(name.val, argsig);
  5523. if((func != null) && (func.retType.ToString() != ret.ToString()))
  5524. {
  5525. ErrorMsg(name, "return type mismatch, have " + func.retType.ToString() + ", expect " + ret.ToString());
  5526. }
  5527. if(func != null)
  5528. CheckAccess(func, name);
  5529. return func;
  5530. }
  5531. /**
  5532. * @brief Check the private/protected/public access flags of a member.
  5533. */
  5534. private void CheckAccess(TokenDeclVar var, Token errorAt)
  5535. {
  5536. TokenDeclSDType nested;
  5537. TokenDeclSDType definedBy = var.sdtClass;
  5538. TokenDeclSDType accessedBy = curDeclFunc.sdtClass;
  5539. //*******************************
  5540. // Check member-level access
  5541. //*******************************
  5542. // Note that if accessedBy is null, ie, accessing from global function (or event handlers),
  5543. // anything tagged as SDT_PRIVATE or SDT_PROTECTED will fail.
  5544. // Private means accessed by the class that defined the member or accessed by a nested class
  5545. // of the class that defined the member.
  5546. if((var.sdtFlags & ScriptReduce.SDT_PRIVATE) != 0)
  5547. {
  5548. for(nested = accessedBy; nested != null; nested = nested.outerSDType)
  5549. {
  5550. if(nested == definedBy)
  5551. goto acc1ok;
  5552. }
  5553. ErrorMsg(errorAt, "private member " + var.fullName + " cannot be accessed by " + curDeclFunc.fullName);
  5554. return;
  5555. }
  5556. // Protected means:
  5557. // If being accessed by an inner class, the inner class has access to it if the inner class derives
  5558. // from the declaring class. It also has access to it if an outer class derives from the declaring
  5559. // class.
  5560. if((var.sdtFlags & ScriptReduce.SDT_PROTECTED) != 0)
  5561. {
  5562. for(nested = accessedBy; nested != null; nested = nested.outerSDType)
  5563. {
  5564. for(TokenDeclSDType rootward = nested; rootward != null; rootward = rootward.extends)
  5565. {
  5566. if(rootward == definedBy)
  5567. goto acc1ok;
  5568. }
  5569. }
  5570. ErrorMsg(errorAt, "protected member " + var.fullName + " cannot be accessed by " + curDeclFunc.fullName);
  5571. return;
  5572. }
  5573. acc1ok:
  5574. //******************************
  5575. // Check class-level access
  5576. //******************************
  5577. // If being accessed by same or inner class than where defined, it is ok.
  5578. //
  5579. // class DefiningClass {
  5580. // varBeingAccessed;
  5581. // .
  5582. // .
  5583. // .
  5584. // class AccessingClass {
  5585. // functionDoingAccess() { }
  5586. // }
  5587. // .
  5588. // .
  5589. // .
  5590. // }
  5591. nested = accessedBy;
  5592. while(true)
  5593. {
  5594. if(nested == definedBy)
  5595. return;
  5596. if(nested == null)
  5597. break;
  5598. nested = (TokenDeclSDTypeClass)nested.outerSDType;
  5599. }
  5600. // It is being accessed by an outer class than where defined,
  5601. // check for a 'private' or 'protected' class tag that blocks.
  5602. do
  5603. {
  5604. // If the field's class is defined directly inside the accessing class,
  5605. // access is allowed regardless of class-level private or protected tags.
  5606. //
  5607. // class AccessingClass {
  5608. // functionDoingAccess() { }
  5609. // class DefiningClass {
  5610. // varBeingAccessed;
  5611. // }
  5612. // }
  5613. if(definedBy.outerSDType == accessedBy)
  5614. return;
  5615. // If the field's class is defined two or more levels inside the accessing class,
  5616. // access is denied if the defining class is tagged private.
  5617. //
  5618. // class AccessingClass {
  5619. // functionDoingAccess() { }
  5620. // .
  5621. // .
  5622. // .
  5623. // class IntermediateClass {
  5624. // private class DefiningClass {
  5625. // varBeingAccessed;
  5626. // }
  5627. // }
  5628. // .
  5629. // .
  5630. // .
  5631. // }
  5632. if((definedBy.accessLevel & ScriptReduce.SDT_PRIVATE) != 0)
  5633. {
  5634. ErrorMsg(errorAt, "member " + var.fullName + " cannot be accessed by " + curDeclFunc.fullName +
  5635. " because of private class " + definedBy.longName.val);
  5636. return;
  5637. }
  5638. // Likewise, if DefiningClass is tagged protected, the AccessingClass must derive from the
  5639. // IntermediateClass or access is denied.
  5640. if((definedBy.accessLevel & ScriptReduce.SDT_PROTECTED) != 0)
  5641. {
  5642. for(TokenDeclSDType extends = accessedBy; extends != definedBy.outerSDType; extends = extends.extends)
  5643. {
  5644. if(extends == null)
  5645. {
  5646. ErrorMsg(errorAt, "member " + var.fullName + " cannot be accessed by " + curDeclFunc.fullName +
  5647. " because of protected class " + definedBy.longName.val);
  5648. return;
  5649. }
  5650. }
  5651. }
  5652. // Check next outer level.
  5653. definedBy = definedBy.outerSDType;
  5654. } while(definedBy != null);
  5655. }
  5656. /**
  5657. * @brief Convert a list of argument types to printable string, eg, "(list,string,float,integer)"
  5658. * If given a null, return "" indicating it is a field not a method
  5659. */
  5660. public static string ArgSigString(TokenType[] argsig)
  5661. {
  5662. if(argsig == null)
  5663. return string.Empty;
  5664. if(argsig.Length == 0)
  5665. return "()";
  5666. StringBuilder sb = new ();
  5667. sb.Append('(');
  5668. for (int i = 0; i < argsig.Length; i++)
  5669. {
  5670. if(i > 0)
  5671. sb.Append(',');
  5672. sb.Append(argsig[i].ToString());
  5673. }
  5674. sb.Append(')');
  5675. return sb.ToString();
  5676. }
  5677. /**
  5678. * @brief output error message and remember that we did
  5679. */
  5680. public void ErrorMsg(Token token, string message)
  5681. {
  5682. if((token == null) || (token.emsg == null))
  5683. token = errorMessageToken;
  5684. if(!youveAnError || (token.file != lastErrorFile) || (token.line > lastErrorLine))
  5685. {
  5686. token.ErrorMsg(message);
  5687. youveAnError = true;
  5688. lastErrorFile = token.file;
  5689. lastErrorLine = token.line;
  5690. }
  5691. }
  5692. /**
  5693. * @brief Find a private static method.
  5694. * @param owner = class the method is part of
  5695. * @param name = name of method to find
  5696. * @param args = array of argument types
  5697. * @returns pointer to method
  5698. */
  5699. public static MethodInfo GetStaticMethod(Type owner, string name, Type[] args)
  5700. {
  5701. return owner.GetMethod(name, BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic, null, args, null) ??
  5702. throw new Exception("undefined method " + owner.ToString() + "." + name);
  5703. }
  5704. // http://wiki.secondlife.com/wiki/Rotation 'negate a rotation' says just negate .s component
  5705. // but http://wiki.secondlife.com/wiki/LSL_Language_Test (lslangtest1.lsl) says negate all 4 values
  5706. public static LSL_Rotation LSLRotationNegate(LSL_Rotation r)
  5707. {
  5708. return new LSL_Rotation(-r.x, -r.y, -r.z, -r.s);
  5709. }
  5710. public static LSL_Vector LSLVectorNegate(LSL_Vector v)
  5711. {
  5712. return -v;
  5713. }
  5714. public static string CatchExcToStr(Exception exc)
  5715. {
  5716. return exc.ToString();
  5717. }
  5718. //public static void ConsoleWrite (string str) { Console.Write(str); }
  5719. /**
  5720. * @brief Defines an internal label that is used as a target for 'break' and 'continue' statements.
  5721. */
  5722. private class BreakContTarg
  5723. {
  5724. public bool used;
  5725. public ScriptMyLabel label;
  5726. public TokenStmtBlock block;
  5727. public BreakContTarg(ScriptCodeGen scg, string name)
  5728. {
  5729. used = false; // assume it isn't referenced at all
  5730. label = scg.ilGen.DefineLabel(name); // label that the break/continue jumps to
  5731. block = scg.curStmtBlock; // { ... } that the break/continue label is in
  5732. }
  5733. }
  5734. }
  5735. /**
  5736. * @brief Marker interface indicates an exception that can't be caught by a script-level try/catch.
  5737. */
  5738. public interface IXMRUncatchable
  5739. {
  5740. }
  5741. /**
  5742. * @brief Thrown by a script when it attempts to change to an undefined state.
  5743. * These can be detected at compile time but the moron XEngine compiles
  5744. * such things, so we compile them as runtime errors.
  5745. */
  5746. [SerializableAttribute]
  5747. public class ScriptUndefinedStateException: Exception, ISerializable
  5748. {
  5749. public string stateName;
  5750. public ScriptUndefinedStateException(string stateName) : base("undefined state " + stateName)
  5751. {
  5752. this.stateName = stateName;
  5753. }
  5754. }
  5755. /**
  5756. * @brief Created by a throw statement.
  5757. */
  5758. [SerializableAttribute]
  5759. public class ScriptThrownException: Exception, ISerializable
  5760. {
  5761. public object thrown;
  5762. /**
  5763. * @brief Called by a throw statement to wrap the object in a unique
  5764. * tag that capable of capturing a stack trace. Script can
  5765. * unwrap it by calling xmrExceptionThrownValue().
  5766. */
  5767. public static Exception Wrap(object thrown)
  5768. {
  5769. return new ScriptThrownException(thrown);
  5770. }
  5771. private ScriptThrownException(object thrown) : base(thrown.ToString())
  5772. {
  5773. this.thrown = thrown;
  5774. }
  5775. }
  5776. /**
  5777. * @brief Thrown by a script when it attempts to change to a defined state.
  5778. */
  5779. [SerializableAttribute]
  5780. public class ScriptChangeStateException: Exception, ISerializable, IXMRUncatchable
  5781. {
  5782. public int newState;
  5783. public ScriptChangeStateException(int newState)
  5784. {
  5785. this.newState = newState;
  5786. }
  5787. }
  5788. /**
  5789. * @brief We are restoring to the body of a catch { } so we need to
  5790. * wrap the original exception in an outer exception, so the
  5791. * system won't try to refill the stack trace.
  5792. *
  5793. * We don't mark this one serializable as it should never get
  5794. * serialized out. It only lives from the throw to the very
  5795. * beginning of the catch handler where it is promptly unwrapped.
  5796. * No CheckRun() call can possibly intervene.
  5797. */
  5798. public class ScriptRestoreCatchException: Exception
  5799. {
  5800. // old code uses these
  5801. private readonly object e;
  5802. public ScriptRestoreCatchException(object e)
  5803. {
  5804. this.e = e;
  5805. }
  5806. public static object Unwrap(object o)
  5807. {
  5808. if(o is IXMRUncatchable)
  5809. return null;
  5810. if(o is ScriptRestoreCatchException oe)
  5811. return oe.e;
  5812. return o;
  5813. }
  5814. // new code uses these
  5815. private readonly Exception ee;
  5816. public ScriptRestoreCatchException(Exception ee)
  5817. {
  5818. this.ee = ee;
  5819. }
  5820. public static Exception Unwrap(Exception oo)
  5821. {
  5822. if(oo is IXMRUncatchable)
  5823. return null;
  5824. if(oo is ScriptRestoreCatchException ooe)
  5825. return ooe.ee;
  5826. return oo;
  5827. }
  5828. }
  5829. [SerializableAttribute]
  5830. public class ScriptBadCallNoException: Exception
  5831. {
  5832. public ScriptBadCallNoException(int callNo) : base("bad callNo " + callNo) { }
  5833. }
  5834. public class CVVMismatchException: Exception
  5835. {
  5836. public CVVMismatchException(string msg) : base(msg)
  5837. {
  5838. }
  5839. }
  5840. }