MMRScriptCodeGen.cs 283 KB

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