MMRScriptCodeGen.cs 282 KB

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