MMRScriptCodeGen.cs 292 KB

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