1
0

MMRScriptCodeGen.cs 281 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409
  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. ilGen.Emit(stateStmt, OpCodes.Ldc_I4, index); // new state's index
  2298. ilGen.Emit(stateStmt, OpCodes.Newobj, scriptChangeStateExceptionConstructorInfo);
  2299. }
  2300. ilGen.Emit(stateStmt, OpCodes.Throw);
  2301. // 'state' statements never fall through.
  2302. mightGetHere = false;
  2303. }
  2304. /**
  2305. * @brief output code for a 'switch' statement
  2306. */
  2307. private void GenerateStmtSwitch(TokenStmtSwitch switchStmt)
  2308. {
  2309. if(!mightGetHere)
  2310. return;
  2311. // Output code to calculate index.
  2312. CompValu testRVal = GenerateFromRVal(switchStmt.testRVal);
  2313. // Generate code based on string or integer index.
  2314. if((testRVal.type is TokenTypeKey) || (testRVal.type is TokenTypeStr))
  2315. GenerateStmtSwitchStr(testRVal, switchStmt);
  2316. else
  2317. GenerateStmtSwitchInt(testRVal, switchStmt);
  2318. }
  2319. private void GenerateStmtSwitchInt(CompValu testRVal, TokenStmtSwitch switchStmt)
  2320. {
  2321. testRVal.PushVal(this, switchStmt.testRVal, tokenTypeInt);
  2322. BreakContTarg oldBreakTarg = curBreakTarg;
  2323. ScriptMyLabel defaultLabel = null;
  2324. TokenSwitchCase sortedCases = null;
  2325. TokenSwitchCase defaultCase = null;
  2326. curBreakTarg = new BreakContTarg(this, "switchbreak_" + switchStmt.Unique);
  2327. // Build list of cases sorted by ascending values.
  2328. // There should not be any overlapping of values.
  2329. for(TokenSwitchCase thisCase = switchStmt.cases; thisCase != null; thisCase = thisCase.nextCase)
  2330. {
  2331. thisCase.label = ilGen.DefineLabel("case_" + thisCase.Unique);
  2332. // The default case if any, goes in its own separate slot.
  2333. if(thisCase.rVal1 == null)
  2334. {
  2335. if(defaultCase != null)
  2336. {
  2337. ErrorMsg(thisCase, "only one default case allowed");
  2338. ErrorMsg(defaultCase, "...prior default case");
  2339. return;
  2340. }
  2341. defaultCase = thisCase;
  2342. defaultLabel = thisCase.label;
  2343. continue;
  2344. }
  2345. // Evaluate case operands, they must be compile-time integer constants.
  2346. CompValu rVal = GenerateFromRVal(thisCase.rVal1);
  2347. if(!IsConstIntExpr(rVal, out thisCase.val1))
  2348. {
  2349. ErrorMsg(thisCase.rVal1, "must be compile-time char or integer constant");
  2350. return;
  2351. }
  2352. thisCase.val2 = thisCase.val1;
  2353. if(thisCase.rVal2 != null)
  2354. {
  2355. rVal = GenerateFromRVal(thisCase.rVal2);
  2356. if(!IsConstIntExpr(rVal, out thisCase.val2))
  2357. {
  2358. ErrorMsg(thisCase.rVal2, "must be compile-time char or integer constant");
  2359. return;
  2360. }
  2361. }
  2362. if(thisCase.val2 < thisCase.val1)
  2363. {
  2364. ErrorMsg(thisCase.rVal2, "must be .ge. first value for the case");
  2365. return;
  2366. }
  2367. // Insert into list, sorted by value.
  2368. // Note that both limits are inclusive.
  2369. TokenSwitchCase lastCase = null;
  2370. TokenSwitchCase nextCase;
  2371. for(nextCase = sortedCases; nextCase != null; nextCase = nextCase.nextSortedCase)
  2372. {
  2373. if(nextCase.val1 > thisCase.val2)
  2374. break;
  2375. if(nextCase.val2 >= thisCase.val1)
  2376. {
  2377. ErrorMsg(thisCase, "value used by previous case");
  2378. ErrorMsg(nextCase, "...previous case");
  2379. return;
  2380. }
  2381. lastCase = nextCase;
  2382. }
  2383. thisCase.nextSortedCase = nextCase;
  2384. if(lastCase == null)
  2385. {
  2386. sortedCases = thisCase;
  2387. }
  2388. else
  2389. {
  2390. lastCase.nextSortedCase = thisCase;
  2391. }
  2392. }
  2393. defaultLabel ??= ilGen.DefineLabel("default_" + switchStmt.Unique);
  2394. // Output code to jump to the case statement's labels based on integer index on stack.
  2395. // Note that each case still has the integer index on stack when jumped to.
  2396. int offset = 0;
  2397. for(TokenSwitchCase thisCase = sortedCases; thisCase != null;)
  2398. {
  2399. // Scan through list of cases to find the maximum number of cases who's numvalues-to-case ratio
  2400. // is from 0.5 to 2.0. If such a group is found, use a CIL switch for them. If not, just use a
  2401. // compare-and-branch for the current case.
  2402. int numCases = 0;
  2403. int numFound = 0;
  2404. int lowValue = thisCase.val1;
  2405. int numValues = 0;
  2406. for(TokenSwitchCase scanCase = thisCase; scanCase != null; scanCase = scanCase.nextSortedCase)
  2407. {
  2408. int nVals = scanCase.val2 - thisCase.val1 + 1;
  2409. double ratio = (double)nVals / (double)(++numCases);
  2410. if((ratio >= 0.5) && (ratio <= 2.0))
  2411. {
  2412. numFound = numCases;
  2413. numValues = nVals;
  2414. }
  2415. }
  2416. if(numFound > 1)
  2417. {
  2418. // There is a group of case's, starting with thisCase, that fall within our criteria, ie,
  2419. // that have a nice density of meaningful jumps.
  2420. //
  2421. // So first generate an array of jumps to the default label (explicit or implicit).
  2422. ScriptMyLabel[] labels = new ScriptMyLabel[numValues];
  2423. for(int i = 0; i < numValues; i++)
  2424. {
  2425. labels[i] = defaultLabel;
  2426. }
  2427. // Next, for each case in that group, fill in the corresponding array entries to jump to
  2428. // that case's label.
  2429. do
  2430. {
  2431. for(int i = thisCase.val1; i <= thisCase.val2; i++)
  2432. {
  2433. labels[i - lowValue] = thisCase.label;
  2434. }
  2435. thisCase = thisCase.nextSortedCase;
  2436. } while(--numFound > 0);
  2437. // Subtract the low value and do the computed jump.
  2438. // The OpCodes.Switch falls through if out of range (unsigned compare).
  2439. if(offset != lowValue)
  2440. {
  2441. ilGen.Emit(switchStmt, OpCodes.Ldc_I4, lowValue - offset);
  2442. ilGen.Emit(switchStmt, OpCodes.Sub);
  2443. offset = lowValue;
  2444. }
  2445. ilGen.Emit(switchStmt, OpCodes.Dup);
  2446. ilGen.Emit(switchStmt, OpCodes.Switch, labels);
  2447. }
  2448. else
  2449. {
  2450. // It's not economical to do with a computed jump, so output a subtract/compare/branch
  2451. // for thisCase.
  2452. if(lowValue == thisCase.val2)
  2453. {
  2454. ilGen.Emit(switchStmt, OpCodes.Dup);
  2455. ilGen.Emit(switchStmt, OpCodes.Ldc_I4, lowValue - offset);
  2456. ilGen.Emit(switchStmt, OpCodes.Beq, thisCase.label);
  2457. }
  2458. else
  2459. {
  2460. if(offset != lowValue)
  2461. {
  2462. ilGen.Emit(switchStmt, OpCodes.Ldc_I4, lowValue - offset);
  2463. ilGen.Emit(switchStmt, OpCodes.Sub);
  2464. offset = lowValue;
  2465. }
  2466. ilGen.Emit(switchStmt, OpCodes.Dup);
  2467. ilGen.Emit(switchStmt, OpCodes.Ldc_I4, thisCase.val2 - offset);
  2468. ilGen.Emit(switchStmt, OpCodes.Ble_Un, thisCase.label);
  2469. }
  2470. thisCase = thisCase.nextSortedCase;
  2471. }
  2472. }
  2473. ilGen.Emit(switchStmt, OpCodes.Br, defaultLabel);
  2474. // Output code for the cases themselves, in the order given by the programmer,
  2475. // so they fall through as programmer wants. This includes the default case, if any.
  2476. //
  2477. // Each label is jumped to with the index still on the stack. So pop it off in case
  2478. // the case body does a goto outside the switch or a return. If the case body might
  2479. // fall through to the next case or the bottom of the switch, push a zero so the stack
  2480. // matches in all cases.
  2481. for(TokenSwitchCase thisCase = switchStmt.cases; thisCase != null; thisCase = thisCase.nextCase)
  2482. {
  2483. ilGen.MarkLabel(thisCase.label); // the branch comes here
  2484. ilGen.Emit(thisCase, OpCodes.Pop); // pop the integer index off stack
  2485. mightGetHere = true; // it's possible to get here
  2486. for(TokenStmt stmt = thisCase.stmts; stmt != null; stmt = (TokenStmt)(stmt.nextToken))
  2487. {
  2488. GenerateStmt(stmt); // output the case/explicit default body
  2489. }
  2490. if(mightGetHere)
  2491. {
  2492. ilGen.Emit(thisCase, OpCodes.Ldc_I4_0);
  2493. // in case we fall through, push a dummy integer index
  2494. }
  2495. }
  2496. // If no explicit default case, output the default label here.
  2497. if(defaultCase == null)
  2498. {
  2499. ilGen.MarkLabel(defaultLabel);
  2500. mightGetHere = true;
  2501. }
  2502. // If the last case of the switch falls through out the bottom,
  2503. // we have to pop the index still on the stack.
  2504. if(mightGetHere)
  2505. {
  2506. ilGen.Emit(switchStmt, OpCodes.Pop);
  2507. }
  2508. // Output the 'break' statement target label.
  2509. // Note that the integer index is not on the stack at this point.
  2510. if(curBreakTarg.used)
  2511. {
  2512. ilGen.MarkLabel(curBreakTarg.label);
  2513. mightGetHere = true;
  2514. }
  2515. curBreakTarg = oldBreakTarg;
  2516. }
  2517. private void GenerateStmtSwitchStr(CompValu testRVal, TokenStmtSwitch switchStmt)
  2518. {
  2519. BreakContTarg oldBreakTarg = curBreakTarg;
  2520. ScriptMyLabel defaultLabel = null;
  2521. TokenSwitchCase caseTreeTop = null;
  2522. TokenSwitchCase defaultCase = null;
  2523. curBreakTarg = new BreakContTarg(this, "switchbreak_" + switchStmt.Unique);
  2524. // Make sure value is in a temp so we don't compute it more than once.
  2525. if(testRVal is not CompValuTemp)
  2526. {
  2527. CompValuTemp temp = new (testRVal.type, this);
  2528. testRVal.PushVal(this, switchStmt);
  2529. temp.Pop(this, switchStmt);
  2530. testRVal = temp;
  2531. }
  2532. // Build tree of cases.
  2533. // There should not be any overlapping of values.
  2534. for(TokenSwitchCase thisCase = switchStmt.cases; thisCase != null; thisCase = thisCase.nextCase)
  2535. {
  2536. thisCase.label = ilGen.DefineLabel("case");
  2537. // The default case if any, goes in its own separate slot.
  2538. if(thisCase.rVal1 == null)
  2539. {
  2540. if(defaultCase != null)
  2541. {
  2542. ErrorMsg(thisCase, "only one default case allowed");
  2543. ErrorMsg(defaultCase, "...prior default case");
  2544. return;
  2545. }
  2546. defaultCase = thisCase;
  2547. defaultLabel = thisCase.label;
  2548. continue;
  2549. }
  2550. // Evaluate case operands, they must be compile-time string constants.
  2551. CompValu rVal = GenerateFromRVal(thisCase.rVal1);
  2552. if(!IsConstStrExpr(rVal, out thisCase.str1))
  2553. {
  2554. ErrorMsg(thisCase.rVal1, "must be compile-time string constant");
  2555. continue;
  2556. }
  2557. thisCase.str2 = thisCase.str1;
  2558. if(thisCase.rVal2 != null)
  2559. {
  2560. rVal = GenerateFromRVal(thisCase.rVal2);
  2561. if(!IsConstStrExpr(rVal, out thisCase.str2))
  2562. {
  2563. ErrorMsg(thisCase.rVal2, "must be compile-time string constant");
  2564. continue;
  2565. }
  2566. }
  2567. if(String.Compare(thisCase.str2, thisCase.str1, StringComparison.Ordinal) < 0)
  2568. {
  2569. ErrorMsg(thisCase.rVal2, "must be .ge. first value for the case");
  2570. continue;
  2571. }
  2572. // Insert into list, sorted by value.
  2573. // Note that both limits are inclusive.
  2574. caseTreeTop = InsertCaseInTree(caseTreeTop, thisCase);
  2575. }
  2576. // Balance tree so we end up generating code that does O(log2 n) comparisons.
  2577. caseTreeTop = BalanceTree(caseTreeTop);
  2578. // Output compare and branch instructions in a tree-like fashion so we do O(log2 n) comparisons.
  2579. defaultLabel ??= ilGen.DefineLabel("default");
  2580. OutputStrCase(testRVal, caseTreeTop, defaultLabel);
  2581. // Output code for the cases themselves, in the order given by the programmer,
  2582. // so they fall through as programmer wants. This includes the default case, if any.
  2583. for(TokenSwitchCase thisCase = switchStmt.cases; thisCase != null; thisCase = thisCase.nextCase)
  2584. {
  2585. ilGen.MarkLabel(thisCase.label); // the branch comes here
  2586. mightGetHere = true; // it's possible to get here
  2587. for(TokenStmt stmt = thisCase.stmts; stmt != null; stmt = (TokenStmt)(stmt.nextToken))
  2588. {
  2589. GenerateStmt(stmt); // output the case/explicit default body
  2590. }
  2591. }
  2592. // If no explicit default case, output the default label here.
  2593. if(defaultCase == null)
  2594. {
  2595. ilGen.MarkLabel(defaultLabel);
  2596. mightGetHere = true;
  2597. }
  2598. // Output the 'break' statement target label.
  2599. if(curBreakTarg.used)
  2600. {
  2601. ilGen.MarkLabel(curBreakTarg.label);
  2602. mightGetHere = true;
  2603. }
  2604. curBreakTarg = oldBreakTarg;
  2605. }
  2606. /**
  2607. * @brief Insert a case in a tree of cases
  2608. * @param r = root of existing cases to insert into
  2609. * @param n = new case being inserted
  2610. * @returns new root with new case inserted
  2611. */
  2612. private TokenSwitchCase InsertCaseInTree(TokenSwitchCase r, TokenSwitchCase n)
  2613. {
  2614. if(r == null)
  2615. return n;
  2616. TokenSwitchCase t = r;
  2617. while(true)
  2618. {
  2619. if(String.Compare(n.str2, t.str1, StringComparison.Ordinal) < 0)
  2620. {
  2621. if(t.lowerCase == null)
  2622. {
  2623. t.lowerCase = n;
  2624. break;
  2625. }
  2626. t = t.lowerCase;
  2627. continue;
  2628. }
  2629. if(String.Compare(n.str1, t.str2, StringComparison.Ordinal) > 0)
  2630. {
  2631. if(t.higherCase == null)
  2632. {
  2633. t.higherCase = n;
  2634. break;
  2635. }
  2636. t = t.higherCase;
  2637. continue;
  2638. }
  2639. ErrorMsg(n, "duplicate case");
  2640. ErrorMsg(r, "...duplicate of");
  2641. break;
  2642. }
  2643. return r;
  2644. }
  2645. /**
  2646. * @brief Balance a tree so left & right halves contain same number within +-1
  2647. * @param r = root of tree to balance
  2648. * @returns new root
  2649. */
  2650. private static TokenSwitchCase BalanceTree(TokenSwitchCase r)
  2651. {
  2652. if(r == null)
  2653. return r;
  2654. int lc = CountTree(r.lowerCase);
  2655. int hc = CountTree(r.higherCase);
  2656. TokenSwitchCase n, x;
  2657. // If lower side is heavy, move highest nodes from lower side to
  2658. // higher side until balanced.
  2659. while(lc > hc + 1)
  2660. {
  2661. x = ExtractHighest(r.lowerCase, out n);
  2662. n.lowerCase = x;
  2663. n.higherCase = r;
  2664. r.lowerCase = null;
  2665. r = n;
  2666. lc--;
  2667. hc++;
  2668. }
  2669. // If higher side is heavy, move lowest nodes from higher side to
  2670. // lower side until balanced.
  2671. while(hc > lc + 1)
  2672. {
  2673. x = ExtractLowest(r.higherCase, out n);
  2674. n.higherCase = x;
  2675. n.lowerCase = r;
  2676. r.higherCase = null;
  2677. r = n;
  2678. lc++;
  2679. hc--;
  2680. }
  2681. // Now balance each side because they can be lopsided individually.
  2682. r.lowerCase = BalanceTree(r.lowerCase);
  2683. r.higherCase = BalanceTree(r.higherCase);
  2684. return r;
  2685. }
  2686. /**
  2687. * @brief Get number of nodes in a tree
  2688. * @param n = root of tree to count
  2689. * @returns number of nodes including root
  2690. */
  2691. private static int CountTree(TokenSwitchCase n)
  2692. {
  2693. if(n == null)
  2694. return 0;
  2695. return 1 + CountTree(n.lowerCase) + CountTree(n.higherCase);
  2696. }
  2697. // Extract highest node from a tree
  2698. // @param r = root of tree to extract highest from
  2699. // @returns new root after node has been extracted
  2700. // n = node that was extracted from tree
  2701. private static TokenSwitchCase ExtractHighest(TokenSwitchCase r, out TokenSwitchCase n)
  2702. {
  2703. if(r.higherCase == null)
  2704. {
  2705. n = r;
  2706. return r.lowerCase;
  2707. }
  2708. r.higherCase = ExtractHighest(r.higherCase, out n);
  2709. return r;
  2710. }
  2711. // Extract lowest node from a tree
  2712. // @param r = root of tree to extract lowest from
  2713. // @returns new root after node has been extracted
  2714. // n = node that was extracted from tree
  2715. private static TokenSwitchCase ExtractLowest(TokenSwitchCase r, out TokenSwitchCase n)
  2716. {
  2717. if(r.lowerCase == null)
  2718. {
  2719. n = r;
  2720. return r.higherCase;
  2721. }
  2722. r.lowerCase = ExtractLowest(r.lowerCase, out n);
  2723. return r;
  2724. }
  2725. /**
  2726. * Output code for string-style case of a switch/case to jump to the script code associated with the case.
  2727. * @param testRVal = value being switched on
  2728. * @param thisCase = case that the code is being output for
  2729. * @param defaultLabel = where the default clause is (or past all cases if none)
  2730. * Note:
  2731. * Outputs code for this case and the lowerCase and higherCases if any.
  2732. * If no lowerCase or higherCase, outputs a br to defaultLabel so this code never falls through.
  2733. */
  2734. private void OutputStrCase(CompValu testRVal, TokenSwitchCase thisCase, ScriptMyLabel defaultLabel)
  2735. {
  2736. // If nothing lower on tree and there is a single case value,
  2737. // just do one compare for equality.
  2738. if((thisCase.lowerCase == null) && (thisCase.higherCase == null) && (thisCase.str1 == thisCase.str2))
  2739. {
  2740. testRVal.PushVal(this, thisCase, tokenTypeStr);
  2741. ilGen.Emit(thisCase, OpCodes.Ldstr, thisCase.str1);
  2742. ilGen.Emit(thisCase, OpCodes.Call, stringCompareMethodInfo);
  2743. ilGen.Emit(thisCase, OpCodes.Brfalse, thisCase.label);
  2744. ilGen.Emit(thisCase, OpCodes.Br, defaultLabel);
  2745. return;
  2746. }
  2747. // Determine where to jump if switch value is lower than lower case value.
  2748. ScriptMyLabel lowerLabel = defaultLabel;
  2749. if(thisCase.lowerCase != null)
  2750. {
  2751. lowerLabel = ilGen.DefineLabel("lower");
  2752. }
  2753. // If single case value, put comparison result in this temp.
  2754. CompValuTemp cmpv1 = null;
  2755. if(thisCase.str1 == thisCase.str2)
  2756. {
  2757. cmpv1 = new CompValuTemp(tokenTypeInt, this);
  2758. }
  2759. // If switch value .lt. lower case value, jump to lower label.
  2760. // Maybe save comparison result in a temp.
  2761. testRVal.PushVal(this, thisCase, tokenTypeStr);
  2762. ilGen.Emit(thisCase, OpCodes.Ldstr, thisCase.str1);
  2763. ilGen.Emit(thisCase, OpCodes.Call, stringCompareMethodInfo);
  2764. if(cmpv1 != null)
  2765. {
  2766. ilGen.Emit(thisCase, OpCodes.Dup);
  2767. cmpv1.Pop(this, thisCase);
  2768. }
  2769. ilGen.Emit(thisCase, OpCodes.Ldc_I4_0);
  2770. ilGen.Emit(thisCase, OpCodes.Blt, lowerLabel);
  2771. // If switch value .le. higher case value, jump to case code.
  2772. // Maybe get comparison from the temp.
  2773. if(cmpv1 == null)
  2774. {
  2775. testRVal.PushVal(this, thisCase, tokenTypeStr);
  2776. ilGen.Emit(thisCase, OpCodes.Ldstr, thisCase.str2);
  2777. ilGen.Emit(thisCase, OpCodes.Call, stringCompareMethodInfo);
  2778. }
  2779. else
  2780. {
  2781. cmpv1.PushVal(this, thisCase);
  2782. }
  2783. ilGen.Emit(thisCase, OpCodes.Ldc_I4_0);
  2784. ilGen.Emit(thisCase, OpCodes.Ble, thisCase.label);
  2785. // Output code for higher comparison if any.
  2786. if(thisCase.higherCase == null)
  2787. {
  2788. ilGen.Emit(thisCase, OpCodes.Br, defaultLabel);
  2789. }
  2790. else
  2791. {
  2792. OutputStrCase(testRVal, thisCase.higherCase, defaultLabel);
  2793. }
  2794. // Output code for lower comparison if any.
  2795. if(thisCase.lowerCase != null)
  2796. {
  2797. ilGen.MarkLabel(lowerLabel);
  2798. OutputStrCase(testRVal, thisCase.lowerCase, defaultLabel);
  2799. }
  2800. }
  2801. /**
  2802. * @brief output code for a throw statement.
  2803. * @param throwStmt = throw statement token, including value to be thrown
  2804. */
  2805. private void GenerateStmtThrow(TokenStmtThrow throwStmt)
  2806. {
  2807. if(!mightGetHere)
  2808. return;
  2809. // 'throw' statements never fall through.
  2810. mightGetHere = false;
  2811. // Output code for either a throw or a rethrow.
  2812. if(throwStmt.rVal == null)
  2813. {
  2814. for(TokenStmtBlock blk = curStmtBlock; blk != null; blk = blk.outerStmtBlock)
  2815. {
  2816. if(curStmtBlock.isCatch)
  2817. {
  2818. ilGen.Emit(throwStmt, OpCodes.Rethrow);
  2819. return;
  2820. }
  2821. }
  2822. ErrorMsg(throwStmt, "rethrow allowed only in catch clause");
  2823. }
  2824. else
  2825. {
  2826. CompValu rVal = GenerateFromRVal(throwStmt.rVal);
  2827. rVal.PushVal(this, throwStmt.rVal, tokenTypeObj);
  2828. ilGen.Emit(throwStmt, OpCodes.Call, thrownExceptionWrapMethodInfo);
  2829. ilGen.Emit(throwStmt, OpCodes.Throw);
  2830. }
  2831. }
  2832. /**
  2833. * @brief output code for a try/catch/finally block
  2834. */
  2835. private void GenerateStmtTry(TokenStmtTry tryStmt)
  2836. {
  2837. if(!mightGetHere)
  2838. return;
  2839. /*
  2840. * Reducer should make sure we have exactly one of catch or finally.
  2841. */
  2842. if((tryStmt.catchStmt == null) && (tryStmt.finallyStmt == null))
  2843. {
  2844. throw new Exception("must have a catch or a finally on try");
  2845. }
  2846. if((tryStmt.catchStmt != null) && (tryStmt.finallyStmt != null))
  2847. {
  2848. throw new Exception("can't have both catch and finally on same try");
  2849. }
  2850. // Stack the call labels.
  2851. // Try blocks have their own series of call labels.
  2852. ScriptMyLocal saveCallNo = actCallNo;
  2853. LinkedList<CallLabel> saveCallLabels = actCallLabels;
  2854. // Generate code for either try { } catch { } or try { } finally { }.
  2855. if(tryStmt.catchStmt != null)
  2856. GenerateStmtTryCatch(tryStmt);
  2857. if(tryStmt.finallyStmt != null)
  2858. GenerateStmtTryFinally(tryStmt);
  2859. // Restore call labels.
  2860. actCallNo = saveCallNo;
  2861. actCallLabels = saveCallLabels;
  2862. }
  2863. /**
  2864. * @brief output code for a try/catch block
  2865. *
  2866. * int __tryCallNo = -1; // call number within try { } subblock
  2867. * int __catCallNo = -1; // call number within catch { } subblock
  2868. * Exception __catThrown = null; // caught exception
  2869. * <oldCallLabel>: // the outside world jumps here to restore us no matter ...
  2870. * try { // ... where we actually were inside of try/catch
  2871. * if (__tryCallNo >= 0) goto tryCallSw; // maybe go do restore
  2872. * <try body using __tryCallNo> // execute script-defined code
  2873. * // ...stack capture WILL run catch { } subblock
  2874. * leave tryEnd; // exits
  2875. * tryThrow:<tryCallLabel>:
  2876. * throw new ScriptRestoreCatchException(__catThrown); // catch { } was running, jump to its beginning
  2877. * tryCallSw: // restoring...
  2878. * switch (__tryCallNo) back up into <try body> // not catching, jump back inside try
  2879. * } catch (Exception exc) {
  2880. * exc = ScriptRestoreCatchException.Unwrap(exc); // unwrap possible ScriptRestoreCatchException
  2881. * if (exc == null) goto catchRetro; // rethrow if IXMRUncatchable (eg, StackCaptureException)
  2882. * __catThrown = exc; // save what was thrown so restoring try { } will throw it again
  2883. * catchVar = exc; // set up script-visible variable
  2884. * __tryCallNo = tryThrow:<tryCallLabel>
  2885. * if (__catCallNo >= 0) goto catchCallSw; // if restoring, go check below
  2886. * <catch body using __catCallNo> // normal, execute script-defined code
  2887. * leave tryEnd; // all done, exit catch { }
  2888. * catchRetro:
  2889. * rethrow;
  2890. * catchCallSw:
  2891. * switch (__catCallNo) back up into <catch body> // restart catch { } code wherever it was
  2892. * }
  2893. * tryEnd:
  2894. */
  2895. private void GenerateStmtTryCatch(TokenStmtTry tryStmt)
  2896. {
  2897. CompValuTemp tryCallNo = new (tokenTypeInt, this);
  2898. CompValuTemp catCallNo = new (tokenTypeInt, this);
  2899. CompValuTemp catThrown = new (tokenTypeExc, this);
  2900. ScriptMyLabel tryCallSw = ilGen.DefineLabel("__tryCallSw_" + tryStmt.Unique);
  2901. ScriptMyLabel catchRetro = ilGen.DefineLabel("__catchRetro_" + tryStmt.Unique);
  2902. ScriptMyLabel catchCallSw = ilGen.DefineLabel("__catchCallSw_" + tryStmt.Unique);
  2903. ScriptMyLabel tryEnd = ilGen.DefineLabel("__tryEnd_" + tryStmt.Unique);
  2904. SetCallNo(tryStmt, tryCallNo, -1);
  2905. SetCallNo(tryStmt, catCallNo, -1);
  2906. ilGen.Emit(tryStmt, OpCodes.Ldnull);
  2907. catThrown.Pop(this, tryStmt);
  2908. _ = new CallLabel(this, tryStmt); // <oldcalllabel>:
  2909. ilGen.BeginExceptionBlock(); // try {
  2910. openCallLabel = null;
  2911. GetCallNo(tryStmt, tryCallNo); // if (__tryCallNo >= 0) goto tryCallSw;
  2912. ilGen.Emit(tryStmt, OpCodes.Ldc_I4_0);
  2913. ilGen.Emit(tryStmt, OpCodes.Bge, tryCallSw);
  2914. actCallNo = tryCallNo.localBuilder; // set up __tryCallNo for call labels
  2915. actCallLabels = new LinkedList<CallLabel>();
  2916. GenerateStmtBlock(tryStmt.tryStmt); // output the try block statement subblock
  2917. bool tryBlockFallsOutBottom = mightGetHere;
  2918. if(tryBlockFallsOutBottom)
  2919. {
  2920. _ = new CallLabel(this, tryStmt); // <tryCallLabel>:
  2921. ilGen.Emit(tryStmt, OpCodes.Leave, tryEnd); // leave tryEnd;
  2922. openCallLabel = null;
  2923. }
  2924. CallLabel tryThrow = new (this, tryStmt); // tryThrow:<tryCallLabel>:
  2925. catThrown.PushVal(this, tryStmt); // throw new ScriptRestoreCatchException (__catThrown);
  2926. ilGen.Emit(tryStmt, OpCodes.Newobj, scriptRestoreCatchExceptionConstructorInfo);
  2927. ilGen.Emit(tryStmt, OpCodes.Throw);
  2928. openCallLabel = null;
  2929. ilGen.MarkLabel(tryCallSw); // tryCallSw:
  2930. OutputCallNoSwitchStmt(); // switch (tryCallNo) ...
  2931. CompValuLocalVar catchVarLocExc = null;
  2932. CompValuTemp catchVarLocStr = null;
  2933. if(tryStmt.catchVar.type.ToSysType() == typeof(Exception))
  2934. {
  2935. catchVarLocExc = new CompValuLocalVar(tryStmt.catchVar.type, tryStmt.catchVar.name.val, this);
  2936. }
  2937. else if(tryStmt.catchVar.type.ToSysType() == typeof(String))
  2938. {
  2939. catchVarLocStr = new CompValuTemp(tryStmt.catchVar.type, this);
  2940. }
  2941. ScriptMyLocal excLocal = ilGen.DeclareLocal(typeof(String), "catchstr_" + tryStmt.Unique);
  2942. ilGen.BeginCatchBlock(typeof(Exception)); // start of the catch block that can catch any exception
  2943. ilGen.Emit(tryStmt.catchStmt, OpCodes.Call, scriptRestoreCatchExceptionUnwrap);
  2944. // exc = ScriptRestoreCatchException.Unwrap (exc);
  2945. ilGen.Emit(tryStmt.catchStmt, OpCodes.Dup); // rethrow if IXMRUncatchable (eg, StackCaptureException)
  2946. ilGen.Emit(tryStmt.catchStmt, OpCodes.Brfalse, catchRetro);
  2947. if(tryStmt.catchVar.type.ToSysType() == typeof(Exception))
  2948. {
  2949. tryStmt.catchVar.location = catchVarLocExc;
  2950. ilGen.Emit(tryStmt.catchStmt, OpCodes.Dup);
  2951. catThrown.Pop(this, tryStmt); // store exception object in catThrown
  2952. catchVarLocExc.Pop(this, tryStmt.catchVar.name); // also store in script-visible variable
  2953. }
  2954. else if(tryStmt.catchVar.type.ToSysType() == typeof(String))
  2955. {
  2956. tryStmt.catchVar.location = catchVarLocStr;
  2957. ilGen.Emit(tryStmt.catchStmt, OpCodes.Dup);
  2958. catThrown.Pop(this, tryStmt); // store exception object in catThrown
  2959. ilGen.Emit(tryStmt.catchStmt, OpCodes.Call, catchExcToStrMethodInfo);
  2960. ilGen.Emit(tryStmt.catchStmt, OpCodes.Stloc, excLocal);
  2961. catchVarLocStr.PopPre(this, tryStmt.catchVar.name);
  2962. ilGen.Emit(tryStmt.catchStmt, OpCodes.Ldloc, excLocal);
  2963. catchVarLocStr.PopPost(this, tryStmt.catchVar.name, tokenTypeStr);
  2964. }
  2965. else
  2966. {
  2967. throw new Exception("bad catch var type " + tryStmt.catchVar.type.ToString());
  2968. }
  2969. SetCallNo(tryStmt, tryCallNo, tryThrow.index); // __tryCallNo = tryThrow so it knows to do 'throw catThrown' on restore
  2970. GetCallNo(tryStmt, catCallNo); // if (__catCallNo >= 0) goto catchCallSw;
  2971. ilGen.Emit(tryStmt.catchStmt, OpCodes.Ldc_I4_0);
  2972. ilGen.Emit(tryStmt.catchStmt, OpCodes.Bge, catchCallSw);
  2973. actCallNo = catCallNo.localBuilder; // set up __catCallNo for call labels
  2974. actCallLabels.Clear();
  2975. mightGetHere = true; // if we can get to the 'try' assume we can get to the 'catch'
  2976. GenerateStmtBlock(tryStmt.catchStmt); // output catch clause statement subblock
  2977. if(mightGetHere)
  2978. {
  2979. _ = new CallLabel(this, tryStmt.catchStmt);
  2980. ilGen.Emit(tryStmt.catchStmt, OpCodes.Leave, tryEnd);
  2981. openCallLabel = null;
  2982. }
  2983. ilGen.MarkLabel(catchRetro); // not a script-visible exception, rethrow it
  2984. ilGen.Emit(tryStmt.catchStmt, OpCodes.Pop);
  2985. ilGen.Emit(tryStmt.catchStmt, OpCodes.Rethrow);
  2986. ilGen.MarkLabel(catchCallSw);
  2987. OutputCallNoSwitchStmt(); // restoring, jump back inside script-defined body
  2988. ilGen.EndExceptionBlock();
  2989. ilGen.MarkLabel(tryEnd);
  2990. mightGetHere |= tryBlockFallsOutBottom; // also get here if try body falls out bottom
  2991. }
  2992. /**
  2993. * @brief output code for a try/finally block
  2994. *
  2995. * This is such a mess because there is hidden state for the finally { } that we have to recreate.
  2996. * The finally { } can be entered either via an exception being thrown in the try { } or a leave
  2997. * being executed in the try { } whose target is outside the try { } finally { }.
  2998. *
  2999. * For the thrown exception case, we slip in a try { } catch { } wrapper around the original try { }
  3000. * body. This will sense any thrown exception that would execute the finally { }. Then we have our
  3001. * try { } throw the exception on restore which gets the finally { } called and on its way again.
  3002. *
  3003. * For the leave case, we prefix all leave instructions with a call label and we explicitly chain
  3004. * all leaves through each try { } that has an associated finally { } that the leave would unwind
  3005. * through. This gets each try { } to simply jump to the correct leave instruction which immediately
  3006. * invokes the corresponding finally { } and then chains to the next leave instruction on out until
  3007. * it gets to its target.
  3008. *
  3009. * int __finCallNo = -1; // call number within finally { } subblock
  3010. * int __tryCallNo = -1; // call number within try { } subblock
  3011. * Exception __catThrown = null; // caught exception
  3012. * <oldCallLabel>: // the outside world jumps here to restore us no matter ...
  3013. * try { // ... where we actually were inside of try/finally
  3014. * try {
  3015. * if (__tryCallNo >= 0) goto tryCallSw; // maybe go do restore
  3016. * <try body using __tryCallNo> // execute script-defined code
  3017. * // ...stack capture WILL run catch/finally { } subblock
  3018. * leave tryEnd; // executes finally { } subblock and exits
  3019. * tryThrow:<tryCallLabel>:
  3020. * throw new ScriptRestoreCatchException(__catThrown); // catch { } was running, jump to its beginning
  3021. * tryCallSw: // restoring...
  3022. * switch (__tryCallNo) back up into <try body> // jump back inside try, ...
  3023. * // ... maybe to a leave if we were doing finally { } subblock
  3024. * } catch (Exception exc) { // in case we're getting to finally { } via a thrown exception:
  3025. * exc = ScriptRestoreCatchException.Unwrap(exc); // unwrap possible ScriptRestoreCatchException
  3026. * if (callMode == CallMode_SAVE) goto catchRetro; // don't touch anything if capturing stack
  3027. * __catThrown = exc; // save exception so try { } can throw it on restore
  3028. * __tryCallNo = tryThrow:<tryCallLabel>; // tell try { } to throw it on restore
  3029. * catchRetro:
  3030. * rethrow; // in any case, go on to finally { } subblock now
  3031. * }
  3032. * } finally {
  3033. * if (callMode == CallMode_SAVE) goto finEnd; // don't touch anything if capturing stack
  3034. * if (__finCallNo >= 0) goto finCallSw; // maybe go do restore
  3035. * <finally body using __finCallNo> // normal, execute script-defined code
  3036. * finEnd:
  3037. * endfinally // jump to leave/throw target or next outer finally { }
  3038. * finCallSw:
  3039. * switch (__finCallNo) back up into <finally body> // restoring, restart finally { } code wherever it was
  3040. * }
  3041. * tryEnd:
  3042. */
  3043. private void GenerateStmtTryFinally(TokenStmtTry tryStmt)
  3044. {
  3045. CompValuTemp finCallNo = new (tokenTypeInt, this);
  3046. CompValuTemp tryCallNo = new (tokenTypeInt, this);
  3047. CompValuTemp catThrown = new (tokenTypeExc, this);
  3048. ScriptMyLabel tryCallSw = ilGen.DefineLabel("__tryCallSw_" + tryStmt.Unique);
  3049. ScriptMyLabel catchRetro = ilGen.DefineLabel("__catchRetro_" + tryStmt.Unique);
  3050. ScriptMyLabel finCallSw = ilGen.DefineLabel("__finCallSw_" + tryStmt.Unique);
  3051. BreakContTarg finEnd = new (this, "__finEnd_" + tryStmt.Unique);
  3052. ScriptMyLabel tryEnd = ilGen.DefineLabel("__tryEnd_" + tryStmt.Unique);
  3053. SetCallNo(tryStmt, finCallNo, -1);
  3054. SetCallNo(tryStmt, tryCallNo, -1);
  3055. ilGen.Emit(tryStmt, OpCodes.Ldnull);
  3056. catThrown.Pop(this, tryStmt);
  3057. _ = new CallLabel(this, tryStmt); // <oldcalllabel>:
  3058. ilGen.BeginExceptionBlock(); // try {
  3059. ilGen.BeginExceptionBlock(); // try {
  3060. openCallLabel = null;
  3061. GetCallNo(tryStmt, tryCallNo); // if (__tryCallNo >= 0) goto tryCallSw;
  3062. ilGen.Emit(tryStmt, OpCodes.Ldc_I4_0);
  3063. ilGen.Emit(tryStmt, OpCodes.Bge, tryCallSw);
  3064. actCallNo = tryCallNo.localBuilder; // set up __tryCallNo for call labels
  3065. actCallLabels = new LinkedList<CallLabel>();
  3066. GenerateStmtBlock(tryStmt.tryStmt); // output the try block statement subblock
  3067. if(mightGetHere)
  3068. {
  3069. _ = new CallLabel(this, tryStmt); // <newCallLabel>:
  3070. ilGen.Emit(tryStmt, OpCodes.Leave, tryEnd); // leave tryEnd;
  3071. openCallLabel = null;
  3072. }
  3073. foreach(IntermediateLeave iLeave in tryStmt.iLeaves.Values)
  3074. {
  3075. ilGen.MarkLabel(iLeave.jumpIntoLabel); // intr2_exit:
  3076. _ = new CallLabel(this, tryStmt); // tryCallNo = n;
  3077. ilGen.Emit(tryStmt, OpCodes.Leave, iLeave.jumpAwayLabel); // __callNo_n_: leave int1_exit;
  3078. openCallLabel = null;
  3079. }
  3080. CallLabel tryThrow = new (this, tryStmt); // tryThrow:<tryCallLabel>:
  3081. catThrown.PushVal(this, tryStmt); // throw new ScriptRestoreCatchException (__catThrown);
  3082. ilGen.Emit(tryStmt, OpCodes.Newobj, scriptRestoreCatchExceptionConstructorInfo);
  3083. ilGen.Emit(tryStmt, OpCodes.Throw);
  3084. openCallLabel = null;
  3085. ilGen.MarkLabel(tryCallSw); // tryCallSw:
  3086. OutputCallNoSwitchStmt(); // switch (tryCallNo) ...
  3087. // }
  3088. ilGen.BeginCatchBlock(typeof(Exception)); // start of the catch block that can catch any exception
  3089. ilGen.Emit(tryStmt, OpCodes.Call, scriptRestoreCatchExceptionUnwrap); // exc = ScriptRestoreCatchException.Unwrap (exc);
  3090. PushXMRInst(); // if (callMode == CallMode_SAVE) goto catchRetro;
  3091. ilGen.Emit(tryStmt, OpCodes.Ldfld, callModeFieldInfo);
  3092. ilGen.Emit(tryStmt, OpCodes.Ldc_I4, XMRInstAbstract.CallMode_SAVE);
  3093. ilGen.Emit(tryStmt, OpCodes.Beq, catchRetro);
  3094. catThrown.Pop(this, tryStmt); // __catThrown = exc;
  3095. SetCallNo(tryStmt, tryCallNo, tryThrow.index); // __tryCallNo = tryThrow:<tryCallLabel>;
  3096. ilGen.Emit(tryStmt, OpCodes.Rethrow);
  3097. ilGen.MarkLabel(catchRetro); // catchRetro:
  3098. ilGen.Emit(tryStmt, OpCodes.Pop);
  3099. ilGen.Emit(tryStmt, OpCodes.Rethrow); // rethrow;
  3100. ilGen.EndExceptionBlock(); // }
  3101. ilGen.BeginFinallyBlock(); // start of the finally block
  3102. PushXMRInst(); // if (callMode == CallMode_SAVE) goto finEnd;
  3103. ilGen.Emit(tryStmt, OpCodes.Ldfld, callModeFieldInfo);
  3104. ilGen.Emit(tryStmt, OpCodes.Ldc_I4, XMRInstAbstract.CallMode_SAVE);
  3105. ilGen.Emit(tryStmt, OpCodes.Beq, finEnd.label);
  3106. GetCallNo(tryStmt, finCallNo); // if (__finCallNo >= 0) goto finCallSw;
  3107. ilGen.Emit(tryStmt, OpCodes.Ldc_I4_0);
  3108. ilGen.Emit(tryStmt, OpCodes.Bge, finCallSw);
  3109. actCallNo = finCallNo.localBuilder; // set up __finCallNo for call labels
  3110. actCallLabels.Clear();
  3111. mightGetHere = true; // if we can get to the 'try' assume we can get to the 'finally'
  3112. GenerateStmtBlock(tryStmt.finallyStmt); // output finally clause statement subblock
  3113. ilGen.MarkLabel(finEnd.label); // finEnd:
  3114. ilGen.Emit(tryStmt, OpCodes.Endfinally); // return out to next finally { } or catch { } or leave target
  3115. ilGen.MarkLabel(finCallSw); // restore mode, switch (finCallNo) ...
  3116. OutputCallNoSwitchStmt();
  3117. ilGen.EndExceptionBlock();
  3118. ilGen.MarkLabel(tryEnd);
  3119. mightGetHere |= finEnd.used; // get here if finally body falls through or has a break statement
  3120. }
  3121. /**
  3122. * @brief Generate code to initialize a variable to its default value.
  3123. */
  3124. private void GenerateStmtVarIniDef(TokenStmtVarIniDef varIniDefStmt)
  3125. {
  3126. if(!mightGetHere)
  3127. return;
  3128. CompValu left = GenerateFromLVal(varIniDefStmt.var);
  3129. left.PopPre(this, varIniDefStmt);
  3130. PushDefaultValue(left.type);
  3131. left.PopPost(this, varIniDefStmt);
  3132. }
  3133. /**
  3134. * @brief generate code for a 'while' statement including the loop body.
  3135. */
  3136. private void GenerateStmtWhile(TokenStmtWhile whileStmt)
  3137. {
  3138. if(!mightGetHere)
  3139. return;
  3140. BreakContTarg oldBreakTarg = curBreakTarg;
  3141. BreakContTarg oldContTarg = curContTarg;
  3142. ScriptMyLabel loopLabel = ilGen.DefineLabel("whileloop_" + whileStmt.Unique);
  3143. curBreakTarg = new BreakContTarg(this, "whilebreak_" + whileStmt.Unique);
  3144. curContTarg = new BreakContTarg(this, "whilecont_" + whileStmt.Unique);
  3145. ilGen.MarkLabel(loopLabel); // loop:
  3146. CompValu testRVal = GenerateFromRVal(whileStmt.testRVal); // testRVal = while test expression
  3147. if(!IsConstBoolExprTrue(testRVal))
  3148. {
  3149. testRVal.PushVal(this, whileStmt.testRVal, tokenTypeBool); // if (!testRVal)
  3150. ilGen.Emit(whileStmt, OpCodes.Brfalse, curBreakTarg.label); // goto break
  3151. curBreakTarg.used = true;
  3152. }
  3153. GenerateStmt(whileStmt.bodyStmt); // while body statement
  3154. if(curContTarg.used)
  3155. {
  3156. ilGen.MarkLabel(curContTarg.label); // cont:
  3157. mightGetHere = true;
  3158. }
  3159. if(mightGetHere)
  3160. {
  3161. EmitCallCheckRun(whileStmt, false); // __sw.CheckRun()
  3162. ilGen.Emit(whileStmt, OpCodes.Br, loopLabel); // goto loop
  3163. }
  3164. mightGetHere = curBreakTarg.used;
  3165. if(mightGetHere)
  3166. {
  3167. ilGen.MarkLabel(curBreakTarg.label); // done:
  3168. }
  3169. curBreakTarg = oldBreakTarg;
  3170. curContTarg = oldContTarg;
  3171. }
  3172. /**
  3173. * @brief process a local variable declaration statement, possibly with initialization expression.
  3174. * Note that the function header processing allocated stack space (CompValuTemp) for the
  3175. * variable and now all we do is write its initialization value.
  3176. */
  3177. private void GenerateDeclVar(TokenDeclVar declVar)
  3178. {
  3179. // Script gave us an initialization value, so just store init value in var like an assignment statement.
  3180. // If no init given, set it to its default value.
  3181. CompValu local = declVar.location;
  3182. if(declVar.init != null)
  3183. {
  3184. CompValu rVal = GenerateFromRVal(declVar.init, local.GetArgTypes());
  3185. local.PopPre(this, declVar);
  3186. rVal.PushVal(this, declVar.init, declVar.type);
  3187. local.PopPost(this, declVar);
  3188. }
  3189. else
  3190. {
  3191. local.PopPre(this, declVar);
  3192. PushDefaultValue(declVar.type);
  3193. local.PopPost(this, declVar);
  3194. }
  3195. }
  3196. /**
  3197. * @brief Get the type and location of an L-value (eg, variable)
  3198. * @param lVal = L-value expression to evaluate
  3199. * @param argsig = null: it's a field/property
  3200. * else: select overload method that fits these arg types
  3201. */
  3202. private CompValu GenerateFromLVal(TokenLVal lVal)
  3203. {
  3204. return GenerateFromLVal(lVal, null);
  3205. }
  3206. private CompValu GenerateFromLVal(TokenLVal lVal, TokenType[] argsig)
  3207. {
  3208. if(lVal is TokenLValArEle TokenLValArElelVal)
  3209. return GenerateFromLValArEle(TokenLValArElelVal);
  3210. if(lVal is TokenLValBaseField TokenLValBaseFieldlVal)
  3211. return GenerateFromLValBaseField(TokenLValBaseFieldlVal, argsig);
  3212. if(lVal is TokenLValIField TokenLValIFieldlVal)
  3213. return GenerateFromLValIField(TokenLValIFieldlVal, argsig);
  3214. if(lVal is TokenLValName TokenLValNamelVal)
  3215. return GenerateFromLValName(TokenLValNamelVal, argsig);
  3216. if(lVal is TokenLValSField TokenLValSFieldlVal)
  3217. return GenerateFromLValSField(TokenLValSFieldlVal, argsig);
  3218. throw new Exception("bad lval class");
  3219. }
  3220. /**
  3221. * @brief we have an L-value token that is an element within an array.
  3222. * @returns a CompValu giving the type and location of the element of the array.
  3223. */
  3224. private CompValu GenerateFromLValArEle(TokenLValArEle lVal)
  3225. {
  3226. CompValu subCompValu;
  3227. // Compute location of array itself.
  3228. CompValu baseCompValu = GenerateFromRVal(lVal.baseRVal);
  3229. // Maybe it is a fixed array access.
  3230. string basetypestring = baseCompValu.type.ToString();
  3231. if(basetypestring.EndsWith(']'))
  3232. {
  3233. TokenRVal subRVal = lVal.subRVal;
  3234. int nSubs = 1;
  3235. if(subRVal is TokenRValList list)
  3236. {
  3237. nSubs = list.nItems;
  3238. subRVal = list.rVal;
  3239. }
  3240. int rank = basetypestring.IndexOf(']') - basetypestring.IndexOf('[');
  3241. if(nSubs != rank)
  3242. {
  3243. ErrorMsg(lVal.baseRVal, "expect " + rank + " subscript" + ((rank == 1) ? "" : "s") + " but have " + nSubs);
  3244. }
  3245. CompValu[] subCompValus = new CompValu[rank];
  3246. int i;
  3247. for(i = 0; (subRVal != null) && (i < rank); i++)
  3248. {
  3249. subCompValus[i] = GenerateFromRVal(subRVal);
  3250. subRVal = (TokenRVal)subRVal.nextToken;
  3251. }
  3252. while(i < rank)
  3253. subCompValus[i++] = new CompValuInteger(new TokenTypeInt(lVal.subRVal), 0);
  3254. return new CompValuFixArEl(this, baseCompValu, subCompValus);
  3255. }
  3256. // Maybe it is accessing the $idxprop property of a script-defined class.
  3257. if(baseCompValu.type is TokenTypeSDTypeClass typeclass)
  3258. {
  3259. TokenName name = new (lVal, "$idxprop");
  3260. TokenTypeSDTypeClass sdtType = typeclass;
  3261. TokenDeclSDTypeClass sdtDecl = sdtType.decl;
  3262. TokenDeclVar idxProp = FindThisMember(sdtDecl, name, null);
  3263. if(idxProp == null)
  3264. {
  3265. ErrorMsg(lVal, "no index property in class " + sdtDecl.longName.val);
  3266. return new CompValuVoid(lVal);
  3267. }
  3268. if((idxProp.sdtFlags & ScriptReduce.SDT_STATIC) != 0)
  3269. {
  3270. ErrorMsg(lVal, "non-static reference to static member " + idxProp.name.val);
  3271. return new CompValuVoid(idxProp);
  3272. }
  3273. CheckAccess(idxProp, name);
  3274. TokenType[] argTypes = IdxPropArgTypes(idxProp);
  3275. CompValu[] compValus = IdxPropCompValus(lVal, argTypes.Length);
  3276. return new CompValuIdxProp(idxProp, baseCompValu, argTypes, compValus);
  3277. }
  3278. // Maybe they are accessing $idxprop property of a script-defined interface.
  3279. if(baseCompValu.type is TokenTypeSDTypeInterface TokenTypeSDTypeInterfacebaseCompValutype)
  3280. {
  3281. TokenName name = new (lVal, "$idxprop");
  3282. TokenTypeSDTypeInterface sdtType = TokenTypeSDTypeInterfacebaseCompValutype;
  3283. TokenDeclVar idxProp = FindInterfaceMember(sdtType, name, null, ref baseCompValu);
  3284. if(idxProp == null)
  3285. {
  3286. ErrorMsg(lVal, "no index property defined for interface " + sdtType.decl.longName.val);
  3287. return baseCompValu;
  3288. }
  3289. TokenType[] argTypes = IdxPropArgTypes(idxProp);
  3290. CompValu[] compValus = IdxPropCompValus(lVal, argTypes.Length);
  3291. return new CompValuIdxProp(idxProp, baseCompValu, argTypes, compValus);
  3292. }
  3293. // Maybe it is extracting a character from a string.
  3294. if((baseCompValu.type is TokenTypeKey) || (baseCompValu.type is TokenTypeStr))
  3295. {
  3296. subCompValu = GenerateFromRVal(lVal.subRVal);
  3297. return new CompValuStrChr(new TokenTypeChar(lVal), baseCompValu, subCompValu);
  3298. }
  3299. // Maybe it is extracting an element from a list.
  3300. if(baseCompValu.type is TokenTypeList)
  3301. {
  3302. subCompValu = GenerateFromRVal(lVal.subRVal);
  3303. return new CompValuListEl(new TokenTypeObject(lVal), baseCompValu, subCompValu);
  3304. }
  3305. // Access should be to XMR_Array otherwise.
  3306. if(baseCompValu.type is not TokenTypeArray)
  3307. {
  3308. ErrorMsg(lVal, "taking subscript of non-array");
  3309. return baseCompValu;
  3310. }
  3311. subCompValu = GenerateFromRVal(lVal.subRVal);
  3312. return new CompValuArEle(new TokenTypeObject(lVal), baseCompValu, subCompValu);
  3313. }
  3314. /**
  3315. * @brief Get number and type of arguments required by an index property.
  3316. */
  3317. private static TokenType[] IdxPropArgTypes(TokenDeclVar idxProp)
  3318. {
  3319. TokenType[] argTypes;
  3320. if(idxProp.getProp != null)
  3321. {
  3322. int nArgs = idxProp.getProp.argDecl.varDict.Count;
  3323. argTypes = new TokenType[nArgs];
  3324. foreach(TokenDeclVar var in idxProp.getProp.argDecl.varDict)
  3325. {
  3326. argTypes[var.vTableIndex] = var.type;
  3327. }
  3328. }
  3329. else
  3330. {
  3331. int nArgs = idxProp.setProp.argDecl.varDict.Count - 1;
  3332. argTypes = new TokenType[nArgs];
  3333. foreach(TokenDeclVar var in idxProp.setProp.argDecl.varDict)
  3334. {
  3335. if(var.vTableIndex < nArgs)
  3336. {
  3337. argTypes[var.vTableIndex] = var.type;
  3338. }
  3339. }
  3340. }
  3341. return argTypes;
  3342. }
  3343. /**
  3344. * @brief Get number and computed value of index property arguments.
  3345. * @param lVal = list of arguments
  3346. * @param nArgs = number of arguments required
  3347. * @returns null: argument count mismatch
  3348. * else: array of index property argument values
  3349. */
  3350. private CompValu[] IdxPropCompValus(TokenLValArEle lVal, int nArgs)
  3351. {
  3352. TokenRVal subRVal = lVal.subRVal;
  3353. int nSubs = 1;
  3354. if(subRVal is TokenRValList list)
  3355. {
  3356. nSubs = list.nItems;
  3357. subRVal = list.rVal;
  3358. }
  3359. if(nSubs != nArgs)
  3360. {
  3361. ErrorMsg(lVal, "index property requires " + nArgs + " subscript(s)");
  3362. return null;
  3363. }
  3364. CompValu[] subCompValus = new CompValu[nArgs];
  3365. for(int i = 0; i < nArgs; i++)
  3366. {
  3367. subCompValus[i] = GenerateFromRVal(subRVal);
  3368. subRVal = (TokenRVal)subRVal.nextToken;
  3369. }
  3370. return subCompValus;
  3371. }
  3372. /**
  3373. * @brief using 'base' within a script-defined instance method to refer to an instance field/method
  3374. * of the class being extended.
  3375. */
  3376. private CompValu GenerateFromLValBaseField(TokenLValBaseField baseField, TokenType[] argsig)
  3377. {
  3378. string fieldName = baseField.fieldName.val;
  3379. TokenDeclSDType sdtDecl = curDeclFunc.sdtClass;
  3380. if((sdtDecl == null) || ((curDeclFunc.sdtFlags & ScriptReduce.SDT_STATIC) != 0))
  3381. {
  3382. ErrorMsg(baseField, "cannot use 'base' outside instance method body");
  3383. return new CompValuVoid(baseField);
  3384. }
  3385. if(!IsSDTInstMethod())
  3386. {
  3387. ErrorMsg(baseField, "cannot access instance member of base class from static method");
  3388. return new CompValuVoid(baseField);
  3389. }
  3390. TokenDeclVar declVar = FindThisMember(sdtDecl.extends, baseField.fieldName, argsig);
  3391. if(declVar != null)
  3392. {
  3393. CheckAccess(declVar, baseField.fieldName);
  3394. TokenType baseType = declVar.sdtClass.MakeRefToken(baseField);
  3395. CompValu basePtr = new CompValuArg(baseType, 0);
  3396. return AccessInstanceMember(declVar, basePtr, baseField, true);
  3397. }
  3398. ErrorMsg(baseField, "no member " + fieldName + ArgSigString(argsig) + " rootward of " + sdtDecl.longName.val);
  3399. return new CompValuVoid(baseField);
  3400. }
  3401. /**
  3402. * @brief We have an L-value token that is an instance field/method within a struct.
  3403. * @returns a CompValu giving the type and location of the field/method in the struct.
  3404. */
  3405. private CompValu GenerateFromLValIField(TokenLValIField lVal, TokenType[] argsig)
  3406. {
  3407. CompValu baseRVal = GenerateFromRVal(lVal.baseRVal);
  3408. string fieldName = lVal.fieldName.val + ArgSigString(argsig);
  3409. // Maybe they are accessing an instance field, method or property of a script-defined class.
  3410. if(baseRVal.type is TokenTypeSDTypeClass)
  3411. {
  3412. TokenTypeSDTypeClass sdtType = (TokenTypeSDTypeClass)baseRVal.type;
  3413. TokenDeclSDTypeClass sdtDecl = sdtType.decl;
  3414. TokenDeclVar declVar = FindThisMember(sdtDecl, lVal.fieldName, argsig);
  3415. if(declVar != null)
  3416. {
  3417. CheckAccess(declVar, lVal.fieldName);
  3418. return AccessInstanceMember(declVar, baseRVal, lVal, false);
  3419. }
  3420. ErrorMsg(lVal.fieldName, "no member " + fieldName + " in class " + sdtDecl.longName.val);
  3421. return new CompValuVoid(lVal.fieldName);
  3422. }
  3423. // Maybe they are accessing a method or property of a script-defined interface.
  3424. if(baseRVal.type is TokenTypeSDTypeInterface)
  3425. {
  3426. TokenTypeSDTypeInterface sdtType = (TokenTypeSDTypeInterface)baseRVal.type;
  3427. TokenDeclVar declVar = FindInterfaceMember(sdtType, lVal.fieldName, argsig, ref baseRVal);
  3428. if(declVar != null)
  3429. {
  3430. return new CompValuIntfMember(declVar, baseRVal);
  3431. }
  3432. ErrorMsg(lVal.fieldName, "no member " + fieldName + " in interface " + sdtType.decl.longName.val);
  3433. return new CompValuVoid(lVal.fieldName);
  3434. }
  3435. // Since we only have a few built-in types with fields, just pound them out.
  3436. if(baseRVal.type is TokenTypeArray)
  3437. {
  3438. // no arguments, no parentheses, just the field name, returning integer
  3439. // but internally, it is a call to a method()
  3440. if(fieldName == "count")
  3441. {
  3442. return new CompValuIntInstROProp(tokenTypeInt, baseRVal, arrayCountMethodInfo);
  3443. }
  3444. // no arguments but with the parentheses, returning void
  3445. if(fieldName == "clear()")
  3446. {
  3447. return new CompValuIntInstMeth(XMR_Array.clearDelegate, baseRVal, arrayClearMethodInfo);
  3448. }
  3449. // single integer argument, returning an object
  3450. if(fieldName == "index(integer)")
  3451. {
  3452. return new CompValuIntInstMeth(XMR_Array.indexDelegate, baseRVal, arrayIndexMethodInfo);
  3453. }
  3454. if(fieldName == "value(integer)")
  3455. {
  3456. return new CompValuIntInstMeth(XMR_Array.valueDelegate, baseRVal, arrayValueMethodInfo);
  3457. }
  3458. }
  3459. if(baseRVal.type is TokenTypeRot)
  3460. {
  3461. FieldInfo fi = null;
  3462. if(fieldName == "x")
  3463. fi = rotationXFieldInfo;
  3464. if(fieldName == "y")
  3465. fi = rotationYFieldInfo;
  3466. if(fieldName == "z")
  3467. fi = rotationZFieldInfo;
  3468. if(fieldName == "s")
  3469. fi = rotationSFieldInfo;
  3470. if(fi != null)
  3471. {
  3472. return new CompValuField(new TokenTypeFloat(lVal), baseRVal, fi);
  3473. }
  3474. }
  3475. if(baseRVal.type is TokenTypeVec)
  3476. {
  3477. FieldInfo fi = null;
  3478. if(fieldName == "x")
  3479. fi = vectorXFieldInfo;
  3480. if(fieldName == "y")
  3481. fi = vectorYFieldInfo;
  3482. if(fieldName == "z")
  3483. fi = vectorZFieldInfo;
  3484. if(fi != null)
  3485. {
  3486. return new CompValuField(new TokenTypeFloat(lVal), baseRVal, fi);
  3487. }
  3488. }
  3489. ErrorMsg(lVal, "type " + baseRVal.type.ToString() + " does not define member " + fieldName);
  3490. return baseRVal;
  3491. }
  3492. /**
  3493. * @brief We have an L-value token that is a function, method or variable name.
  3494. * @param lVal = name we are looking for
  3495. * @param argsig = null: just look for name as a variable
  3496. * else: look for name as a function/method being called with the given argument types
  3497. * eg, "(string,integer,list)"
  3498. * @returns a CompValu giving the type and location of the function, method or variable.
  3499. */
  3500. private CompValu GenerateFromLValName(TokenLValName lVal, TokenType[] argsig)
  3501. {
  3502. // Look in variable stack then look for built-in constants and functions.
  3503. TokenDeclVar var = FindNamedVar(lVal, argsig);
  3504. if(var == null)
  3505. {
  3506. ErrorMsg(lVal, "undefined constant/function/variable " + lVal.name.val + ArgSigString(argsig));
  3507. return new CompValuVoid(lVal);
  3508. }
  3509. // Maybe it has an implied 'this.' on the front.
  3510. if((var.sdtClass != null) && ((var.sdtFlags & ScriptReduce.SDT_STATIC) == 0))
  3511. {
  3512. if(!IsSDTInstMethod())
  3513. {
  3514. ErrorMsg(lVal, "cannot access instance member of class from static method");
  3515. return new CompValuVoid(lVal);
  3516. }
  3517. // Don't allow something such as:
  3518. //
  3519. // class A {
  3520. // integer I;
  3521. // class B {
  3522. // Print ()
  3523. // {
  3524. // llOwnerSay ("I=" + (string)I); <- access to I not allowed inside class B.
  3525. // explicit reference required as we don't
  3526. // have a valid reference to class A.
  3527. // }
  3528. // }
  3529. // }
  3530. //
  3531. // But do allow something such as:
  3532. //
  3533. // class A {
  3534. // integer I;
  3535. // }
  3536. // class B : A {
  3537. // Print ()
  3538. // {
  3539. // llOwnerSay ("I=" + (string)I);
  3540. // }
  3541. // }
  3542. for(TokenDeclSDType c = curDeclFunc.sdtClass; c != var.sdtClass; c = c.extends)
  3543. {
  3544. if(c == null)
  3545. {
  3546. // our arg0 points to an instance of curDeclFunc.sdtClass, not var.sdtClass
  3547. ErrorMsg(lVal, "cannot access instance member of outer class with implied 'this'");
  3548. break;
  3549. }
  3550. }
  3551. CompValu thisCompValu = new CompValuArg(var.sdtClass.MakeRefToken(lVal), 0);
  3552. return AccessInstanceMember(var, thisCompValu, lVal, false);
  3553. }
  3554. // It's a local variable, static field, global, constant, etc.
  3555. return var.location;
  3556. }
  3557. /**
  3558. * @brief Access a script-defined type's instance member
  3559. * @param declVar = which member (field,method,property) to access
  3560. * @param basePtr = points to particular object instance
  3561. * @param ignoreVirt = true: access declVar's method directly; else: maybe use vTable
  3562. * @returns where the field/method/property is located
  3563. */
  3564. private CompValu AccessInstanceMember(TokenDeclVar declVar, CompValu basePtr, Token errorAt, bool ignoreVirt)
  3565. {
  3566. if((declVar.sdtFlags & ScriptReduce.SDT_STATIC) != 0)
  3567. {
  3568. ErrorMsg(errorAt, "non-static reference to static member " + declVar.name.val);
  3569. return new CompValuVoid(declVar);
  3570. }
  3571. return new CompValuInstMember(declVar, basePtr, ignoreVirt);
  3572. }
  3573. /**
  3574. * @brief we have an L-value token that is a static member within a struct.
  3575. * @returns a CompValu giving the type and location of the member in the struct.
  3576. */
  3577. private CompValu GenerateFromLValSField(TokenLValSField lVal, TokenType[] argsig)
  3578. {
  3579. TokenType stType = lVal.baseType;
  3580. string fieldName = lVal.fieldName.val + ArgSigString(argsig);
  3581. // Maybe they are accessing a static member of a script-defined class.
  3582. if (stType is TokenTypeSDTypeClass sdtType)
  3583. {
  3584. TokenDeclVar declVar = FindThisMember(sdtType.decl, lVal.fieldName, argsig);
  3585. if (declVar != null)
  3586. {
  3587. CheckAccess(declVar, lVal.fieldName);
  3588. if ((declVar.sdtFlags & ScriptReduce.SDT_STATIC) == 0)
  3589. {
  3590. ErrorMsg(lVal.fieldName, "static reference to non-static member " + fieldName);
  3591. return new CompValuVoid(lVal.fieldName);
  3592. }
  3593. return declVar.location;
  3594. }
  3595. }
  3596. ErrorMsg(lVal.fieldName, "no member " + fieldName + " in " + stType.ToString());
  3597. return new CompValuVoid(lVal.fieldName);
  3598. }
  3599. /**
  3600. * @brief generate code from an RVal expression and return its type and where the result is stored.
  3601. * For anything that has side-effects, statements are generated that perform the computation then
  3602. * the result it put in a temp var and the temp var name is returned.
  3603. * For anything without side-effects, they are returned as an equivalent sequence of Emits.
  3604. * @param rVal = rVal token to be evaluated
  3605. * @param argsig = null: not being used in an function/method context
  3606. * else: string giving argument types, eg, "(string,integer,list,vector)"
  3607. * that can be used to select among overloaded methods
  3608. * @returns resultant type and location
  3609. */
  3610. private CompValu GenerateFromRVal(TokenRVal rVal)
  3611. {
  3612. return GenerateFromRVal(rVal, null);
  3613. }
  3614. private CompValu GenerateFromRVal(TokenRVal rVal, TokenType[] argsig)
  3615. {
  3616. errorMessageToken = rVal;
  3617. // Maybe the expression can be converted to a constant.
  3618. bool didOne;
  3619. try
  3620. {
  3621. do
  3622. {
  3623. didOne = false;
  3624. rVal = rVal.TryComputeConstant(LookupBodyConstants, ref didOne);
  3625. } while(didOne);
  3626. }
  3627. catch(Exception ex)
  3628. {
  3629. ErrorMsg(errorMessageToken, ex.Message);
  3630. throw;
  3631. }
  3632. // Generate code for the computation and return resulting type and location.
  3633. CompValu cVal = null;
  3634. if(rVal is TokenRValAsnPost TokenRValAsnPostrVal)
  3635. cVal = GenerateFromRValAsnPost(TokenRValAsnPostrVal);
  3636. else if (rVal is TokenRValAsnPre TokenRValAsnPrerVal)
  3637. cVal = GenerateFromRValAsnPre(TokenRValAsnPrerVal);
  3638. else if (rVal is TokenRValCall TokenRValCallrVal)
  3639. cVal = GenerateFromRValCall(TokenRValCallrVal);
  3640. else if (rVal is TokenRValCast TokenRValCastrVal)
  3641. cVal = GenerateFromRValCast(TokenRValCastrVal);
  3642. else if (rVal is TokenRValCondExpr TokenRValCondExprrVal)
  3643. cVal = GenerateFromRValCondExpr(TokenRValCondExprrVal);
  3644. else if (rVal is TokenRValConst TokenRValConstrVal)
  3645. cVal = GenerateFromRValConst(TokenRValConstrVal);
  3646. else if (rVal is TokenRValInitDef TokenRValInitDefrVal)
  3647. cVal = GenerateFromRValInitDef(TokenRValInitDefrVal);
  3648. else if (rVal is TokenRValIsType TokenRValIsTyperVal)
  3649. cVal = GenerateFromRValIsType(TokenRValIsTyperVal);
  3650. else if (rVal is TokenRValList TokenRValListrVal)
  3651. cVal = GenerateFromRValList(TokenRValListrVal);
  3652. else if (rVal is TokenRValNewArIni TokenRValNewArInirVal)
  3653. cVal = GenerateFromRValNewArIni(TokenRValNewArInirVal);
  3654. else if (rVal is TokenRValOpBin TokenRValOpBinrVal)
  3655. cVal = GenerateFromRValOpBin(TokenRValOpBinrVal);
  3656. else if (rVal is TokenRValOpUn TokenRValOpUnrVal)
  3657. cVal = GenerateFromRValOpUn(TokenRValOpUnrVal);
  3658. else if (rVal is TokenRValParen TokenRValParenrVal)
  3659. cVal = GenerateFromRValParen(TokenRValParenrVal);
  3660. else if (rVal is TokenRValRot TokenRValRotrVal)
  3661. cVal = GenerateFromRValRot(TokenRValRotrVal);
  3662. else if (rVal is TokenRValThis TokenRValThisrVal)
  3663. cVal = GenerateFromRValThis(TokenRValThisrVal);
  3664. else if (rVal is TokenRValUndef TokenRValUndefrVal)
  3665. cVal = GenerateFromRValUndef(TokenRValUndefrVal);
  3666. else if (rVal is TokenRValVec TokenRValVecrVal)
  3667. cVal = GenerateFromRValVec(TokenRValVecrVal);
  3668. else if (rVal is TokenLVal TokenLValrVal)
  3669. cVal = GenerateFromLVal(TokenLValrVal, argsig);
  3670. if(cVal == null)
  3671. throw new Exception("bad rval class " + rVal.GetType().ToString());
  3672. // Sanity check.
  3673. if(!youveAnError)
  3674. {
  3675. if(cVal.type == null)
  3676. throw new Exception("cVal has no type " + cVal.GetType());
  3677. string cValType = cVal.type.ToString();
  3678. string rValType = rVal.GetRValType(this, argsig).ToString();
  3679. if(cValType == "bool")
  3680. cValType = "integer";
  3681. if(rValType == "bool")
  3682. rValType = "integer";
  3683. if(cValType != rValType)
  3684. {
  3685. throw new Exception("cVal.type " + cValType + " != rVal.type " + rValType +
  3686. " (" + rVal.GetType().Name + " " + rVal.SrcLoc + ")");
  3687. }
  3688. }
  3689. return cVal;
  3690. }
  3691. /**
  3692. * @brief compute the result of a binary operator (eg, add, subtract, multiply, lessthan)
  3693. * @param token = binary operator token, includes the left and right operands
  3694. * @returns where the resultant R-value is as something that doesn't have side effects
  3695. */
  3696. private CompValu GenerateFromRValOpBin(TokenRValOpBin token)
  3697. {
  3698. CompValu left, right;
  3699. string opcodeIndex = token.opcode.ToString();
  3700. // Comma operators are special, as they say to compute the left-hand value and
  3701. // discard it, then compute the right-hand argument and that is the result.
  3702. if(opcodeIndex == ",")
  3703. {
  3704. // Compute left-hand operand but throw away result.
  3705. GenerateFromRVal(token.rValLeft);
  3706. // Compute right-hand operand and that is the value of the expression.
  3707. return GenerateFromRVal(token.rValRight);
  3708. }
  3709. // Simple overwriting assignments are their own special case,
  3710. // as we want to cast the R-value to the type of the L-value.
  3711. // And in the case of delegates, we want to use the arg signature
  3712. // of the delegate to select which overloaded method to use.
  3713. if(opcodeIndex == "=")
  3714. {
  3715. if(token.rValLeft is not TokenLVal)
  3716. {
  3717. ErrorMsg(token, "invalid L-value for =");
  3718. return GenerateFromRVal(token.rValLeft);
  3719. }
  3720. left = GenerateFromLVal((TokenLVal)token.rValLeft);
  3721. right = Trivialize(GenerateFromRVal(token.rValRight, left.GetArgTypes()), token.rValRight);
  3722. left.PopPre(this, token.rValLeft);
  3723. right.PushVal(this, token.rValRight, left.type); // push (left.type)right
  3724. left.PopPost(this, token.rValLeft); // pop to left
  3725. return left;
  3726. }
  3727. // There are String.Concat() methods available for 2, 3 and 4 operands.
  3728. // So see if we have a string concat op and optimize if so.
  3729. if((opcodeIndex == "+") ||
  3730. ((opcodeIndex == "+=") &&
  3731. (token.rValLeft is TokenLVal) &&
  3732. (token.rValLeft.GetRValType(this, null) is TokenTypeStr)))
  3733. {
  3734. // We are adding something. Maybe it's a bunch of strings together.
  3735. List<TokenRVal> scorvs = new ();
  3736. if(StringConcatOperands(token.rValLeft, token.rValRight, scorvs, token.opcode))
  3737. {
  3738. // Evaluate all the operands, right-to-left on purpose per LSL scripting.
  3739. int i;
  3740. int n = scorvs.Count;
  3741. CompValu[] scocvs = new CompValu[n];
  3742. for(i = n; --i >= 0;)
  3743. {
  3744. scocvs[i] = GenerateFromRVal(scorvs[i]);
  3745. if(i > 0)
  3746. scocvs[i] = Trivialize(scocvs[i], scorvs[i]);
  3747. }
  3748. /*
  3749. * Figure out where to put the result.
  3750. * A temp if '+', or back in original L-value if '+='.
  3751. */
  3752. CompValu retcv;
  3753. if(opcodeIndex == "+")
  3754. {
  3755. retcv = new CompValuTemp(new TokenTypeStr(token.opcode), this);
  3756. }
  3757. else
  3758. {
  3759. retcv = GenerateFromLVal((TokenLVal)token.rValLeft);
  3760. }
  3761. retcv.PopPre(this, token);
  3762. // Call the String.Concat() methods, passing operands in left-to-right order.
  3763. // Force a cast to string (retcv.type) for each operand.
  3764. ++i;
  3765. scocvs[i].PushVal(this, scorvs[i], retcv.type);
  3766. while(i + 3 < n)
  3767. {
  3768. ++i;
  3769. scocvs[i].PushVal(this, scorvs[i], retcv.type);
  3770. ++i;
  3771. scocvs[i].PushVal(this, scorvs[i], retcv.type);
  3772. ++i;
  3773. scocvs[i].PushVal(this, scorvs[i], retcv.type);
  3774. ilGen.Emit(scorvs[i], OpCodes.Call, stringConcat4MethodInfo);
  3775. }
  3776. if(i + 2 < n)
  3777. {
  3778. ++i;
  3779. scocvs[i].PushVal(this, scorvs[i], retcv.type);
  3780. ++i;
  3781. scocvs[i].PushVal(this, scorvs[i], retcv.type);
  3782. ilGen.Emit(scorvs[i], OpCodes.Call, stringConcat3MethodInfo);
  3783. }
  3784. if(i + 1 < n)
  3785. {
  3786. ++i;
  3787. scocvs[i].PushVal(this, scorvs[i], retcv.type);
  3788. ilGen.Emit(scorvs[i], OpCodes.Call, stringConcat2MethodInfo);
  3789. }
  3790. // Put the result where we want it and return where we put it.
  3791. retcv.PopPost(this, token);
  3792. return retcv;
  3793. }
  3794. }
  3795. // If "&&&", it is a short-circuiting AND.
  3796. // Compute left-hand operand and if true, compute right-hand operand.
  3797. if(opcodeIndex == "&&&")
  3798. {
  3799. bool rightVal;
  3800. left = GenerateFromRVal(token.rValLeft);
  3801. if(!IsConstBoolExpr(left, out bool leftVal))
  3802. {
  3803. ScriptMyLabel falseLabel = ilGen.DefineLabel("ssandfalse");
  3804. left.PushVal(this, tokenTypeBool);
  3805. ilGen.Emit(token, OpCodes.Brfalse, falseLabel);
  3806. right = GenerateFromRVal(token.rValRight);
  3807. if(!IsConstBoolExpr(right, out rightVal))
  3808. {
  3809. right.PushVal(this, tokenTypeBool);
  3810. goto donessand;
  3811. }
  3812. if(!rightVal)
  3813. {
  3814. ilGen.MarkLabel(falseLabel);
  3815. return new CompValuInteger(new TokenTypeInt(token.rValLeft), 0);
  3816. }
  3817. ilGen.Emit(token, OpCodes.Ldc_I4_1);
  3818. donessand:
  3819. ScriptMyLabel doneLabel = ilGen.DefineLabel("ssanddone");
  3820. ilGen.Emit(token, OpCodes.Br, doneLabel);
  3821. ilGen.MarkLabel(falseLabel);
  3822. ilGen.Emit(token, OpCodes.Ldc_I4_0);
  3823. ilGen.MarkLabel(doneLabel);
  3824. CompValuTemp retRVal = new (new TokenTypeInt(token), this);
  3825. retRVal.Pop(this, token);
  3826. return retRVal;
  3827. }
  3828. if(!leftVal)
  3829. {
  3830. return new CompValuInteger(new TokenTypeInt(token.rValLeft), 0);
  3831. }
  3832. right = GenerateFromRVal(token.rValRight);
  3833. if(!IsConstBoolExpr(right, out rightVal))
  3834. {
  3835. right.PushVal(this, tokenTypeBool);
  3836. CompValuTemp retRVal = new (new TokenTypeInt(token), this);
  3837. retRVal.Pop(this, token);
  3838. return retRVal;
  3839. }
  3840. return new CompValuInteger(new TokenTypeInt(token), rightVal ? 1 : 0);
  3841. }
  3842. // If "|||", it is a short-circuiting OR.
  3843. // Compute left-hand operand and if false, compute right-hand operand.
  3844. if(opcodeIndex == "|||")
  3845. {
  3846. bool rightVal;
  3847. left = GenerateFromRVal(token.rValLeft);
  3848. if(!IsConstBoolExpr(left, out bool leftVal))
  3849. {
  3850. ScriptMyLabel trueLabel = ilGen.DefineLabel("ssortrue");
  3851. left.PushVal(this, tokenTypeBool);
  3852. ilGen.Emit(token, OpCodes.Brtrue, trueLabel);
  3853. right = GenerateFromRVal(token.rValRight);
  3854. if(!IsConstBoolExpr(right, out rightVal))
  3855. {
  3856. right.PushVal(this, tokenTypeBool);
  3857. goto donessor;
  3858. }
  3859. if(rightVal)
  3860. {
  3861. ilGen.MarkLabel(trueLabel);
  3862. return new CompValuInteger(new TokenTypeInt(token.rValLeft), 1);
  3863. }
  3864. ilGen.Emit(token, OpCodes.Ldc_I4_0);
  3865. donessor:
  3866. ScriptMyLabel doneLabel = ilGen.DefineLabel("ssanddone");
  3867. ilGen.Emit(token, OpCodes.Br, doneLabel);
  3868. ilGen.MarkLabel(trueLabel);
  3869. ilGen.Emit(token, OpCodes.Ldc_I4_1);
  3870. ilGen.MarkLabel(doneLabel);
  3871. CompValuTemp retRVal = new (new TokenTypeInt(token), this);
  3872. retRVal.Pop(this, token);
  3873. return retRVal;
  3874. }
  3875. if(leftVal)
  3876. {
  3877. return new CompValuInteger(new TokenTypeInt(token.rValLeft), 1);
  3878. }
  3879. right = GenerateFromRVal(token.rValRight);
  3880. if(!IsConstBoolExpr(right, out rightVal))
  3881. {
  3882. right.PushVal(this, tokenTypeBool);
  3883. CompValuTemp retRVal = new (new TokenTypeInt(token), this);
  3884. retRVal.Pop(this, token);
  3885. return retRVal;
  3886. }
  3887. return new CompValuInteger(new TokenTypeInt(token), rightVal ? 1 : 0);
  3888. }
  3889. // Computation of some sort, compute right-hand operand value then left-hand value
  3890. // because LSL is supposed to be right-to-left evaluation.
  3891. right = Trivialize(GenerateFromRVal(token.rValRight), token.rValRight);
  3892. // If left is a script-defined class and there is a method with the operator's name,
  3893. // convert this to a call to that method with the right value as its single parameter.
  3894. // Except don't if the right value is 'undef' so they can always compare to undef.
  3895. TokenType leftType = token.rValLeft.GetRValType(this, null);
  3896. if((leftType is TokenTypeSDTypeClass sdtType) && right.type is not TokenTypeUndef)
  3897. {
  3898. TokenDeclSDTypeClass sdtDecl = sdtType.decl;
  3899. TokenType[] argsig = [right.type];
  3900. TokenName funcName = new (token.opcode, "$op" + opcodeIndex);
  3901. TokenDeclVar declFunc = FindThisMember(sdtDecl, funcName, argsig);
  3902. if(declFunc != null)
  3903. {
  3904. CheckAccess(declFunc, funcName);
  3905. left = GenerateFromRVal(token.rValLeft);
  3906. CompValu method = AccessInstanceMember(declFunc, left, token, false);
  3907. CompValu[] argRVals = [right];
  3908. return GenerateACall(method, argRVals, token);
  3909. }
  3910. }
  3911. // Formulate key string for binOpStrings = (lefttype)(operator)(righttype)
  3912. string leftIndex = leftType.ToString();
  3913. string rightIndex = right.type.ToString();
  3914. string key = leftIndex + opcodeIndex + rightIndex;
  3915. // If that key exists in table, then the operation is defined between those types
  3916. // ... and it produces an R-value of type as given in the table.
  3917. if (BinOpStr.defined.TryGetValue(key, out BinOpStr binOpStr))
  3918. {
  3919. // If table contained an explicit assignment type like +=, output the statement without
  3920. // casting the L-value, then return the L-value as the resultant value.
  3921. //
  3922. // Make sure we don't include comparisons (such as ==, >=, etc).
  3923. // Nothing like +=, -=, %=, etc, generate a boolean, only the comparisons.
  3924. if ((binOpStr.outtype != typeof(bool)) && opcodeIndex.EndsWith('=') && (opcodeIndex != "!="))
  3925. {
  3926. if (token.rValLeft is not TokenLVal)
  3927. {
  3928. ErrorMsg(token.rValLeft, "invalid L-value");
  3929. return GenerateFromRVal(token.rValLeft);
  3930. }
  3931. left = GenerateFromLVal((TokenLVal)token.rValLeft);
  3932. binOpStr.emitBO(this, token, left, right, left);
  3933. return left;
  3934. }
  3935. // It's of the form left binop right.
  3936. // Compute left, perform operation then put result in a temp.
  3937. left = GenerateFromRVal(token.rValLeft);
  3938. CompValu retRVal = new CompValuTemp(TokenType.FromSysType(token.opcode, binOpStr.outtype), this);
  3939. binOpStr.emitBO(this, token, left, right, retRVal);
  3940. return retRVal;
  3941. }
  3942. // Nothing in the table, check for comparing object pointers because of the myriad of types possible.
  3943. // This will compare list pointers, null pointers, script-defined type pointers, array pointers, etc.
  3944. // It will show equal iff the memory addresses are equal and that is good enough.
  3945. if (!leftType.ToSysType().IsValueType && !right.type.ToSysType().IsValueType && ((opcodeIndex == "==") || (opcodeIndex == "!=")))
  3946. {
  3947. CompValuTemp retRVal = new (new TokenTypeInt(token), this);
  3948. left = GenerateFromRVal(token.rValLeft);
  3949. left.PushVal(this, token.rValLeft);
  3950. right.PushVal(this, token.rValRight);
  3951. ilGen.Emit(token, OpCodes.Ceq);
  3952. if(opcodeIndex == "!=")
  3953. {
  3954. ilGen.Emit(token, OpCodes.Ldc_I4_1);
  3955. ilGen.Emit(token, OpCodes.Xor);
  3956. }
  3957. retRVal.Pop(this, token);
  3958. return retRVal;
  3959. }
  3960. // If the opcode ends with "=", it may be something like "+=".
  3961. // So look up the key as if we didn't have the "=" to tell us if the operation is legal.
  3962. // Also, the binary operation's output type must be the same as the L-value type.
  3963. // Likewise, integer += float not allowed because result is float, but float += integer is ok.
  3964. if(opcodeIndex.EndsWith('='))
  3965. {
  3966. string op = opcodeIndex[..^1];
  3967. key = leftIndex + op + rightIndex;
  3968. if(BinOpStr.defined.TryGetValue(key, out binOpStr))
  3969. {
  3970. if(token.rValLeft is not TokenLVal)
  3971. {
  3972. ErrorMsg(token, "invalid L-value for <op>=");
  3973. return GenerateFromRVal(token.rValLeft);
  3974. }
  3975. if(!binOpStr.rmwOK)
  3976. {
  3977. ErrorMsg(token, "<op>= not allowed: " + leftIndex + " " + opcodeIndex + " " + rightIndex);
  3978. return new CompValuVoid(token);
  3979. }
  3980. // Now we know for something like %= that left%right is legal for the types given.
  3981. left = GenerateFromLVal((TokenLVal)token.rValLeft);
  3982. if(binOpStr.outtype == leftType.ToSysType())
  3983. {
  3984. binOpStr.emitBO(this, token, left, right, left);
  3985. }
  3986. else
  3987. {
  3988. CompValu temp = new CompValuTemp(TokenType.FromSysType(token, binOpStr.outtype), this);
  3989. binOpStr.emitBO(this, token, left, right, temp);
  3990. left.PopPre(this, token);
  3991. if(op == "*")
  3992. temp.PushVal(this, token, leftType, true);
  3993. else
  3994. temp.PushVal(this, token, leftType);
  3995. left.PopPost(this, token);
  3996. }
  3997. return left;
  3998. }
  3999. }
  4000. // Can't find it, oh well.
  4001. ErrorMsg(token, "op not defined: " + leftIndex + " " + opcodeIndex + " " + rightIndex);
  4002. return new CompValuVoid(token);
  4003. }
  4004. /**
  4005. * @brief Queue the given operands to the end of the scos list.
  4006. * If it can be broken down into more string concat operands, do so.
  4007. * Otherwise, just push it as one operand.
  4008. * @param leftRVal = left-hand operand of a '+' operation
  4009. * @param rightRVal = right-hand operand of a '+' operation
  4010. * @param scos = left-to-right list of operands for the string concat so far
  4011. * @param addop = the add operator token (either '+' or '+=')
  4012. * @returns false: neither operand is a string, nothing added to scos
  4013. * true: scos = updated with leftRVal then rightRVal added onto the end, possibly broken down further
  4014. */
  4015. private bool StringConcatOperands(TokenRVal leftRVal, TokenRVal rightRVal, List<TokenRVal> scos, TokenKw addop)
  4016. {
  4017. /*
  4018. * If neither operand is a string (eg, float+integer), then the result isn't going to be a string.
  4019. */
  4020. TokenType leftType = leftRVal.GetRValType(this, null);
  4021. TokenType rightType = rightRVal.GetRValType(this, null);
  4022. if(leftType is not TokenTypeStr && rightType is not TokenTypeStr)
  4023. return false;
  4024. // Also, list+string => list so reject that too.
  4025. // Also, string+list => list so reject that too.
  4026. if(leftType is TokenTypeList)
  4027. return false;
  4028. if(rightType is TokenTypeList)
  4029. return false;
  4030. // Append values to the end of the list in left-to-right order.
  4031. // If value is formed from a something+something => string,
  4032. // push them as separate values, otherwise push as one value.
  4033. StringConcatOperand(leftType, leftRVal, scos);
  4034. StringConcatOperand(rightType, rightRVal, scos);
  4035. // Maybe constant strings can be concatted.
  4036. try
  4037. {
  4038. int len;
  4039. while(((len = scos.Count) >= 2) &&
  4040. ((leftRVal = scos[len - 2]) is TokenRValConst) &&
  4041. ((rightRVal = scos[len - 1]) is TokenRValConst))
  4042. {
  4043. object sum = addop.binOpConst(((TokenRValConst)leftRVal).val,
  4044. ((TokenRValConst)rightRVal).val);
  4045. scos[len - 2] = new TokenRValConst(addop, sum);
  4046. scos.RemoveAt(len - 1);
  4047. }
  4048. }
  4049. catch
  4050. {
  4051. }
  4052. // We pushed some string stuff.
  4053. return true;
  4054. }
  4055. /**
  4056. * @brief Queue the given operand to the end of the scos list.
  4057. * If it can be broken down into more string concat operands, do so.
  4058. * Otherwise, just push it as one operand.
  4059. * @param type = rVal's resultant type
  4060. * @param rVal = operand to examine
  4061. * @param scos = left-to-right list of operands for the string concat so far
  4062. * @returns with scos = updated with rVal added onto the end, possibly broken down further
  4063. */
  4064. private void StringConcatOperand(TokenType type, TokenRVal rVal, List<TokenRVal> scos)
  4065. {
  4066. bool didOne;
  4067. do
  4068. {
  4069. didOne = false;
  4070. rVal = rVal.TryComputeConstant(LookupBodyConstants, ref didOne);
  4071. } while(didOne);
  4072. if(type is not TokenTypeStr)
  4073. goto pushasis;
  4074. if(rVal is not TokenRValOpBin)
  4075. goto pushasis;
  4076. TokenRValOpBin rValOpBin = (TokenRValOpBin)rVal;
  4077. if(rValOpBin.opcode is not TokenKwAdd)
  4078. goto pushasis;
  4079. if(StringConcatOperands(rValOpBin.rValLeft, rValOpBin.rValRight, scos, rValOpBin.opcode))
  4080. return;
  4081. pushasis:
  4082. scos.Add(rVal);
  4083. }
  4084. /**
  4085. * @brief compute the result of an unary operator
  4086. * @param token = unary operator token, includes the operand
  4087. * @returns where the resultant R-value is
  4088. */
  4089. private CompValu GenerateFromRValOpUn(TokenRValOpUn token)
  4090. {
  4091. CompValu inRVal = GenerateFromRVal(token.rVal);
  4092. // Script-defined types can define their own methods to handle unary operators.
  4093. if (inRVal.type is TokenTypeSDTypeClass sdtType)
  4094. {
  4095. TokenDeclSDTypeClass sdtDecl = sdtType.decl;
  4096. TokenName funcName = new (token.opcode, "$op" + token.opcode.ToString());
  4097. TokenDeclVar declFunc = FindThisMember(sdtDecl, funcName, zeroArgs);
  4098. if (declFunc != null)
  4099. {
  4100. CheckAccess(declFunc, funcName);
  4101. CompValu method = AccessInstanceMember(declFunc, inRVal, token, false);
  4102. return GenerateACall(method, zeroCompValus, token);
  4103. }
  4104. }
  4105. // Otherwise use the default.
  4106. return UnOpGenerate(inRVal, token.opcode);
  4107. }
  4108. /**
  4109. * @brief postfix operator -- this returns the type and location of the resultant value
  4110. */
  4111. private CompValu GenerateFromRValAsnPost(TokenRValAsnPost asnPost)
  4112. {
  4113. CompValu lVal = GenerateFromLVal(asnPost.lVal);
  4114. // Make up a temp to save original value in.
  4115. CompValuTemp result = new (lVal.type, this);
  4116. // Prepare to pop incremented value back into variable being incremented.
  4117. lVal.PopPre(this, asnPost.lVal);
  4118. // Copy original value to temp and leave value on stack.
  4119. lVal.PushVal(this, asnPost.lVal);
  4120. ilGen.Emit(asnPost.lVal, OpCodes.Dup);
  4121. result.Pop(this, asnPost.lVal);
  4122. // Perform the ++/--.
  4123. if((lVal.type is TokenTypeChar) || (lVal.type is TokenTypeInt))
  4124. {
  4125. ilGen.Emit(asnPost, OpCodes.Ldc_I4_1);
  4126. }
  4127. else if(lVal.type is TokenTypeFloat)
  4128. {
  4129. ilGen.Emit(asnPost, OpCodes.Ldc_R4, 1.0f);
  4130. }
  4131. else
  4132. {
  4133. lVal.PopPost(this, asnPost.lVal);
  4134. ErrorMsg(asnPost, "invalid type for " + asnPost.postfix.ToString());
  4135. return lVal;
  4136. }
  4137. switch(asnPost.postfix.ToString())
  4138. {
  4139. case "++":
  4140. {
  4141. ilGen.Emit(asnPost, OpCodes.Add);
  4142. break;
  4143. }
  4144. case "--":
  4145. {
  4146. ilGen.Emit(asnPost, OpCodes.Sub);
  4147. break;
  4148. }
  4149. default:
  4150. throw new Exception("unknown asnPost op");
  4151. }
  4152. // Store new value in original variable.
  4153. lVal.PopPost(this, asnPost.lVal);
  4154. return result;
  4155. }
  4156. /**
  4157. * @brief prefix operator -- this returns the type and location of the resultant value
  4158. */
  4159. private CompValu GenerateFromRValAsnPre(TokenRValAsnPre asnPre)
  4160. {
  4161. CompValu lVal = GenerateFromLVal(asnPre.lVal);
  4162. // Make up a temp to put result in.
  4163. CompValuTemp result = new (lVal.type, this);
  4164. // Prepare to pop incremented value back into variable being incremented.
  4165. lVal.PopPre(this, asnPre.lVal);
  4166. // Push original value.
  4167. lVal.PushVal(this, asnPre.lVal);
  4168. // Perform the ++/--.
  4169. if((lVal.type is TokenTypeChar) || (lVal.type is TokenTypeInt))
  4170. {
  4171. ilGen.Emit(asnPre, OpCodes.Ldc_I4_1);
  4172. }
  4173. else if(lVal.type is TokenTypeFloat)
  4174. {
  4175. ilGen.Emit(asnPre, OpCodes.Ldc_R4, 1.0f);
  4176. }
  4177. else
  4178. {
  4179. lVal.PopPost(this, asnPre.lVal);
  4180. ErrorMsg(asnPre, "invalid type for " + asnPre.prefix.ToString());
  4181. return lVal;
  4182. }
  4183. switch(asnPre.prefix.ToString())
  4184. {
  4185. case "++":
  4186. {
  4187. ilGen.Emit(asnPre, OpCodes.Add);
  4188. break;
  4189. }
  4190. case "--":
  4191. {
  4192. ilGen.Emit(asnPre, OpCodes.Sub);
  4193. break;
  4194. }
  4195. default:
  4196. throw new Exception("unknown asnPre op");
  4197. }
  4198. // Store new value in temp variable, keeping new value on stack.
  4199. ilGen.Emit(asnPre.lVal, OpCodes.Dup);
  4200. result.Pop(this, asnPre.lVal);
  4201. // Store new value in original variable.
  4202. lVal.PopPost(this, asnPre.lVal);
  4203. return result;
  4204. }
  4205. /**
  4206. * @brief Generate code that calls a function or object's method.
  4207. * @returns where the call's return value is stored (a TokenTypeVoid if void)
  4208. */
  4209. private CompValu GenerateFromRValCall(TokenRValCall call)
  4210. {
  4211. CompValu method;
  4212. CompValu[] argRVals;
  4213. int i, nargs;
  4214. TokenRVal arg;
  4215. TokenType[] argTypes;
  4216. // Compute the values of all the function's call arguments.
  4217. // Save where the computation results are in the argRVals[] array.
  4218. // Might as well build the argument signature from the argument types, too.
  4219. nargs = call.nArgs;
  4220. argRVals = new CompValu[nargs];
  4221. argTypes = new TokenType[nargs];
  4222. if(nargs > 0)
  4223. {
  4224. i = 0;
  4225. for(arg = call.args; arg != null; arg = (TokenRVal)arg.nextToken)
  4226. {
  4227. argRVals[i] = GenerateFromRVal(arg);
  4228. argTypes[i] = argRVals[i].type;
  4229. i++;
  4230. }
  4231. }
  4232. // Get function/method's entrypoint that matches the call argument types.
  4233. method = GenerateFromRVal(call.meth, argTypes);
  4234. if(method == null)
  4235. return null;
  4236. return GenerateACall(method, argRVals, call);
  4237. }
  4238. /**
  4239. * @brief Generate call to a function/method.
  4240. * @param method = function/method being called
  4241. * @param argVRVals = its call parameters (zero length if none)
  4242. * @param call = where in source code call is being made from (for error messages)
  4243. * @returns type and location of return value (CompValuVoid if none)
  4244. */
  4245. private CompValu GenerateACall(CompValu method, CompValu[] argRVals, Token call)
  4246. {
  4247. CompValuTemp result;
  4248. int i, nArgs;
  4249. TokenType retType;
  4250. TokenType[] argTypes;
  4251. // Must be some kind of callable.
  4252. retType = method.GetRetType(); // TokenTypeVoid if void; null means a variable
  4253. if(retType == null)
  4254. {
  4255. ErrorMsg(call, "must be a delegate, function or method");
  4256. return new CompValuVoid(call);
  4257. }
  4258. // Get a location for return value.
  4259. if(retType is TokenTypeVoid)
  4260. {
  4261. result = new CompValuVoid(call);
  4262. }
  4263. else
  4264. {
  4265. result = new CompValuTemp(retType, this);
  4266. }
  4267. // Make sure all arguments are trivial, ie, don't involve their own call labels.
  4268. // For any that aren't, output code to calculate the arg and put in a temporary.
  4269. nArgs = argRVals.Length;
  4270. for(i = 0; i < nArgs; i++)
  4271. {
  4272. if(!argRVals[i].IsReadTrivial(this, call))
  4273. {
  4274. argRVals[i] = Trivialize(argRVals[i], call);
  4275. }
  4276. }
  4277. // Inline functions know how to generate their own call.
  4278. if (method is CompValuInline inline)
  4279. {
  4280. inline.declInline.CodeGen(this, call, result, argRVals);
  4281. return result;
  4282. }
  4283. // Push whatever the function/method needs as a this argument, if anything.
  4284. method.CallPre(this, call);
  4285. // Push the script-visible args, left-to-right.
  4286. argTypes = method.GetArgTypes();
  4287. for(i = 0; i < nArgs; i++)
  4288. {
  4289. if(argTypes == null)
  4290. {
  4291. argRVals[i].PushVal(this, call);
  4292. }
  4293. else
  4294. {
  4295. argRVals[i].PushVal(this, call, argTypes[i]);
  4296. }
  4297. }
  4298. // Now output call instruction.
  4299. method.CallPost(this, call);
  4300. // Deal with the return value (if any), by putting it in 'result'.
  4301. result.Pop(this, call, retType);
  4302. return result;
  4303. }
  4304. /**
  4305. * @brief This is needed to avoid nesting call labels around non-trivial properties.
  4306. * It should be used for the second (and later) operands.
  4307. * Note that a 'call' is considered an operator, so all arguments of a call
  4308. * should be trivialized, but the method itself does not need to be.
  4309. */
  4310. public CompValu Trivialize(CompValu operand, Token errorAt)
  4311. {
  4312. if(operand.IsReadTrivial(this, errorAt))
  4313. return operand;
  4314. CompValuTemp temp = new (operand.type, this);
  4315. operand.PushVal(this, errorAt);
  4316. temp.Pop(this, errorAt);
  4317. return temp;
  4318. }
  4319. /**
  4320. * @brief Generate code that casts a value to a particular type.
  4321. * @returns where the result of the conversion is stored.
  4322. */
  4323. private CompValu GenerateFromRValCast(TokenRValCast cast)
  4324. {
  4325. // If casting to a delegate type, use the argment signature
  4326. // of the delegate to help select the function/method, eg,
  4327. // '(delegate string(integer))ToString'
  4328. // will select 'string ToString(integer x)'
  4329. // instaead of 'string ToString(float x)' or anything else
  4330. TokenType[] argsig = null;
  4331. TokenType outType = cast.castTo;
  4332. if(outType is TokenTypeSDTypeDelegate TokenTypeSDTypeDelegateoutType)
  4333. {
  4334. argsig = TokenTypeSDTypeDelegateoutType.decl.GetArgTypes();
  4335. }
  4336. // Generate the value that is being cast.
  4337. // If the value is already the requested type, just use it as is.
  4338. CompValu inRVal = GenerateFromRVal(cast.rVal, argsig);
  4339. if(inRVal.type == outType)
  4340. return inRVal;
  4341. // Different type, generate casting code, putting the result in a temp of the output type.
  4342. CompValu outRVal = new CompValuTemp(outType, this);
  4343. outRVal.PopPre(this, cast);
  4344. inRVal.PushVal(this, cast, outType, true);
  4345. outRVal.PopPost(this, cast);
  4346. return outRVal;
  4347. }
  4348. /**
  4349. * @brief Compute conditional expression value.
  4350. * @returns type and location of computed value.
  4351. */
  4352. private CompValu GenerateFromRValCondExpr(TokenRValCondExpr rValCondExpr)
  4353. {
  4354. CompValu condValu = GenerateFromRVal(rValCondExpr.condExpr);
  4355. if (IsConstBoolExpr(condValu, out bool condVal))
  4356. {
  4357. return GenerateFromRVal(condVal ? rValCondExpr.trueExpr : rValCondExpr.falseExpr);
  4358. }
  4359. ScriptMyLabel falseLabel = ilGen.DefineLabel("condexfalse");
  4360. ScriptMyLabel doneLabel = ilGen.DefineLabel("condexdone");
  4361. condValu.PushVal(this, rValCondExpr.condExpr, tokenTypeBool);
  4362. ilGen.Emit(rValCondExpr, OpCodes.Brfalse, falseLabel);
  4363. CompValu trueValu = GenerateFromRVal(rValCondExpr.trueExpr);
  4364. trueValu.PushVal(this, rValCondExpr.trueExpr);
  4365. ilGen.Emit(rValCondExpr, OpCodes.Br, doneLabel);
  4366. ilGen.MarkLabel(falseLabel);
  4367. CompValu falseValu = GenerateFromRVal(rValCondExpr.falseExpr);
  4368. falseValu.PushVal(this, rValCondExpr.falseExpr);
  4369. if(trueValu.type.GetType() != falseValu.type.GetType())
  4370. {
  4371. ErrorMsg(rValCondExpr, "? operands " + trueValu.type.ToString() + " : " +
  4372. falseValu.type.ToString() + " must be of same type");
  4373. }
  4374. ilGen.MarkLabel(doneLabel);
  4375. CompValuTemp retRVal = new (trueValu.type, this);
  4376. retRVal.Pop(this, rValCondExpr);
  4377. return retRVal;
  4378. }
  4379. /**
  4380. * @brief Constant in the script somewhere
  4381. * @returns where the constants value is stored
  4382. */
  4383. private static CompValu GenerateFromRValConst(TokenRValConst rValConst)
  4384. {
  4385. switch(rValConst.type)
  4386. {
  4387. case TokenRValConstType.CHAR:
  4388. {
  4389. return new CompValuChar(new TokenTypeChar(rValConst), (char)(rValConst.val));
  4390. }
  4391. case TokenRValConstType.FLOAT:
  4392. {
  4393. return new CompValuFloat(new TokenTypeFloat(rValConst), (double)(rValConst.val));
  4394. }
  4395. case TokenRValConstType.INT:
  4396. {
  4397. return new CompValuInteger(new TokenTypeInt(rValConst), (int)(rValConst.val));
  4398. }
  4399. case TokenRValConstType.KEY:
  4400. {
  4401. return new CompValuString(new TokenTypeKey(rValConst), (string)(rValConst.val));
  4402. }
  4403. case TokenRValConstType.STRING:
  4404. {
  4405. return new CompValuString(new TokenTypeStr(rValConst), (string)(rValConst.val));
  4406. }
  4407. }
  4408. throw new Exception("unknown constant type " + rValConst.val.GetType());
  4409. }
  4410. /**
  4411. * @brief generate a new list object
  4412. * @param rValList = an rVal to create it from
  4413. */
  4414. private CompValu GenerateFromRValList(TokenRValList rValList)
  4415. {
  4416. // Compute all element values and remember where we put them.
  4417. // Do it right-to-left as customary for LSL scripts.
  4418. int i = 0;
  4419. TokenRVal lastRVal = null;
  4420. for(TokenRVal val = rValList.rVal; val != null; val = (TokenRVal)val.nextToken)
  4421. {
  4422. i++;
  4423. val.prevToken = lastRVal;
  4424. lastRVal = val;
  4425. }
  4426. CompValu[] vals = new CompValu[i];
  4427. for(TokenRVal val = lastRVal; val != null; val = (TokenRVal)val.prevToken)
  4428. {
  4429. vals[--i] = GenerateFromRVal(val);
  4430. }
  4431. // This is the temp that will hold the created list.
  4432. CompValuTemp newList = new (new TokenTypeList(rValList.rVal), this);
  4433. // Create a temp object[] array to hold all the initial values.
  4434. ilGen.Emit(rValList, OpCodes.Ldc_I4, rValList.nItems);
  4435. ilGen.Emit(rValList, OpCodes.Newarr, typeof(object));
  4436. // Populate the array.
  4437. i = 0;
  4438. for(TokenRVal val = rValList.rVal; val != null; val = (TokenRVal)val.nextToken)
  4439. {
  4440. // Get pointer to temp array object.
  4441. ilGen.Emit(rValList, OpCodes.Dup);
  4442. // Get index in that array.
  4443. ilGen.Emit(rValList, OpCodes.Ldc_I4, i);
  4444. // Store initialization value in array location.
  4445. // However, floats and ints need to be converted to LSL_Float and LSL_Integer,
  4446. // or things like llSetPayPrice() will puque when they try to cast the elements
  4447. // to LSL_Float or LSL_Integer. Likewise with string/LSL_String.
  4448. //
  4449. // Maybe it's already LSL-boxed so we don't do anything with it except make sure
  4450. // it is an object, not a struct.
  4451. CompValu eRVal = vals[i++];
  4452. eRVal.PushVal(this, val);
  4453. if(eRVal.type.ToLSLWrapType() == null)
  4454. {
  4455. if(eRVal.type is TokenTypeFloat)
  4456. {
  4457. ilGen.Emit(val, OpCodes.Newobj, lslFloatConstructorInfo);
  4458. ilGen.Emit(val, OpCodes.Box, typeof(LSL_Float));
  4459. }
  4460. else if (eRVal.type is TokenTypeInt)
  4461. {
  4462. ilGen.Emit(val, OpCodes.Newobj, lslIntegerConstructorInfo);
  4463. ilGen.Emit(val, OpCodes.Box, typeof(LSL_Integer));
  4464. }
  4465. else if (eRVal.type is TokenTypeBool)
  4466. {
  4467. ilGen.Emit(val, OpCodes.Newobj, lslIntegerConstructorInfo);
  4468. ilGen.Emit(val, OpCodes.Box, typeof(LSL_Integer));
  4469. }
  4470. else if ((eRVal.type is TokenTypeKey) || (eRVal.type is TokenTypeStr))
  4471. {
  4472. ilGen.Emit(val, OpCodes.Newobj, lslStringConstructorInfo);
  4473. ilGen.Emit(val, OpCodes.Box, typeof(LSL_String));
  4474. }
  4475. else if(eRVal.type.ToSysType().IsValueType)
  4476. {
  4477. ilGen.Emit(val, OpCodes.Box, eRVal.type.ToSysType());
  4478. }
  4479. }
  4480. else if(eRVal.type.ToLSLWrapType().IsValueType)
  4481. {
  4482. // Convert the LSL value structs to an object of the LSL-boxed type
  4483. ilGen.Emit(val, OpCodes.Box, eRVal.type.ToLSLWrapType());
  4484. }
  4485. ilGen.Emit(val, OpCodes.Stelem, typeof(object));
  4486. }
  4487. // Create new list object from temp initial value array (whose ref is still on the stack).
  4488. ilGen.Emit(rValList, OpCodes.Newobj, lslListConstructorInfo);
  4489. newList.Pop(this, rValList);
  4490. return newList;
  4491. }
  4492. /**
  4493. * @brief New array allocation with initializer expressions.
  4494. */
  4495. private CompValu GenerateFromRValNewArIni(TokenRValNewArIni rValNewArIni)
  4496. {
  4497. return MallocAndInitArray(rValNewArIni.arrayType, rValNewArIni.valueList);
  4498. }
  4499. /**
  4500. * @brief Mallocate and initialize an array from its initialization list.
  4501. * @param arrayType = type of the array to be allocated and initialized
  4502. * @param values = initialization value list used to size and initialize the array.
  4503. * @returns memory location of the resultant initialized array.
  4504. */
  4505. private CompValu MallocAndInitArray(TokenType arrayType, TokenList values)
  4506. {
  4507. TokenDeclSDTypeClass arrayDecl = ((TokenTypeSDTypeClass)arrayType).decl;
  4508. TokenType eleType = arrayDecl.arrayOfType;
  4509. int rank = arrayDecl.arrayOfRank;
  4510. // Get size of each of the dimensions by scanning the initialization value list
  4511. int[] dimSizes = new int[rank];
  4512. FillInDimSizes(dimSizes, 0, rank, values);
  4513. // Figure out where the array's $new() method is
  4514. TokenType[] newargsig = new TokenType[rank];
  4515. for(int k = 0; k < rank; k++)
  4516. {
  4517. newargsig[k] = tokenTypeInt;
  4518. }
  4519. TokenDeclVar newMeth = FindThisMember(arrayDecl, new TokenName(null, "$new"), newargsig);
  4520. // Output a call to malloc the array with all default values
  4521. // array = ArrayType.$new (dimSizes[0], dimSizes[1], ...)
  4522. CompValuTemp array = new (arrayType, this);
  4523. PushXMRInst();
  4524. for(int k = 0; k < rank; k++)
  4525. {
  4526. ilGen.Emit(values, OpCodes.Ldc_I4, dimSizes[k]);
  4527. }
  4528. ilGen.Emit(values, OpCodes.Call, newMeth.ilGen);
  4529. array.Pop(this, arrayType);
  4530. // Figure out where the array's Set() method is
  4531. TokenType[] setargsig = new TokenType[rank + 1];
  4532. for(int k = 0; k < rank; k++)
  4533. {
  4534. setargsig[k] = tokenTypeInt;
  4535. }
  4536. setargsig[rank] = eleType;
  4537. TokenDeclVar setMeth = FindThisMember(arrayDecl, new TokenName(null, "Set"), setargsig);
  4538. // Fill in the array with the initializer values
  4539. FillInInitVals(array, setMeth, dimSizes, 0, rank, values, eleType);
  4540. // The array is our resultant value
  4541. return array;
  4542. }
  4543. /**
  4544. * @brief Compute an array's dimensions given its initialization value list
  4545. * @param dimSizes = filled in with array's dimensions
  4546. * @param dimNo = what dimension the 'values' list applies to
  4547. * @param rank = total number of dimensions of the array
  4548. * @param values = list of values to initialize the array's 'dimNo' dimension with
  4549. * @returns with dimSizes[dimNo..rank-1] filled in
  4550. */
  4551. private static void FillInDimSizes(int[] dimSizes, int dimNo, int rank, TokenList values)
  4552. {
  4553. // the size of a dimension is the largest number of initializer elements at this level
  4554. // for dimNo 0, this is the number of elements in the top-level list
  4555. if(dimSizes[dimNo] < values.tl.Count)
  4556. dimSizes[dimNo] = values.tl.Count;
  4557. // see if there is another dimension to calculate
  4558. if(++dimNo < rank)
  4559. {
  4560. // its size is the size of the largest initializer list at the next inner level
  4561. foreach(Token val in values.tl)
  4562. {
  4563. if (val is TokenList subvals)
  4564. {
  4565. FillInDimSizes(dimSizes, dimNo, rank, subvals);
  4566. }
  4567. }
  4568. }
  4569. }
  4570. /**
  4571. * @brief Output code to fill in array's initialization values
  4572. * @param array = array to be filled in
  4573. * @param setMeth = the array's Set() method
  4574. * @param subscripts = holds subscripts being built
  4575. * @param dimNo = which dimension the 'values' are for
  4576. * @param values = list of initialization values for dimension 'dimNo'
  4577. * @param rank = number of dimensions of 'array'
  4578. * @param values = list of values to initialize the array's 'dimNo' dimension with
  4579. * @param eleType = the element's type
  4580. * @returns with code emitted to initialize array's [subscripts[0], ..., subscripts[dimNo-1], *, *, ...]
  4581. * dimNo and up completely filled ---^
  4582. */
  4583. private void FillInInitVals(CompValu array, TokenDeclVar setMeth, int[] subscripts, int dimNo, int rank, TokenList values, TokenType eleType)
  4584. {
  4585. subscripts[dimNo] = 0;
  4586. foreach(Token val in values.tl)
  4587. {
  4588. CompValu initValue = null;
  4589. // If it is a sublist, process it.
  4590. // If we don't have enough subscripts yet, hopefully that sublist will have enough.
  4591. // If we already have enough subscripts, then that sublist can be for an element of this supposedly jagged array.
  4592. if (val is TokenList sublist)
  4593. {
  4594. if (dimNo + 1 < rank)
  4595. {
  4596. // We don't have enough subscripts yet, hopefully the sublist has the rest.
  4597. FillInInitVals(array, setMeth, subscripts, dimNo + 1, rank, sublist, eleType);
  4598. }
  4599. else if ((eleType is TokenTypeSDTypeClass eleTypeclass) && (eleTypeclass.decl.arrayOfType is null))
  4600. {
  4601. // If we aren't a jagged array either, we can't do anything with the sublist.
  4602. ErrorMsg(val, "too many brace levels");
  4603. }
  4604. else
  4605. {
  4606. // We are a jagged array, so malloc a subarray and initialize it with the sublist.
  4607. // Then we can use that subarray to fill this array's element.
  4608. initValue = MallocAndInitArray(eleType, sublist);
  4609. }
  4610. }
  4611. // If it is a value expression, then output code to compute the value.
  4612. if (val is TokenRVal val1)
  4613. {
  4614. if(dimNo + 1 < rank)
  4615. {
  4616. ErrorMsg((Token)val, "not enough brace levels");
  4617. }
  4618. else
  4619. {
  4620. initValue = GenerateFromRVal(val1);
  4621. }
  4622. }
  4623. // If there is an initValue, output "array.Set (subscript[0], subscript[1], ..., initValue)"
  4624. if(initValue != null)
  4625. {
  4626. array.PushVal(this, val);
  4627. for(int i = 0; i <= dimNo; i++)
  4628. {
  4629. ilGen.Emit(val, OpCodes.Ldc_I4, subscripts[i]);
  4630. }
  4631. initValue.PushVal(this, val, eleType);
  4632. ilGen.Emit(val, OpCodes.Call, setMeth.ilGen);
  4633. }
  4634. // That subscript is processed one way or another, on to the next.
  4635. subscripts[dimNo]++;
  4636. }
  4637. }
  4638. /**
  4639. * @brief parenthesized expression
  4640. * @returns type and location of the result of the computation.
  4641. */
  4642. private CompValu GenerateFromRValParen(TokenRValParen rValParen)
  4643. {
  4644. return GenerateFromRVal(rValParen.rVal);
  4645. }
  4646. /**
  4647. * @brief create a rotation object from the x,y,z,w value expressions.
  4648. */
  4649. private CompValu GenerateFromRValRot(TokenRValRot rValRot)
  4650. {
  4651. CompValu xRVal, yRVal, zRVal, wRVal;
  4652. xRVal = Trivialize(GenerateFromRVal(rValRot.xRVal), rValRot);
  4653. yRVal = Trivialize(GenerateFromRVal(rValRot.yRVal), rValRot);
  4654. zRVal = Trivialize(GenerateFromRVal(rValRot.zRVal), rValRot);
  4655. wRVal = Trivialize(GenerateFromRVal(rValRot.wRVal), rValRot);
  4656. return new CompValuRot(new TokenTypeRot(rValRot), xRVal, yRVal, zRVal, wRVal);
  4657. }
  4658. /**
  4659. * @brief Using 'this' as a pointer to the current script-defined instance object.
  4660. * The value is located in arg #0 of the current instance method.
  4661. */
  4662. private CompValu GenerateFromRValThis(TokenRValThis zhis)
  4663. {
  4664. if(!IsSDTInstMethod())
  4665. {
  4666. ErrorMsg(zhis, "cannot access instance member of class from static method");
  4667. return new CompValuVoid(zhis);
  4668. }
  4669. return new CompValuArg(curDeclFunc.sdtClass.MakeRefToken(zhis), 0);
  4670. }
  4671. /**
  4672. * @brief 'undefined' constant.
  4673. * If this constant gets written to an array element, it will delete that element from the array.
  4674. * If the script retrieves an element by key that is not defined, it will get this value.
  4675. * This value can be stored in and retrieved from variables of type 'object' or script-defined classes.
  4676. * It is a runtime error to cast this value to any other type, eg,
  4677. * we don't allow list or string variables to be null pointers.
  4678. */
  4679. private static CompValu GenerateFromRValUndef(TokenRValUndef rValUndef)
  4680. {
  4681. return new CompValuNull(new TokenTypeUndef(rValUndef));
  4682. }
  4683. /**
  4684. * @brief create a vector object from the x,y,z value expressions.
  4685. */
  4686. private CompValu GenerateFromRValVec(TokenRValVec rValVec)
  4687. {
  4688. CompValu xRVal, yRVal, zRVal;
  4689. xRVal = Trivialize(GenerateFromRVal(rValVec.xRVal), rValVec);
  4690. yRVal = Trivialize(GenerateFromRVal(rValVec.yRVal), rValVec);
  4691. zRVal = Trivialize(GenerateFromRVal(rValVec.zRVal), rValVec);
  4692. return new CompValuVec(new TokenTypeVec(rValVec), xRVal, yRVal, zRVal);
  4693. }
  4694. /**
  4695. * @brief Generate code to get the default initialization value for a variable.
  4696. */
  4697. private CompValu GenerateFromRValInitDef(TokenRValInitDef rValInitDef)
  4698. {
  4699. TokenType type = rValInitDef.type;
  4700. if(type is TokenTypeChar)
  4701. {
  4702. return new CompValuChar(type, (char)0);
  4703. }
  4704. if(type is TokenTypeRot)
  4705. {
  4706. CompValuFloat x = new (type, ScriptBaseClass.ZERO_ROTATION.x);
  4707. CompValuFloat y = new (type, ScriptBaseClass.ZERO_ROTATION.y);
  4708. CompValuFloat z = new (type, ScriptBaseClass.ZERO_ROTATION.z);
  4709. CompValuFloat s = new (type, ScriptBaseClass.ZERO_ROTATION.s);
  4710. return new CompValuRot(type, x, y, z, s);
  4711. }
  4712. if((type is TokenTypeKey) || (type is TokenTypeStr))
  4713. {
  4714. return new CompValuString(type, "");
  4715. }
  4716. if(type is TokenTypeVec)
  4717. {
  4718. CompValuFloat x = new (type, ScriptBaseClass.ZERO_VECTOR.x);
  4719. CompValuFloat y = new (type, ScriptBaseClass.ZERO_VECTOR.y);
  4720. CompValuFloat z = new (type, ScriptBaseClass.ZERO_VECTOR.z);
  4721. return new CompValuVec(type, x, y, z);
  4722. }
  4723. if(type is TokenTypeInt)
  4724. {
  4725. return new CompValuInteger(type, 0);
  4726. }
  4727. if(type is TokenTypeFloat)
  4728. {
  4729. return new CompValuFloat(type, 0);
  4730. }
  4731. if(type is TokenTypeVoid)
  4732. {
  4733. return new CompValuVoid(type);
  4734. }
  4735. // Default for 'object' type is 'undef'.
  4736. // Likewise for script-defined classes and interfaces.
  4737. if((type is TokenTypeObject) || (type is TokenTypeSDTypeClass) || (type is TokenTypeSDTypeDelegate) ||
  4738. (type is TokenTypeSDTypeInterface) || (type is TokenTypeExc))
  4739. {
  4740. return new CompValuNull(type);
  4741. }
  4742. // array and list
  4743. CompValuTemp temp = new (type, this);
  4744. PushDefaultValue(type);
  4745. temp.Pop(this, rValInitDef, type);
  4746. return temp;
  4747. }
  4748. /**
  4749. * @brief Generate code to process an <rVal> is <type> expression, and produce a boolean value.
  4750. */
  4751. private CompValu GenerateFromRValIsType(TokenRValIsType rValIsType)
  4752. {
  4753. // Expression we want to know the type of.
  4754. CompValu val = GenerateFromRVal(rValIsType.rValExp);
  4755. // Pass it in to top-level type expression decoder.
  4756. return GenerateFromTypeExp(val, rValIsType.typeExp);
  4757. }
  4758. /**
  4759. * @brief See if the type of the given value matches the type expression.
  4760. * @param val = where the value to be evaluated is stored
  4761. * @param typeExp = script tokens representing type expression
  4762. * @returns location where the boolean result is stored
  4763. */
  4764. private CompValu GenerateFromTypeExp(CompValu val, TokenTypeExp typeExp)
  4765. {
  4766. if(typeExp is TokenTypeExpBinOp op1)
  4767. {
  4768. CompValu left = GenerateFromTypeExp(val, op1.leftOp);
  4769. CompValu right = GenerateFromTypeExp(val, op1.rightOp);
  4770. CompValuTemp result = new (tokenTypeBool, this);
  4771. Token op = op1.binOp;
  4772. left.PushVal(this, op1.leftOp);
  4773. right.PushVal(this, op1.rightOp);
  4774. if(op is TokenKwAnd)
  4775. {
  4776. ilGen.Emit(typeExp, OpCodes.And);
  4777. }
  4778. else if(op is TokenKwOr)
  4779. {
  4780. ilGen.Emit(typeExp, OpCodes.Or);
  4781. }
  4782. else
  4783. {
  4784. throw new Exception("unknown TokenTypeExpBinOp " + op.GetType());
  4785. }
  4786. result.Pop(this, typeExp);
  4787. return result;
  4788. }
  4789. if(typeExp is TokenTypeExpNot expnot)
  4790. {
  4791. CompValu interm = GenerateFromTypeExp(val, expnot.typeExp);
  4792. CompValuTemp result = new (tokenTypeBool, this);
  4793. interm.PushVal(this, expnot.typeExp, tokenTypeBool);
  4794. ilGen.Emit(typeExp, OpCodes.Ldc_I4_1);
  4795. ilGen.Emit(typeExp, OpCodes.Xor);
  4796. result.Pop(this, typeExp);
  4797. return result;
  4798. }
  4799. if(typeExp is TokenTypeExpPar TokenTypeExpPartypeExp)
  4800. {
  4801. return GenerateFromTypeExp(val, TokenTypeExpPartypeExp.typeExp);
  4802. }
  4803. if(typeExp is TokenTypeExpType TokenTypeExpTypetypeExp)
  4804. {
  4805. CompValuTemp result = new (tokenTypeBool, this);
  4806. val.PushVal(this, typeExp);
  4807. ilGen.Emit(typeExp, OpCodes.Isinst, TokenTypeExpTypetypeExp.typeToken.ToSysType());
  4808. ilGen.Emit(typeExp, OpCodes.Ldnull);
  4809. ilGen.Emit(typeExp, OpCodes.Ceq);
  4810. ilGen.Emit(typeExp, OpCodes.Ldc_I4_1);
  4811. ilGen.Emit(typeExp, OpCodes.Xor);
  4812. result.Pop(this, typeExp);
  4813. return result;
  4814. }
  4815. if(typeExp is TokenTypeExpUndef)
  4816. {
  4817. CompValuTemp result = new (tokenTypeBool, this);
  4818. val.PushVal(this, typeExp);
  4819. ilGen.Emit(typeExp, OpCodes.Ldnull);
  4820. ilGen.Emit(typeExp, OpCodes.Ceq);
  4821. result.Pop(this, typeExp);
  4822. return result;
  4823. }
  4824. throw new Exception("unknown TokenTypeExp type " + typeExp.GetType());
  4825. }
  4826. /**
  4827. * @brief Push the default (null) value for a particular variable
  4828. * @param var = variable to get the default value for
  4829. * @returns with value pushed on stack
  4830. */
  4831. public void PushVarDefaultValue(TokenDeclVar var)
  4832. {
  4833. PushDefaultValue(var.type);
  4834. }
  4835. public void PushDefaultValue(TokenType type)
  4836. {
  4837. if(type is TokenTypeArray)
  4838. {
  4839. PushXMRInst(); // instance
  4840. ilGen.Emit(type, OpCodes.Newobj, xmrArrayConstructorInfo);
  4841. return;
  4842. }
  4843. if(type is TokenTypeChar)
  4844. {
  4845. ilGen.Emit(type, OpCodes.Ldc_I4_0);
  4846. return;
  4847. }
  4848. if(type is TokenTypeList)
  4849. {
  4850. ilGen.Emit(type, OpCodes.Ldc_I4_0);
  4851. ilGen.Emit(type, OpCodes.Newarr, typeof(object));
  4852. ilGen.Emit(type, OpCodes.Newobj, lslListConstructorInfo);
  4853. return;
  4854. }
  4855. if(type is TokenTypeRot)
  4856. {
  4857. // Mono is tOO stOOpid to allow: ilGen.Emit (OpCodes.Ldsfld, zeroRotationFieldInfo);
  4858. ilGen.Emit(type, OpCodes.Ldc_R8, ScriptBaseClass.ZERO_ROTATION.x);
  4859. ilGen.Emit(type, OpCodes.Ldc_R8, ScriptBaseClass.ZERO_ROTATION.y);
  4860. ilGen.Emit(type, OpCodes.Ldc_R8, ScriptBaseClass.ZERO_ROTATION.z);
  4861. ilGen.Emit(type, OpCodes.Ldc_R8, ScriptBaseClass.ZERO_ROTATION.s);
  4862. ilGen.Emit(type, OpCodes.Newobj, lslRotationConstructorInfo);
  4863. return;
  4864. }
  4865. if((type is TokenTypeKey) || (type is TokenTypeStr))
  4866. {
  4867. ilGen.Emit(type, OpCodes.Ldstr, "");
  4868. return;
  4869. }
  4870. if(type is TokenTypeVec)
  4871. {
  4872. // Mono is tOO stOOpid to allow: ilGen.Emit (OpCodes.Ldsfld, zeroVectorFieldInfo);
  4873. ilGen.Emit(type, OpCodes.Ldc_R8, ScriptBaseClass.ZERO_VECTOR.x);
  4874. ilGen.Emit(type, OpCodes.Ldc_R8, ScriptBaseClass.ZERO_VECTOR.y);
  4875. ilGen.Emit(type, OpCodes.Ldc_R8, ScriptBaseClass.ZERO_VECTOR.z);
  4876. ilGen.Emit(type, OpCodes.Newobj, lslVectorConstructorInfo);
  4877. return;
  4878. }
  4879. if(type is TokenTypeInt)
  4880. {
  4881. ilGen.Emit(type, OpCodes.Ldc_I4_0);
  4882. return;
  4883. }
  4884. if(type is TokenTypeFloat)
  4885. {
  4886. ilGen.Emit(type, OpCodes.Ldc_R4, 0.0f);
  4887. return;
  4888. }
  4889. // Default for 'object' type is 'undef'.
  4890. // Likewise for script-defined classes and interfaces.
  4891. if((type is TokenTypeObject) || (type is TokenTypeSDTypeClass) || (type is TokenTypeSDTypeInterface) || (type is TokenTypeExc))
  4892. {
  4893. ilGen.Emit(type, OpCodes.Ldnull);
  4894. return;
  4895. }
  4896. // Void is pushed as the default return value of a void function.
  4897. // So just push nothing as expected of void functions.
  4898. if(type is TokenTypeVoid)
  4899. {
  4900. return;
  4901. }
  4902. // Default for 'delegate' type is 'undef'.
  4903. if(type is TokenTypeSDTypeDelegate)
  4904. {
  4905. ilGen.Emit(type, OpCodes.Ldnull);
  4906. return;
  4907. }
  4908. throw new Exception("unknown type " + type.GetType().ToString());
  4909. }
  4910. /**
  4911. * @brief Determine if the expression has a constant boolean value
  4912. * and if so, if the value is true or false.
  4913. * @param expr = expression to evaluate
  4914. * @returns true: expression is contant and has boolean value true
  4915. * false: otherwise
  4916. */
  4917. private static bool IsConstBoolExprTrue(CompValu expr)
  4918. {
  4919. return IsConstBoolExpr(expr, out bool constVal) && constVal;
  4920. }
  4921. private static bool IsConstBoolExpr(CompValu expr, out bool constVal)
  4922. {
  4923. if(expr is CompValuChar CompValuCharexpr)
  4924. {
  4925. constVal = CompValuCharexpr.x != 0;
  4926. return true;
  4927. }
  4928. if(expr is CompValuFloat CompValuFloatexpr)
  4929. {
  4930. constVal = CompValuFloatexpr.x != 0;
  4931. return true;
  4932. }
  4933. if(expr is CompValuInteger CompValuIntegerexpr)
  4934. {
  4935. constVal = CompValuIntegerexpr.x != 0;
  4936. return true;
  4937. }
  4938. if(expr is CompValuString CompValuStringexpr)
  4939. {
  4940. string s = CompValuStringexpr.x;
  4941. constVal = s != "";
  4942. if(constVal && (expr.type is TokenTypeKey))
  4943. {
  4944. constVal = s != ScriptBaseClass.NULL_KEY;
  4945. }
  4946. return true;
  4947. }
  4948. constVal = false;
  4949. return false;
  4950. }
  4951. /**
  4952. * @brief Determine if the expression has a constant integer value
  4953. * and if so, return the integer value.
  4954. * @param expr = expression to evaluate
  4955. * @returns true: expression is contant and has integer value
  4956. * false: otherwise
  4957. */
  4958. private static bool IsConstIntExpr(CompValu expr, out int constVal)
  4959. {
  4960. if(expr is CompValuChar CompValuCharexpr)
  4961. {
  4962. constVal = (int)CompValuCharexpr.x;
  4963. return true;
  4964. }
  4965. if(expr is CompValuInteger CompValuIntegerexpr)
  4966. {
  4967. constVal = CompValuIntegerexpr.x;
  4968. return true;
  4969. }
  4970. constVal = 0;
  4971. return false;
  4972. }
  4973. /**
  4974. * @brief Determine if the expression has a constant string value
  4975. * and if so, return the string value.
  4976. * @param expr = expression to evaluate
  4977. * @returns true: expression is contant and has string value
  4978. * false: otherwise
  4979. */
  4980. private static bool IsConstStrExpr(CompValu expr, out string constVal)
  4981. {
  4982. if(expr is CompValuString exprstring)
  4983. {
  4984. constVal = exprstring.x;
  4985. return true;
  4986. }
  4987. constVal = "";
  4988. return false;
  4989. }
  4990. /**
  4991. * @brief create table of legal event handler prototypes.
  4992. * This is used to make sure script's event handler declrations are valid.
  4993. */
  4994. private static VarDict CreateLegalEventHandlers()
  4995. {
  4996. // Get handler prototypes with full argument lists.
  4997. VarDict leh = new InternalFuncDict(typeof(IEventHandlers), false);
  4998. // We want the scripts to be able to declare their handlers with
  4999. // fewer arguments than the full argument lists. So define additional
  5000. // prototypes with fewer arguments.
  5001. TokenDeclVar[] fullArgProtos = new TokenDeclVar[leh.Count];
  5002. int i = 0;
  5003. foreach(TokenDeclVar fap in leh)
  5004. fullArgProtos[i++] = fap;
  5005. foreach(TokenDeclVar fap in fullArgProtos)
  5006. {
  5007. TokenArgDecl fal = fap.argDecl;
  5008. int fullArgCount = fal.vars.Length;
  5009. for(i = 0; i < fullArgCount; i++)
  5010. {
  5011. TokenArgDecl shortArgList = new (null);
  5012. for(int j = 0; j < i; j++)
  5013. {
  5014. TokenDeclVar var = fal.vars[j];
  5015. shortArgList.AddArg(var.type, var.name);
  5016. }
  5017. TokenDeclVar shortArgProto = new (null, null, null)
  5018. {
  5019. name = new TokenName(null, fap.GetSimpleName()),
  5020. retType = fap.retType,
  5021. argDecl = shortArgList
  5022. };
  5023. leh.AddEntry(shortArgProto);
  5024. }
  5025. }
  5026. return leh;
  5027. }
  5028. /**
  5029. * @brief Emit a call to CheckRun(), (voluntary multitasking switch)
  5030. */
  5031. public void EmitCallCheckRun(Token errorAt, bool stack)
  5032. {
  5033. if(curDeclFunc.IsFuncTrivial(this))
  5034. throw new Exception(curDeclFunc.fullName + " is supposed to be trivial");
  5035. _ = new CallLabel(this, errorAt); // jump here when stack restored
  5036. PushXMRInst(); // instance
  5037. ilGen.Emit(errorAt, OpCodes.Call, stack ? checkRunStackMethInfo : checkRunQuickMethInfo);
  5038. openCallLabel = null;
  5039. }
  5040. /**
  5041. * @brief Emit code to push a callNo var on the stack.
  5042. */
  5043. public void GetCallNo(Token errorAt, ScriptMyLocal callNoVar)
  5044. {
  5045. ilGen.Emit(errorAt, OpCodes.Ldloc, callNoVar);
  5046. //ilGen.Emit (errorAt, OpCodes.Ldloca, callNoVar);
  5047. //ilGen.Emit (errorAt, OpCodes.Volatile);
  5048. //ilGen.Emit (errorAt, OpCodes.Ldind_I4);
  5049. }
  5050. public void GetCallNo(Token errorAt, CompValu callNoVar)
  5051. {
  5052. callNoVar.PushVal(this, errorAt);
  5053. //callNoVar.PushRef (this, errorAt);
  5054. //ilGen.Emit (errorAt, OpCodes.Volatile);
  5055. //ilGen.Emit (errorAt, OpCodes.Ldind_I4);
  5056. }
  5057. /**
  5058. * @brief Emit code to set a callNo var to a given constant.
  5059. */
  5060. public void SetCallNo(Token errorAt, ScriptMyLocal callNoVar, int val)
  5061. {
  5062. ilGen.Emit(errorAt, OpCodes.Ldc_I4, val);
  5063. ilGen.Emit(errorAt, OpCodes.Stloc, callNoVar);
  5064. //ilGen.Emit (errorAt, OpCodes.Ldloca, callNoVar);
  5065. //ilGen.Emit (errorAt, OpCodes.Ldc_I4, val);
  5066. //ilGen.Emit (errorAt, OpCodes.Volatile);
  5067. //ilGen.Emit (errorAt, OpCodes.Stind_I4);
  5068. }
  5069. public void SetCallNo(Token errorAt, CompValu callNoVar, int val)
  5070. {
  5071. callNoVar.PopPre(this, errorAt);
  5072. ilGen.Emit(errorAt, OpCodes.Ldc_I4, val);
  5073. callNoVar.PopPost(this, errorAt);
  5074. //callNoVar.PushRef (this, errorAt);
  5075. //ilGen.Emit (errorAt, OpCodes.Ldc_I4, val);
  5076. //ilGen.Emit (errorAt, OpCodes.Volatile);
  5077. //ilGen.Emit (errorAt, OpCodes.Stind_I4);
  5078. }
  5079. /**
  5080. * @brief handle a unary operator, such as -x.
  5081. */
  5082. private CompValu UnOpGenerate(CompValu inRVal, Token opcode)
  5083. {
  5084. // - Negate
  5085. if(opcode is TokenKwSub)
  5086. {
  5087. if(inRVal.type is TokenTypeFloat)
  5088. {
  5089. CompValuTemp outRVal = new (new TokenTypeFloat(opcode), this);
  5090. inRVal.PushVal(this, opcode, outRVal.type); // push value to negate, make sure not LSL-boxed
  5091. ilGen.Emit(opcode, OpCodes.Neg); // compute the negative
  5092. outRVal.Pop(this, opcode); // pop into result
  5093. return outRVal; // tell caller where we put it
  5094. }
  5095. if(inRVal.type is TokenTypeInt)
  5096. {
  5097. CompValuTemp outRVal = new (new TokenTypeInt(opcode), this);
  5098. inRVal.PushVal(this, opcode, outRVal.type); // push value to negate, make sure not LSL-boxed
  5099. ilGen.Emit(opcode, OpCodes.Neg); // compute the negative
  5100. outRVal.Pop(this, opcode); // pop into result
  5101. return outRVal; // tell caller where we put it
  5102. }
  5103. if(inRVal.type is TokenTypeRot)
  5104. {
  5105. CompValuTemp outRVal = new (inRVal.type, this);
  5106. inRVal.PushVal(this, opcode); // push rotation, then call negate routine
  5107. ilGen.Emit(opcode, OpCodes.Call, lslRotationNegateMethodInfo);
  5108. outRVal.Pop(this, opcode); // pop into result
  5109. return outRVal; // tell caller where we put it
  5110. }
  5111. if(inRVal.type is TokenTypeVec)
  5112. {
  5113. CompValuTemp outRVal = new (inRVal.type, this);
  5114. inRVal.PushVal(this, opcode); // push vector, then call negate routine
  5115. ilGen.Emit(opcode, OpCodes.Call, lslVectorNegateMethodInfo);
  5116. outRVal.Pop(this, opcode); // pop into result
  5117. return outRVal; // tell caller where we put it
  5118. }
  5119. if (inRVal.type is TokenTypeBool)
  5120. {
  5121. CompValuTemp outRVal = new (new TokenTypeInt(opcode), this);
  5122. inRVal.PushVal(this, opcode, outRVal.type); // push value to negate, make sure not LSL-boxed
  5123. ilGen.Emit(opcode, OpCodes.Neg); // compute the negative
  5124. outRVal.Pop(this, opcode); // pop into result
  5125. return outRVal; // tell caller where we put it
  5126. }
  5127. ErrorMsg(opcode, "can't negate a " + inRVal.type.ToString());
  5128. return inRVal;
  5129. }
  5130. // ~ Complement (bitwise integer)
  5131. if(opcode is TokenKwTilde)
  5132. {
  5133. if(inRVal.type is TokenTypeInt)
  5134. {
  5135. CompValuTemp outRVal = new (new TokenTypeInt(opcode), this);
  5136. inRVal.PushVal(this, opcode, outRVal.type); // push value to negate, make sure not LSL-boxed
  5137. ilGen.Emit(opcode, OpCodes.Not); // compute the complement
  5138. outRVal.Pop(this, opcode); // pop into result
  5139. return outRVal; // tell caller where we put it
  5140. }
  5141. ErrorMsg(opcode, "can't complement a " + inRVal.type.ToString());
  5142. return inRVal;
  5143. }
  5144. // ! Not (boolean)
  5145. //
  5146. // We stuff the 0/1 result in an int because I've seen x+!y in scripts
  5147. // and we don't want to have to create tables to handle int+bool and
  5148. // everything like that.
  5149. if(opcode is TokenKwExclam)
  5150. {
  5151. CompValuTemp outRVal = new (new TokenTypeInt(opcode), this);
  5152. inRVal.PushVal(this, opcode, tokenTypeBool); // anything converts to boolean
  5153. ilGen.Emit(opcode, OpCodes.Ldc_I4_1); // then XOR with 1 to flip it
  5154. ilGen.Emit(opcode, OpCodes.Xor);
  5155. outRVal.Pop(this, opcode); // pop into result
  5156. return outRVal; // tell caller where we put it
  5157. }
  5158. throw new Exception("unhandled opcode " + opcode.ToString());
  5159. }
  5160. /**
  5161. * @brief This is called while trying to compute the value of constant initializers.
  5162. * It is passed a name and that name is looked up in the constant tables.
  5163. */
  5164. private TokenRVal LookupInitConstants(TokenRVal rVal, ref bool didOne)
  5165. {
  5166. // If it is a static field of a script-defined type, look it up and hopefully we find a constant there.
  5167. TokenDeclVar gblVar;
  5168. if (rVal is TokenLValSField lvsf)
  5169. {
  5170. if (lvsf.baseType is TokenTypeSDTypeClass basetypeclass)
  5171. {
  5172. TokenDeclSDTypeClass sdtClass = basetypeclass.decl;
  5173. gblVar = sdtClass.members.FindExact(lvsf.fieldName.val, null);
  5174. if (gblVar != null)
  5175. {
  5176. if (gblVar.constant && (gblVar.init is TokenRValConst))
  5177. {
  5178. didOne = true;
  5179. return gblVar.init;
  5180. }
  5181. }
  5182. }
  5183. return rVal;
  5184. }
  5185. // Only other thing we handle is stand-alone names.
  5186. if (rVal is not TokenLValName)
  5187. return rVal;
  5188. string name = ((TokenLValName)rVal).name.val;
  5189. // If we are doing the initializations for a script-defined type,
  5190. // look for the constant among the fields for that type.
  5191. if(currentSDTClass != null)
  5192. {
  5193. gblVar = currentSDTClass.members.FindExact(name, null);
  5194. if(gblVar != null)
  5195. {
  5196. if(gblVar.constant && (gblVar.init is TokenRValConst))
  5197. {
  5198. didOne = true;
  5199. return gblVar.init;
  5200. }
  5201. return rVal;
  5202. }
  5203. }
  5204. // Look it up as a script-defined global variable.
  5205. // Then if the variable is defined as a constant and has a constant value,
  5206. // we are successful. If it is defined as something else, return failure.
  5207. gblVar = tokenScript.variablesStack.FindExact(name, null);
  5208. if(gblVar != null)
  5209. {
  5210. if(gblVar.constant && (gblVar.init is TokenRValConst))
  5211. {
  5212. didOne = true;
  5213. return gblVar.init;
  5214. }
  5215. return rVal;
  5216. }
  5217. // Maybe it is a built-in symbolic constant.
  5218. ScriptConst scriptConst = ScriptConst.Lookup(name);
  5219. if(scriptConst != null)
  5220. {
  5221. rVal = CompValuConst2RValConst(scriptConst.rVal, rVal);
  5222. if(rVal is TokenRValConst)
  5223. {
  5224. didOne = true;
  5225. return rVal;
  5226. }
  5227. }
  5228. // Don't know what it is, return failure.
  5229. return rVal;
  5230. }
  5231. /**
  5232. * @brief This is called while trying to compute the value of constant expressions.
  5233. * It is passed a name and that name is looked up in the constant tables.
  5234. */
  5235. private TokenRVal LookupBodyConstants(TokenRVal rVal, ref bool didOne)
  5236. {
  5237. // If it is a static field of a script-defined type, look it up and hopefully we find a constant there.
  5238. TokenDeclVar gblVar;
  5239. if(rVal is TokenLValSField lvsf)
  5240. {
  5241. if(lvsf.baseType is TokenTypeSDTypeClass TokenTypeSDTypeClasslvsfbaseType)
  5242. {
  5243. TokenDeclSDTypeClass sdtClass = TokenTypeSDTypeClasslvsfbaseType.decl;
  5244. gblVar = sdtClass.members.FindExact(lvsf.fieldName.val, null);
  5245. if((gblVar != null) && gblVar.constant && (gblVar.init is TokenRValConst))
  5246. {
  5247. didOne = true;
  5248. return gblVar.init;
  5249. }
  5250. }
  5251. return rVal;
  5252. }
  5253. // Only other thing we handle is stand-alone names.
  5254. if(rVal is not TokenLValName)
  5255. return rVal;
  5256. string name = ((TokenLValName)rVal).name.val;
  5257. // Scan through the variable stack and hopefully we find a constant there.
  5258. // But we stop as soon as we get a match because that's what the script is referring to.
  5259. CompValu val;
  5260. for(VarDict vars = ((TokenLValName)rVal).stack; vars != null; vars = vars.outerVarDict)
  5261. {
  5262. TokenDeclVar var = vars.FindExact(name, null);
  5263. if(var != null)
  5264. {
  5265. val = var.location;
  5266. goto foundit;
  5267. }
  5268. TokenDeclSDTypeClass baseClass = vars.thisClass;
  5269. if(baseClass != null)
  5270. {
  5271. while((baseClass = baseClass.extends) != null)
  5272. {
  5273. var = baseClass.members.FindExact(name, null);
  5274. if(var != null)
  5275. {
  5276. val = var.location;
  5277. goto foundit;
  5278. }
  5279. }
  5280. }
  5281. }
  5282. // Maybe it is a built-in symbolic constant.
  5283. ScriptConst scriptConst = ScriptConst.Lookup(name);
  5284. if(scriptConst != null)
  5285. {
  5286. val = scriptConst.rVal;
  5287. goto foundit;
  5288. }
  5289. // Don't know what it is, return failure.
  5290. return rVal;
  5291. // Found a CompValu. If it's a simple constant, then use it.
  5292. // Otherwise tell caller we failed to simplify.
  5293. foundit:
  5294. rVal = CompValuConst2RValConst(val, rVal);
  5295. if(rVal is TokenRValConst)
  5296. {
  5297. didOne = true;
  5298. }
  5299. return rVal;
  5300. }
  5301. private static TokenRVal CompValuConst2RValConst(CompValu val, TokenRVal rVal)
  5302. {
  5303. if(val is CompValuChar CompValuCharval)
  5304. rVal = new TokenRValConst(rVal, CompValuCharval.x);
  5305. if(val is CompValuFloat CompValuFloatval)
  5306. rVal = new TokenRValConst(rVal, CompValuFloatval.x);
  5307. if(val is CompValuInteger CompValuIntegerval)
  5308. rVal = new TokenRValConst(rVal, CompValuIntegerval.x);
  5309. if(val is CompValuString CompValuStringval)
  5310. rVal = new TokenRValConst(rVal, CompValuStringval.x);
  5311. return rVal;
  5312. }
  5313. /**
  5314. * @brief Generate code to push XMRInstanceSuperType pointer on stack.
  5315. */
  5316. public void PushXMRInst()
  5317. {
  5318. if(instancePointer == null)
  5319. {
  5320. ilGen.Emit(null, OpCodes.Ldarg_0);
  5321. }
  5322. else
  5323. {
  5324. ilGen.Emit(null, OpCodes.Ldloc, instancePointer);
  5325. }
  5326. }
  5327. /**
  5328. * @returns true: Ldarg_0 gives XMRSDTypeClObj pointer
  5329. * - this is the case for instance methods
  5330. * false: Ldarg_0 gives XMR_Instance pointer
  5331. * - this is the case for both global functions and static methods
  5332. */
  5333. public bool IsSDTInstMethod()
  5334. {
  5335. return (curDeclFunc.sdtClass != null) &&
  5336. ((curDeclFunc.sdtFlags & ScriptReduce.SDT_STATIC) == 0);
  5337. }
  5338. /**
  5339. * @brief Look for a simply named function or variable (not a field or method)
  5340. */
  5341. public TokenDeclVar FindNamedVar(TokenLValName lValName, TokenType[] argsig)
  5342. {
  5343. // Look in variable stack for the given name.
  5344. for(VarDict vars = lValName.stack; vars != null; vars = vars.outerVarDict)
  5345. {
  5346. // first look for it possibly with an argument signature
  5347. // so we pick the correct overloaded method
  5348. TokenDeclVar var = FindSingleMember(vars, lValName.name, argsig);
  5349. if(var != null)
  5350. return var;
  5351. // if that fails, try it without the argument signature.
  5352. // delegates get entered like any other variable, ie,
  5353. // no signature on their name.
  5354. if(argsig != null)
  5355. {
  5356. var = FindSingleMember(vars, lValName.name, null);
  5357. if(var != null)
  5358. return var;
  5359. }
  5360. // if this is the frame for some class members, try searching base class members too
  5361. TokenDeclSDTypeClass baseClass = vars.thisClass;
  5362. if(baseClass != null)
  5363. {
  5364. while((baseClass = baseClass.extends) != null)
  5365. {
  5366. var = FindSingleMember(baseClass.members, lValName.name, argsig);
  5367. if(var != null)
  5368. return var;
  5369. if(argsig != null)
  5370. {
  5371. var = FindSingleMember(baseClass.members, lValName.name, null);
  5372. if(var != null)
  5373. return var;
  5374. }
  5375. }
  5376. }
  5377. }
  5378. // If not found, try one of the built-in constants or functions.
  5379. if(argsig == null)
  5380. {
  5381. ScriptConst scriptConst = ScriptConst.Lookup(lValName.name.val);
  5382. if(scriptConst != null)
  5383. {
  5384. TokenDeclVar var = new (lValName.name, null, tokenScript)
  5385. {
  5386. name = lValName.name,
  5387. type = scriptConst.rVal.type,
  5388. location = scriptConst.rVal
  5389. };
  5390. return var;
  5391. }
  5392. }
  5393. else
  5394. {
  5395. TokenDeclVar inline = FindSingleMember(TokenDeclInline.inlineFunctions, lValName.name, argsig);
  5396. if(inline != null)
  5397. return inline;
  5398. }
  5399. return null;
  5400. }
  5401. /**
  5402. * @brief Find a member of an interface.
  5403. * @param sdType = interface type
  5404. * @param name = name of member to find
  5405. * @param argsig = null: field/property; else: script-visible method argument types
  5406. * @param baseRVal = pointer to interface object
  5407. * @returns null: no such member
  5408. * else: pointer to member
  5409. * baseRVal = possibly modified to point to type-casted interface object
  5410. */
  5411. private TokenDeclVar FindInterfaceMember(TokenTypeSDTypeInterface sdtType, TokenName name, TokenType[] argsig, ref CompValu baseRVal)
  5412. {
  5413. TokenDeclSDTypeInterface sdtDecl = sdtType.decl;
  5414. TokenDeclVar declVar = sdtDecl.FindIFaceMember(this, name, argsig, out TokenDeclSDTypeInterface impl);
  5415. if ((declVar != null) && (impl != sdtDecl))
  5416. {
  5417. // Accessing a method or propterty of another interface that the primary interface says it implements.
  5418. // In this case, we have to cast from the primary interface to that secondary interface.
  5419. //
  5420. // interface IEnumerable {
  5421. // IEnumerator GetEnumerator ();
  5422. // }
  5423. // interface ICountable : IEnumerable {
  5424. // integer GetCount ();
  5425. // }
  5426. // class List : ICountable {
  5427. // public GetCount () : ICountable { ... }
  5428. // public GetEnumerator () : IEnumerable { ... }
  5429. // }
  5430. //
  5431. // ICountable aList = new List ();
  5432. // IEnumerator anEnumer = aList.GetEnumerator (); << we are here
  5433. // << baseRVal = aList
  5434. // << sdtDecl = ICountable
  5435. // << impl = IEnumerable
  5436. // << name = GetEnumerator
  5437. // << argsig = ()
  5438. // So we have to cast aList from ICountable to IEnumerable.
  5439. // make type token for the secondary interface type
  5440. TokenType subIntfType = impl.MakeRefToken(name);
  5441. // make a temp variable of the secondary interface type
  5442. CompValuTemp castBase = new (subIntfType, this);
  5443. // output code to cast from the primary interface to the secondary interface
  5444. // this is 2 basic steps:
  5445. // 1) cast from primary interface object -> class object
  5446. // ...gets it from interfaceObject.delegateArray[0].Target
  5447. // 2) cast from class object -> secondary interface object
  5448. // ...gets it from classObject.sdtcITable[interfaceIndex]
  5449. baseRVal.PushVal(this, name, subIntfType);
  5450. // save result of casting in temp
  5451. castBase.Pop(this, name);
  5452. // return temp reference
  5453. baseRVal = castBase;
  5454. }
  5455. return declVar;
  5456. }
  5457. /**
  5458. * @brief Find a member of a script-defined type class.
  5459. * @param sdtType = reference to class declaration
  5460. * @param name = name of member to find
  5461. * @param argsig = argument signature used to select among overloaded members
  5462. * @returns null: no such member found
  5463. * else: the member found
  5464. */
  5465. public TokenDeclVar FindThisMember(TokenTypeSDTypeClass sdtType, TokenName name, TokenType[] argsig)
  5466. {
  5467. return FindThisMember(sdtType.decl, name, argsig);
  5468. }
  5469. public TokenDeclVar FindThisMember(TokenDeclSDTypeClass sdtDecl, TokenName name, TokenType[] argsig)
  5470. {
  5471. for(TokenDeclSDTypeClass sdtd = sdtDecl; sdtd != null; sdtd = sdtd.extends)
  5472. {
  5473. TokenDeclVar declVar = FindSingleMember(sdtd.members, name, argsig);
  5474. if(declVar != null)
  5475. return declVar;
  5476. }
  5477. return null;
  5478. }
  5479. /**
  5480. * @brief Look for a single member that matches the given name and argument signature
  5481. * @param where = which dictionary to look in
  5482. * @param name = basic name of the field or method, eg, "Printable"
  5483. * @param argsig = argument types the method is being called with, eg, "(string)"
  5484. * or null to find a field
  5485. * @returns null: no member found
  5486. * else: the member found
  5487. */
  5488. public TokenDeclVar FindSingleMember(VarDict where, TokenName name, TokenType[] argsig)
  5489. {
  5490. TokenDeclVar[] members = where.FindCallables(name.val, argsig);
  5491. if(members == null)
  5492. return null;
  5493. if(members.Length > 1)
  5494. {
  5495. ErrorMsg(name, "more than one matching member");
  5496. for(int i = 0; i < members.Length; i++)
  5497. {
  5498. ErrorMsg(members[i], " " + members[i].argDecl.GetArgSig());
  5499. }
  5500. }
  5501. return members[0];
  5502. }
  5503. /**
  5504. * @brief Find an exact function name and argument signature match.
  5505. * Also verify that the return value type is an exact match.
  5506. * @param where = which method dictionary to look in
  5507. * @param name = basic name of the method, eg, "Printable"
  5508. * @param ret = expected return value type
  5509. * @param argsig = argument types the method is being called with, eg, "(string)"
  5510. * @returns null: no exact match found
  5511. * else: the matching function
  5512. */
  5513. private TokenDeclVar FindExactWithRet(VarDict where, TokenName name, TokenType ret, TokenType[] argsig)
  5514. {
  5515. TokenDeclVar func = where.FindExact(name.val, argsig);
  5516. if((func != null) && (func.retType.ToString() != ret.ToString()))
  5517. {
  5518. ErrorMsg(name, "return type mismatch, have " + func.retType.ToString() + ", expect " + ret.ToString());
  5519. }
  5520. if(func != null)
  5521. CheckAccess(func, name);
  5522. return func;
  5523. }
  5524. /**
  5525. * @brief Check the private/protected/public access flags of a member.
  5526. */
  5527. private void CheckAccess(TokenDeclVar var, Token errorAt)
  5528. {
  5529. TokenDeclSDType nested;
  5530. TokenDeclSDType definedBy = var.sdtClass;
  5531. TokenDeclSDType accessedBy = curDeclFunc.sdtClass;
  5532. //*******************************
  5533. // Check member-level access
  5534. //*******************************
  5535. // Note that if accessedBy is null, ie, accessing from global function (or event handlers),
  5536. // anything tagged as SDT_PRIVATE or SDT_PROTECTED will fail.
  5537. // Private means accessed by the class that defined the member or accessed by a nested class
  5538. // of the class that defined the member.
  5539. if((var.sdtFlags & ScriptReduce.SDT_PRIVATE) != 0)
  5540. {
  5541. for(nested = accessedBy; nested != null; nested = nested.outerSDType)
  5542. {
  5543. if(nested == definedBy)
  5544. goto acc1ok;
  5545. }
  5546. ErrorMsg(errorAt, "private member " + var.fullName + " cannot be accessed by " + curDeclFunc.fullName);
  5547. return;
  5548. }
  5549. // Protected means:
  5550. // If being accessed by an inner class, the inner class has access to it if the inner class derives
  5551. // from the declaring class. It also has access to it if an outer class derives from the declaring
  5552. // class.
  5553. if((var.sdtFlags & ScriptReduce.SDT_PROTECTED) != 0)
  5554. {
  5555. for(nested = accessedBy; nested != null; nested = nested.outerSDType)
  5556. {
  5557. for(TokenDeclSDType rootward = nested; rootward != null; rootward = rootward.extends)
  5558. {
  5559. if(rootward == definedBy)
  5560. goto acc1ok;
  5561. }
  5562. }
  5563. ErrorMsg(errorAt, "protected member " + var.fullName + " cannot be accessed by " + curDeclFunc.fullName);
  5564. return;
  5565. }
  5566. acc1ok:
  5567. //******************************
  5568. // Check class-level access
  5569. //******************************
  5570. // If being accessed by same or inner class than where defined, it is ok.
  5571. //
  5572. // class DefiningClass {
  5573. // varBeingAccessed;
  5574. // .
  5575. // .
  5576. // .
  5577. // class AccessingClass {
  5578. // functionDoingAccess() { }
  5579. // }
  5580. // .
  5581. // .
  5582. // .
  5583. // }
  5584. nested = accessedBy;
  5585. while(true)
  5586. {
  5587. if(nested == definedBy)
  5588. return;
  5589. if(nested == null)
  5590. break;
  5591. nested = (TokenDeclSDTypeClass)nested.outerSDType;
  5592. }
  5593. // It is being accessed by an outer class than where defined,
  5594. // check for a 'private' or 'protected' class tag that blocks.
  5595. do
  5596. {
  5597. // If the field's class is defined directly inside the accessing class,
  5598. // access is allowed regardless of class-level private or protected tags.
  5599. //
  5600. // class AccessingClass {
  5601. // functionDoingAccess() { }
  5602. // class DefiningClass {
  5603. // varBeingAccessed;
  5604. // }
  5605. // }
  5606. if(definedBy.outerSDType == accessedBy)
  5607. return;
  5608. // If the field's class is defined two or more levels inside the accessing class,
  5609. // access is denied if the defining class is tagged private.
  5610. //
  5611. // class AccessingClass {
  5612. // functionDoingAccess() { }
  5613. // .
  5614. // .
  5615. // .
  5616. // class IntermediateClass {
  5617. // private class DefiningClass {
  5618. // varBeingAccessed;
  5619. // }
  5620. // }
  5621. // .
  5622. // .
  5623. // .
  5624. // }
  5625. if((definedBy.accessLevel & ScriptReduce.SDT_PRIVATE) != 0)
  5626. {
  5627. ErrorMsg(errorAt, "member " + var.fullName + " cannot be accessed by " + curDeclFunc.fullName +
  5628. " because of private class " + definedBy.longName.val);
  5629. return;
  5630. }
  5631. // Likewise, if DefiningClass is tagged protected, the AccessingClass must derive from the
  5632. // IntermediateClass or access is denied.
  5633. if((definedBy.accessLevel & ScriptReduce.SDT_PROTECTED) != 0)
  5634. {
  5635. for(TokenDeclSDType extends = accessedBy; extends != definedBy.outerSDType; extends = extends.extends)
  5636. {
  5637. if(extends == null)
  5638. {
  5639. ErrorMsg(errorAt, "member " + var.fullName + " cannot be accessed by " + curDeclFunc.fullName +
  5640. " because of protected class " + definedBy.longName.val);
  5641. return;
  5642. }
  5643. }
  5644. }
  5645. // Check next outer level.
  5646. definedBy = definedBy.outerSDType;
  5647. } while(definedBy != null);
  5648. }
  5649. /**
  5650. * @brief Convert a list of argument types to printable string, eg, "(list,string,float,integer)"
  5651. * If given a null, return "" indicating it is a field not a method
  5652. */
  5653. public static string ArgSigString(TokenType[] argsig)
  5654. {
  5655. if(argsig == null)
  5656. return string.Empty;
  5657. if(argsig.Length == 0)
  5658. return "()";
  5659. StringBuilder sb = new ();
  5660. sb.Append('(');
  5661. for (int i = 0; i < argsig.Length; i++)
  5662. {
  5663. if(i > 0)
  5664. sb.Append(',');
  5665. sb.Append(argsig[i].ToString());
  5666. }
  5667. sb.Append(')');
  5668. return sb.ToString();
  5669. }
  5670. /**
  5671. * @brief output error message and remember that we did
  5672. */
  5673. public void ErrorMsg(Token token, string message)
  5674. {
  5675. if((token == null) || (token.emsg == null))
  5676. token = errorMessageToken;
  5677. if(!youveAnError || (token.file != lastErrorFile) || (token.line > lastErrorLine))
  5678. {
  5679. token.ErrorMsg(message);
  5680. youveAnError = true;
  5681. lastErrorFile = token.file;
  5682. lastErrorLine = token.line;
  5683. }
  5684. }
  5685. /**
  5686. * @brief Find a private static method.
  5687. * @param owner = class the method is part of
  5688. * @param name = name of method to find
  5689. * @param args = array of argument types
  5690. * @returns pointer to method
  5691. */
  5692. public static MethodInfo GetStaticMethod(Type owner, string name, Type[] args)
  5693. {
  5694. return owner.GetMethod(name, BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic, null, args, null) ??
  5695. throw new Exception("undefined method " + owner.ToString() + "." + name);
  5696. }
  5697. // http://wiki.secondlife.com/wiki/Rotation 'negate a rotation' says just negate .s component
  5698. // but http://wiki.secondlife.com/wiki/LSL_Language_Test (lslangtest1.lsl) says negate all 4 values
  5699. public static LSL_Rotation LSLRotationNegate(LSL_Rotation r)
  5700. {
  5701. return new LSL_Rotation(-r.x, -r.y, -r.z, -r.s);
  5702. }
  5703. public static LSL_Vector LSLVectorNegate(LSL_Vector v)
  5704. {
  5705. return -v;
  5706. }
  5707. public static string CatchExcToStr(Exception exc)
  5708. {
  5709. return exc.ToString();
  5710. }
  5711. //public static void ConsoleWrite (string str) { Console.Write(str); }
  5712. /**
  5713. * @brief Defines an internal label that is used as a target for 'break' and 'continue' statements.
  5714. */
  5715. private class BreakContTarg
  5716. {
  5717. public bool used;
  5718. public ScriptMyLabel label;
  5719. public TokenStmtBlock block;
  5720. public BreakContTarg(ScriptCodeGen scg, string name)
  5721. {
  5722. used = false; // assume it isn't referenced at all
  5723. label = scg.ilGen.DefineLabel(name); // label that the break/continue jumps to
  5724. block = scg.curStmtBlock; // { ... } that the break/continue label is in
  5725. }
  5726. }
  5727. }
  5728. /**
  5729. * @brief Marker interface indicates an exception that can't be caught by a script-level try/catch.
  5730. */
  5731. public interface IXMRUncatchable
  5732. {
  5733. }
  5734. /**
  5735. * @brief Thrown by a script when it attempts to change to an undefined state.
  5736. * These can be detected at compile time but the moron XEngine compiles
  5737. * such things, so we compile them as runtime errors.
  5738. */
  5739. [SerializableAttribute]
  5740. public class ScriptUndefinedStateException: Exception, ISerializable
  5741. {
  5742. public string stateName;
  5743. public ScriptUndefinedStateException(string stateName) : base("undefined state " + stateName)
  5744. {
  5745. this.stateName = stateName;
  5746. }
  5747. }
  5748. /**
  5749. * @brief Created by a throw statement.
  5750. */
  5751. [SerializableAttribute]
  5752. public class ScriptThrownException: Exception, ISerializable
  5753. {
  5754. public object thrown;
  5755. /**
  5756. * @brief Called by a throw statement to wrap the object in a unique
  5757. * tag that capable of capturing a stack trace. Script can
  5758. * unwrap it by calling xmrExceptionThrownValue().
  5759. */
  5760. public static Exception Wrap(object thrown)
  5761. {
  5762. return new ScriptThrownException(thrown);
  5763. }
  5764. private ScriptThrownException(object thrown) : base(thrown.ToString())
  5765. {
  5766. this.thrown = thrown;
  5767. }
  5768. }
  5769. /**
  5770. * @brief Thrown by a script when it attempts to change to a defined state.
  5771. */
  5772. [SerializableAttribute]
  5773. public class ScriptChangeStateException: Exception, ISerializable, IXMRUncatchable
  5774. {
  5775. public int newState;
  5776. public ScriptChangeStateException(int newState)
  5777. {
  5778. this.newState = newState;
  5779. }
  5780. }
  5781. /**
  5782. * @brief We are restoring to the body of a catch { } so we need to
  5783. * wrap the original exception in an outer exception, so the
  5784. * system won't try to refill the stack trace.
  5785. *
  5786. * We don't mark this one serializable as it should never get
  5787. * serialized out. It only lives from the throw to the very
  5788. * beginning of the catch handler where it is promptly unwrapped.
  5789. * No CheckRun() call can possibly intervene.
  5790. */
  5791. public class ScriptRestoreCatchException: Exception
  5792. {
  5793. // old code uses these
  5794. private readonly object e;
  5795. public ScriptRestoreCatchException(object e)
  5796. {
  5797. this.e = e;
  5798. }
  5799. public static object Unwrap(object o)
  5800. {
  5801. if(o is IXMRUncatchable)
  5802. return null;
  5803. if(o is ScriptRestoreCatchException oe)
  5804. return oe.e;
  5805. return o;
  5806. }
  5807. // new code uses these
  5808. private readonly Exception ee;
  5809. public ScriptRestoreCatchException(Exception ee)
  5810. {
  5811. this.ee = ee;
  5812. }
  5813. public static Exception Unwrap(Exception oo)
  5814. {
  5815. if(oo is IXMRUncatchable)
  5816. return null;
  5817. if(oo is ScriptRestoreCatchException ooe)
  5818. return ooe.ee;
  5819. return oo;
  5820. }
  5821. }
  5822. [SerializableAttribute]
  5823. public class ScriptBadCallNoException: Exception
  5824. {
  5825. public ScriptBadCallNoException(int callNo) : base("bad callNo " + callNo) { }
  5826. }
  5827. public class CVVMismatchException: Exception
  5828. {
  5829. public CVVMismatchException(string msg) : base(msg)
  5830. {
  5831. }
  5832. }
  5833. }