MMRScriptCodeGen.cs 282 KB

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