MMRScriptCodeGen.cs 291 KB

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