MMRScriptCodeGen.cs 282 KB

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