MMRScriptReduce.cs 311 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180
  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. /**
  28. * @brief Reduce parser tokens to abstract syntax tree tokens.
  29. *
  30. * Usage:
  31. *
  32. * tokenBegin = returned by TokenBegin.Analyze ()
  33. * representing the whole script source
  34. * as a flat list of tokens
  35. *
  36. * TokenScript tokenScript = Reduce.Analyze (TokenBegin tokenBegin);
  37. *
  38. * tokenScript = represents the whole script source
  39. * as a tree of tokens
  40. */
  41. using OpenSim.Region.ScriptEngine.Shared.ScriptBase;
  42. using System;
  43. using System.Collections.Generic;
  44. using System.IO;
  45. using System.Reflection;
  46. using System.Reflection.Emit;
  47. using System.Text;
  48. using LSL_Float = OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLFloat;
  49. using LSL_Integer = OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLInteger;
  50. using LSL_Key = OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLString;
  51. using LSL_List = OpenSim.Region.ScriptEngine.Shared.LSL_Types.list;
  52. using LSL_Rotation = OpenSim.Region.ScriptEngine.Shared.LSL_Types.Quaternion;
  53. using LSL_String = OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLString;
  54. using LSL_Vector = OpenSim.Region.ScriptEngine.Shared.LSL_Types.Vector3;
  55. namespace OpenSim.Region.ScriptEngine.Yengine
  56. {
  57. public class ScriptReduce
  58. {
  59. public const uint SDT_PRIVATE = 1;
  60. public const uint SDT_PROTECTED = 2;
  61. public const uint SDT_PUBLIC = 4;
  62. public const uint SDT_ABSTRACT = 8;
  63. public const uint SDT_FINAL = 16;
  64. public const uint SDT_NEW = 32;
  65. public const uint SDT_OVERRIDE = 64;
  66. public const uint SDT_STATIC = 128;
  67. public const uint SDT_VIRTUAL = 256;
  68. private const int ASNPR = 50;
  69. private static Dictionary<Type, int> precedence = PrecedenceInit();
  70. private static readonly Type[] brkCloseOnly = new Type[] { typeof(TokenKwBrkClose) };
  71. private static readonly Type[] cmpGTOnly = new Type[] { typeof(TokenKwCmpGT) };
  72. private static readonly Type[] colonOnly = new Type[] { typeof(TokenKwColon) };
  73. private static readonly Type[] commaOrBrcClose = new Type[] { typeof(TokenKwComma), typeof(TokenKwBrcClose) };
  74. private static readonly Type[] colonOrDotDotDot = new Type[] { typeof(TokenKwColon), typeof(TokenKwDotDotDot) };
  75. private static readonly Type[] parCloseOnly = new Type[] { typeof(TokenKwParClose) };
  76. private static readonly Type[] semiOnly = new Type[] { typeof(TokenKwSemi) };
  77. /**
  78. * @brief Initialize operator precedence table
  79. * @returns with precedence table pointer
  80. */
  81. private static Dictionary<Type, int> PrecedenceInit()
  82. {
  83. Dictionary<Type, int> p = new Dictionary<Type, int>();
  84. // http://www.lslwiki.net/lslwiki/wakka.php?wakka=operators
  85. p.Add(typeof(TokenKwComma), 30);
  86. p.Add(typeof(TokenKwAsnLSh), ASNPR); // all assignment operators of equal precedence
  87. p.Add(typeof(TokenKwAsnRSh), ASNPR); // ... so they get processed strictly right-to-left
  88. p.Add(typeof(TokenKwAsnAdd), ASNPR);
  89. p.Add(typeof(TokenKwAsnAnd), ASNPR);
  90. p.Add(typeof(TokenKwAsnSub), ASNPR);
  91. p.Add(typeof(TokenKwAsnMul), ASNPR);
  92. p.Add(typeof(TokenKwAsnDiv), ASNPR);
  93. p.Add(typeof(TokenKwAsnMod), ASNPR);
  94. p.Add(typeof(TokenKwAsnOr), ASNPR);
  95. p.Add(typeof(TokenKwAsnXor), ASNPR);
  96. p.Add(typeof(TokenKwAssign), ASNPR);
  97. p.Add(typeof(TokenKwQMark), 60);
  98. p.Add(typeof(TokenKwOrOrOr), 70);
  99. p.Add(typeof(TokenKwAndAndAnd), 80);
  100. p.Add(typeof(TokenKwOrOr), 100);
  101. p.Add(typeof(TokenKwAndAnd), 120);
  102. p.Add(typeof(TokenKwOr), 140);
  103. p.Add(typeof(TokenKwXor), 160);
  104. p.Add(typeof(TokenKwAnd), 180);
  105. p.Add(typeof(TokenKwCmpEQ), 200);
  106. p.Add(typeof(TokenKwCmpNE), 200);
  107. p.Add(typeof(TokenKwCmpLT), 240);
  108. p.Add(typeof(TokenKwCmpLE), 240);
  109. p.Add(typeof(TokenKwCmpGT), 240);
  110. p.Add(typeof(TokenKwCmpGE), 240);
  111. p.Add(typeof(TokenKwRSh), 260);
  112. p.Add(typeof(TokenKwLSh), 260);
  113. p.Add(typeof(TokenKwAdd), 280);
  114. p.Add(typeof(TokenKwSub), 280);
  115. p.Add(typeof(TokenKwMul), 320);
  116. p.Add(typeof(TokenKwDiv), 320);
  117. p.Add(typeof(TokenKwMod), 320);
  118. return p;
  119. }
  120. /**
  121. * @brief Reduce raw token stream to a single script token.
  122. * Performs a little semantic testing, ie, undefined variables, etc.
  123. * @param tokenBegin = points to a TokenBegin
  124. * followed by raw tokens
  125. * and last token is a TokenEnd
  126. * @returns null: not a valid script, error messages have been output
  127. * else: valid script top token
  128. */
  129. public static TokenScript Reduce(TokenBegin tokenBegin)
  130. {
  131. return new ScriptReduce(tokenBegin).tokenScript;
  132. }
  133. /*
  134. * Instance variables.
  135. */
  136. private bool errors = false;
  137. private string lastErrorFile = "";
  138. private int lastErrorLine = 0;
  139. private int numTypedefs = 0;
  140. private TokenDeclVar currentDeclFunc = null;
  141. private TokenDeclSDType currentDeclSDType = null;
  142. private TokenScript tokenScript;
  143. private TokenStmtBlock currentStmtBlock = null;
  144. /**
  145. * @brief the constructor does all the processing.
  146. * @param token = first token of script after the TokenBegin token
  147. * @returns tokenScript = null: there were errors
  148. * else: successful
  149. */
  150. private ScriptReduce(TokenBegin tokenBegin)
  151. {
  152. // Create a place to put the top-level script components,
  153. // eg, state bodies, functions, global variables.
  154. tokenScript = new TokenScript(tokenBegin.nextToken);
  155. // 'class', 'delegate', 'instance' all define types.
  156. // So we pre-scan the source tokens for those keywords
  157. // to build a script-defined type table and substitute
  158. // type tokens for those names in the source. This is
  159. // done as a separate scan so they can cross-reference
  160. // each other. Also does likewise for fixed array types.
  161. //
  162. // Also, all 'typedef's are processed here. Their definitions
  163. // remain in the source token stream after this, but they can
  164. // be skipped over, because their bodies have been substituted
  165. // in the source for any references.
  166. ParseSDTypePreScanPassOne(tokenBegin); // catalog definitions
  167. ParseSDTypePreScanPassTwo(tokenBegin); // substitute references
  168. /*
  169. int braces = 0;
  170. Token prevTok = null;
  171. for (Token token = tokenBegin; token != null; token = token.nextToken) {
  172. if (token is TokenKwParClose) braces -= 2;
  173. if (token is TokenKwBrcClose) braces -= 4;
  174. StringBuilder sb = new StringBuilder ("ScriptReduce*: ");
  175. sb.Append (token.GetHashCode ().ToString ("X8"));
  176. sb.Append (" ");
  177. sb.Append (token.line.ToString ().PadLeft (3));
  178. sb.Append (".");
  179. sb.Append (token.posn.ToString ().PadLeft (3));
  180. sb.Append (" ");
  181. sb.Append (token.GetType ().Name.PadRight (24));
  182. sb.Append (" : ");
  183. for (int i = 0; i < braces; i ++) sb.Append (' ');
  184. token.DebString (sb);
  185. Console.WriteLine (sb.ToString ());
  186. if (token.prevToken != prevTok) {
  187. Console.WriteLine ("ScriptReduce*: -- prevToken link bad => " + token.prevToken.GetHashCode ().ToString ("X8"));
  188. }
  189. if (token is TokenKwBrcOpen) braces += 4;
  190. if (token is TokenKwParOpen) braces += 2;
  191. prevTok = token;
  192. }
  193. */
  194. // Create a function $globalvarinit to hold all explicit
  195. // global variable initializations.
  196. TokenDeclVar gviFunc = new TokenDeclVar(tokenBegin, null, tokenScript);
  197. gviFunc.name = new TokenName(gviFunc, "$globalvarinit");
  198. gviFunc.retType = new TokenTypeVoid(gviFunc);
  199. gviFunc.argDecl = new TokenArgDecl(gviFunc);
  200. TokenStmtBlock gviBody = new TokenStmtBlock(gviFunc);
  201. gviBody.function = gviFunc;
  202. gviFunc.body = gviBody;
  203. tokenScript.globalVarInit = gviFunc;
  204. tokenScript.AddVarEntry(gviFunc);
  205. // Scan through the tokens until we reach the end.
  206. for(Token token = tokenBegin.nextToken; !(token is TokenEnd);)
  207. {
  208. if(token is TokenKwSemi)
  209. {
  210. token = token.nextToken;
  211. continue;
  212. }
  213. // Script-defined type declarations.
  214. if(ParseDeclSDTypes(ref token, null, SDT_PUBLIC))
  215. continue;
  216. // constant <name> = <rval> ;
  217. if(token is TokenKwConst)
  218. {
  219. ParseDeclVar(ref token, null);
  220. continue;
  221. }
  222. // <type> <name> ;
  223. // <type> <name> = <rval> ;
  224. if((token is TokenType) &&
  225. (token.nextToken is TokenName) &&
  226. ((token.nextToken.nextToken is TokenKwSemi) ||
  227. (token.nextToken.nextToken is TokenKwAssign)))
  228. {
  229. TokenDeclVar var = ParseDeclVar(ref token, gviFunc);
  230. if(var != null)
  231. {
  232. // <name> = <init>;
  233. TokenLValName left = new TokenLValName(var.name, tokenScript.variablesStack);
  234. DoVarInit(gviFunc, left, var.init);
  235. }
  236. continue;
  237. }
  238. // <type> <name> { [ get { <body> } ] [ set { <body> } ] }
  239. if((token is TokenType) &&
  240. (token.nextToken is TokenName) &&
  241. (token.nextToken.nextToken is TokenKwBrcOpen))
  242. {
  243. ParseProperty(ref token, false, true);
  244. continue;
  245. }
  246. // <type> <name> <funcargs> <funcbody>
  247. // global function returning specified type
  248. if(token is TokenType)
  249. {
  250. TokenType tokenType = (TokenType)token;
  251. token = token.nextToken;
  252. if(!(token is TokenName))
  253. {
  254. ErrorMsg(token, "expecting variable/function name");
  255. token = SkipPastSemi(token);
  256. continue;
  257. }
  258. TokenName tokenName = (TokenName)token;
  259. token = token.nextToken;
  260. if(!(token is TokenKwParOpen))
  261. {
  262. ErrorMsg(token, "<type> <name> must be followed by ; = or (");
  263. token = SkipPastSemi(token);
  264. continue;
  265. }
  266. token = tokenType;
  267. TokenDeclVar tokenDeclFunc = ParseDeclFunc(ref token, false, false, false);
  268. if(tokenDeclFunc == null)
  269. continue;
  270. if(!tokenScript.AddVarEntry(tokenDeclFunc))
  271. {
  272. ErrorMsg(tokenName, "duplicate function " + tokenDeclFunc.funcNameSig.val);
  273. }
  274. continue;
  275. }
  276. // <name> <funcargs> <funcbody>
  277. // global function returning void
  278. if(token is TokenName)
  279. {
  280. TokenName tokenName = (TokenName)token;
  281. token = token.nextToken;
  282. if(!(token is TokenKwParOpen))
  283. {
  284. ErrorMsg(token, "looking for open paren after assuming " +
  285. tokenName.val + " is a function name");
  286. token = SkipPastSemi(token);
  287. continue;
  288. }
  289. token = tokenName;
  290. TokenDeclVar tokenDeclFunc = ParseDeclFunc(ref token, false, false, false);
  291. if(tokenDeclFunc == null)
  292. continue;
  293. if(!tokenScript.AddVarEntry(tokenDeclFunc))
  294. ErrorMsg(tokenName, "duplicate function " + tokenDeclFunc.funcNameSig.val);
  295. continue;
  296. }
  297. // default <statebody>
  298. if(token is TokenKwDefault)
  299. {
  300. TokenDeclState tokenDeclState = new TokenDeclState(token);
  301. token = token.nextToken;
  302. tokenDeclState.body = ParseStateBody(ref token);
  303. if(tokenDeclState.body == null)
  304. continue;
  305. if(tokenScript.defaultState != null)
  306. {
  307. ErrorMsg(tokenDeclState, "default state already declared");
  308. continue;
  309. }
  310. tokenScript.defaultState = tokenDeclState;
  311. continue;
  312. }
  313. // state <name> <statebody>
  314. if(token is TokenKwState)
  315. {
  316. TokenDeclState tokenDeclState = new TokenDeclState(token);
  317. token = token.nextToken;
  318. if(!(token is TokenName))
  319. {
  320. ErrorMsg(token, "state must be followed by state name");
  321. token = SkipPastSemi(token);
  322. continue;
  323. }
  324. tokenDeclState.name = (TokenName)token;
  325. token = token.nextToken;
  326. tokenDeclState.body = ParseStateBody(ref token);
  327. if(tokenDeclState.body == null)
  328. continue;
  329. if(tokenScript.states.ContainsKey(tokenDeclState.name.val))
  330. {
  331. ErrorMsg(tokenDeclState.name, "duplicate state definition");
  332. continue;
  333. }
  334. tokenScript.states.Add(tokenDeclState.name.val, tokenDeclState);
  335. continue;
  336. }
  337. // Doesn't fit any of those forms, output message and skip to next statement.
  338. ErrorMsg(token, "looking for var name, type, state or default, script-defined type declaration");
  339. token = SkipPastSemi(token);
  340. continue;
  341. }
  342. // Must have a default state to start in.
  343. if(!errors && (tokenScript.defaultState == null))
  344. {
  345. ErrorMsg(tokenScript, "no default state defined");
  346. }
  347. // If any error messages were written out, set return value to null.
  348. if(errors)
  349. tokenScript = null;
  350. }
  351. /**
  352. * @brief Pre-scan the source for class, delegate, interface, typedef definition keywords.
  353. * Clump the keywords and name being defined together, but leave the body intact.
  354. * In the case of a delegate with an explicit return type, it reverses the name and return type.
  355. * After this completes there shouldn't be any TokenKw{Class,Delegate,Interface,Typedef}
  356. * keywords in the source, they are all replaced by TokenDeclSDType{Class,Delegate,Interface,
  357. * Typedef} tokens which also encapsulate the name of the type being defined and any generic
  358. * parameter names. The body remains intact in the source token stream following the
  359. * TokenDeclSDType* token.
  360. */
  361. private void ParseSDTypePreScanPassOne(Token tokenBegin)
  362. {
  363. Stack<int> braceLevels = new Stack<int>();
  364. Stack<TokenDeclSDType> outerLevels = new Stack<TokenDeclSDType>();
  365. int openBraceLevel = 0;
  366. braceLevels.Push(-1);
  367. outerLevels.Push(null);
  368. for(Token t = tokenBegin; !((t = t.nextToken) is TokenEnd);)
  369. {
  370. // Keep track of nested definitions so we can link them up.
  371. // We also need to detect the end of class and interface definitions.
  372. if(t is TokenKwBrcOpen)
  373. {
  374. openBraceLevel++;
  375. continue;
  376. }
  377. if(t is TokenKwBrcClose)
  378. {
  379. if(--openBraceLevel < 0)
  380. {
  381. ErrorMsg(t, "{ } mismatch");
  382. return;
  383. }
  384. if(braceLevels.Peek() == openBraceLevel)
  385. {
  386. braceLevels.Pop();
  387. outerLevels.Pop().endToken = t;
  388. }
  389. continue;
  390. }
  391. // Check for 'class' or 'interface'.
  392. // They always define a new class or interface.
  393. // They can contain nested script-defined type definitions.
  394. if((t is TokenKwClass) || (t is TokenKwInterface))
  395. {
  396. Token kw = t;
  397. t = t.nextToken;
  398. if(!(t is TokenName))
  399. {
  400. ErrorMsg(t, "expecting class or interface name");
  401. t = SkipPastSemi(t).prevToken;
  402. continue;
  403. }
  404. TokenName name = (TokenName)t;
  405. t = t.nextToken;
  406. // Malloc the script-defined type object.
  407. TokenDeclSDType decl;
  408. if(kw is TokenKwClass)
  409. decl = new TokenDeclSDTypeClass(name, kw.prevToken is TokenKwPartial);
  410. else
  411. decl = new TokenDeclSDTypeInterface(name);
  412. decl.outerSDType = outerLevels.Peek();
  413. // Check for generic parameter list.
  414. if(!ParseGenProtoParamList(ref t, decl))
  415. continue;
  416. // Splice in a TokenDeclSDType token that replaces the keyword and the name tokens
  417. // and any generic parameters including the '<', ','s and '>'.
  418. // kw = points to 'class' or 'interface' keyword.
  419. // t = points to just past last part of class name parsed, hopefully a ':' or '{'.
  420. decl.prevToken = decl.isPartial ? kw.prevToken.prevToken : kw.prevToken;
  421. decl.nextToken = t;
  422. decl.prevToken.nextToken = decl;
  423. decl.nextToken.prevToken = decl;
  424. // Enter it in name lists so it can be seen by others.
  425. Token partialNewBody = CatalogSDTypeDecl(decl);
  426. // Start inner type definitions.
  427. braceLevels.Push(openBraceLevel);
  428. outerLevels.Push(decl);
  429. // Scan the body starting on for before the '{'.
  430. //
  431. // If this body had an old partial merged into it,
  432. // resume scanning at the beginning of the new body,
  433. // ie, what used to be the first token after the '{'
  434. // before the old body was spliced in.
  435. if(partialNewBody != null)
  436. {
  437. // We have a partial that has had old partial body merged
  438. // into new partial body. So resume scanning at the beginning
  439. // of the new partial body so we don't get any duplicate scanning
  440. // of the old partial body.
  441. //
  442. // <decl> ... { <oldbody> <newbody> }
  443. // ^- resume scanning here
  444. // but inc openBraceLevel because
  445. // we skipped scanning the '{'
  446. openBraceLevel++;
  447. t = partialNewBody;
  448. }
  449. t = t.prevToken;
  450. continue;
  451. }
  452. // Check for 'delegate'.
  453. // It always defines a new delegate.
  454. // Delegates never define nested types.
  455. if(t is TokenKwDelegate)
  456. {
  457. Token kw = t;
  458. t = t.nextToken;
  459. // Next thing might be an explicit return type or the delegate's name.
  460. // If it's a type token, then it's the return type, simple enough.
  461. // But if it's a name token, it might be the name of some other script-defined type.
  462. // The way to tell is that the delegate name is followed by a '(', whereas an
  463. // explicit return type is followed by the delegate name.
  464. Token retType = t;
  465. TokenName delName = null;
  466. Token u;
  467. int angles = 0;
  468. for(u = t; !(u is TokenKwParOpen); u = u.nextToken)
  469. {
  470. if((u is TokenKwSemi) || (u is TokenEnd))
  471. break;
  472. if(u is TokenKwCmpLT)
  473. angles++;
  474. if(u is TokenKwCmpGT)
  475. angles--;
  476. if(u is TokenKwRSh)
  477. angles -= 2; // idiot >>
  478. if((angles == 0) && (u is TokenName))
  479. delName = (TokenName)u;
  480. }
  481. if(!(u is TokenKwParOpen))
  482. {
  483. ErrorMsg(u, "expecting ( for delegate parameter list");
  484. t = SkipPastSemi(t).prevToken;
  485. continue;
  486. }
  487. if(delName == null)
  488. {
  489. ErrorMsg(u, "expecting delegate name");
  490. t = SkipPastSemi(t).prevToken;
  491. continue;
  492. }
  493. if(retType == delName)
  494. retType = null;
  495. // Malloc the script-defined type object.
  496. TokenDeclSDTypeDelegate decl = new TokenDeclSDTypeDelegate(delName);
  497. decl.outerSDType = outerLevels.Peek();
  498. // Check for generic parameter list.
  499. t = delName.nextToken;
  500. if(!ParseGenProtoParamList(ref t, decl))
  501. continue;
  502. // Enter it in name lists so it can be seen by others.
  503. CatalogSDTypeDecl(decl);
  504. // Splice in the token that replaces the 'delegate' keyword and the whole name
  505. // (including the '<' name ... '>' parts). The return type token(s), if any,
  506. // follow the splice token and come before the '('.
  507. decl.prevToken = kw.prevToken;
  508. kw.prevToken.nextToken = decl;
  509. if(retType == null)
  510. {
  511. decl.nextToken = t;
  512. t.prevToken = decl;
  513. }
  514. else
  515. {
  516. decl.nextToken = retType;
  517. retType.prevToken = decl;
  518. retType.nextToken = t;
  519. t.prevToken = retType;
  520. }
  521. // Scan for terminating ';'.
  522. // There cannot be an intervening class, delegate, interfate, typedef, { or }.
  523. for(t = decl; !(t is TokenKwSemi); t = u)
  524. {
  525. u = t.nextToken;
  526. if((u is TokenEnd) ||
  527. (u is TokenKwClass) ||
  528. (u is TokenKwDelegate) ||
  529. (u is TokenKwInterface) ||
  530. (u is TokenKwTypedef) ||
  531. (u is TokenKwBrcOpen) ||
  532. (u is TokenKwBrcClose))
  533. {
  534. ErrorMsg(t, "delegate missing terminating ;");
  535. break;
  536. }
  537. }
  538. decl.endToken = t;
  539. continue;
  540. }
  541. // Check for 'typedef'.
  542. // It always defines a new macro.
  543. // Typedefs never define nested types.
  544. if(t is TokenKwTypedef)
  545. {
  546. Token kw = t;
  547. t = t.nextToken;
  548. if(!(t is TokenName))
  549. {
  550. ErrorMsg(t, "expecting typedef name");
  551. t = SkipPastSemi(t).prevToken;
  552. continue;
  553. }
  554. TokenName tdName = (TokenName)t;
  555. t = t.nextToken;
  556. // Malloc the script-defined type object.
  557. TokenDeclSDTypeTypedef decl = new TokenDeclSDTypeTypedef(tdName);
  558. decl.outerSDType = outerLevels.Peek();
  559. // Check for generic parameter list.
  560. if(!ParseGenProtoParamList(ref t, decl))
  561. continue;
  562. // Enter it in name lists so it can be seen by others.
  563. CatalogSDTypeDecl(decl);
  564. numTypedefs++;
  565. // Splice in the token that replaces the 'typedef' keyword and the whole name
  566. // (including the '<' name ... '>' parts).
  567. decl.prevToken = kw.prevToken;
  568. kw.prevToken.nextToken = decl;
  569. decl.nextToken = t;
  570. t.prevToken = decl;
  571. // Scan for terminating ';'.
  572. // There cannot be an intervening class, delegate, interfate, typedef, { or }.
  573. Token u;
  574. for(t = decl; !(t is TokenKwSemi); t = u)
  575. {
  576. u = t.nextToken;
  577. if((u is TokenEnd) ||
  578. (u is TokenKwClass) ||
  579. (u is TokenKwDelegate) ||
  580. (u is TokenKwInterface) ||
  581. (u is TokenKwTypedef) ||
  582. (u is TokenKwBrcOpen) ||
  583. (u is TokenKwBrcClose))
  584. {
  585. ErrorMsg(t, "typedef missing terminating ;");
  586. break;
  587. }
  588. }
  589. decl.endToken = t;
  590. continue;
  591. }
  592. }
  593. }
  594. /**
  595. * @brief Parse a possibly generic type definition's parameter list.
  596. * @param t = points to the possible opening '<' on entry
  597. * points just past the closing '>' on return
  598. * @param decl = the generic type being declared
  599. * @returns false: parse error
  600. * true: decl.genParams = filled in with parameter list
  601. * decl.innerSDTypes = filled in with parameter list
  602. */
  603. private bool ParseGenProtoParamList(ref Token t, TokenDeclSDType decl)
  604. {
  605. // Maybe there aren't any generic parameters.
  606. // If so, leave decl.genParams = null.
  607. if(!(t is TokenKwCmpLT))
  608. return true;
  609. // Build list of generic parameter names.
  610. Dictionary<string, int> parms = new Dictionary<string, int>();
  611. do
  612. {
  613. t = t.nextToken;
  614. if(!(t is TokenName))
  615. {
  616. ErrorMsg(t, "expecting generic parameter name");
  617. break;
  618. }
  619. TokenName tn = (TokenName)t;
  620. if(parms.ContainsKey(tn.val))
  621. ErrorMsg(tn, "duplicate use of generic parameter name");
  622. else
  623. parms.Add(tn.val, parms.Count);
  624. t = t.nextToken;
  625. } while(t is TokenKwComma);
  626. if(!(t is TokenKwCmpGT))
  627. {
  628. ErrorMsg(t, "expecting , for more params or > to end param list");
  629. return false;
  630. }
  631. t = t.nextToken;
  632. decl.genParams = parms;
  633. return true;
  634. }
  635. /**
  636. * @brief Catalog a script-defined type.
  637. * Its short name (eg, 'Node') gets put in the next outer level (eg, 'List')'s inner type definition table.
  638. * Its long name (eg, 'List.Node') gets put in the global type definition table.
  639. */
  640. public Token CatalogSDTypeDecl(TokenDeclSDType decl)
  641. {
  642. string longName = decl.longName.val;
  643. TokenDeclSDType dupDecl;
  644. if(!tokenScript.sdSrcTypesTryGetValue(longName, out dupDecl))
  645. {
  646. tokenScript.sdSrcTypesAdd(longName, decl);
  647. if(decl.outerSDType != null)
  648. decl.outerSDType.innerSDTypes.Add(decl.shortName.val, decl);
  649. return null;
  650. }
  651. if(!dupDecl.isPartial || !decl.isPartial)
  652. {
  653. ErrorMsg(decl, "duplicate definition of type " + longName);
  654. ErrorMsg(dupDecl, "previous definition here");
  655. return null;
  656. }
  657. if(!GenericParametersMatch(decl, dupDecl))
  658. ErrorMsg(decl, "all partial class generic parameters must match");
  659. // Have new declaration be the cataloged one because body is going to get
  660. // snipped out of old declaration and pasted into new declaration.
  661. tokenScript.sdSrcTypesRep(longName, decl);
  662. if(decl.outerSDType != null)
  663. decl.outerSDType.innerSDTypes[decl.shortName.val] = decl;
  664. // Find old partial definition's opening brace.
  665. Token dupBrcOpen;
  666. for(dupBrcOpen = dupDecl; !(dupBrcOpen is TokenKwBrcOpen); dupBrcOpen = dupBrcOpen.nextToken)
  667. {
  668. if(dupBrcOpen == dupDecl.endToken)
  669. {
  670. ErrorMsg(dupDecl, "missing {");
  671. return null;
  672. }
  673. }
  674. // Find new partial definition's opening brace.
  675. Token brcOpen;
  676. for(brcOpen = decl; !(brcOpen is TokenKwBrcOpen); brcOpen = brcOpen.nextToken)
  677. {
  678. if(brcOpen is TokenEnd)
  679. {
  680. ErrorMsg(decl, "missing {");
  681. return null;
  682. }
  683. }
  684. Token body = brcOpen.nextToken;
  685. // Stick old partial definition's extends/implementeds list just
  686. // in front of new partial definition's extends/implementeds list.
  687. //
  688. // class oldextimp { oldbody } ...
  689. // dupDecl dupBrcOpen dupDecl.endToken
  690. //
  691. // class newextimp { newbody } ...
  692. // decl brcOpen body decl.endToken
  693. //
  694. // becomes
  695. //
  696. // class ...
  697. // dupDecl
  698. // dupDecl.endToken
  699. //
  700. // class oldextimp newextimp { oldbody newbody } ...
  701. // decl brcOpen body decl.endToken
  702. if(dupBrcOpen != dupDecl.nextToken)
  703. {
  704. dupBrcOpen.prevToken.nextToken = decl.nextToken;
  705. dupDecl.nextToken.prevToken = decl;
  706. decl.nextToken.prevToken = dupBrcOpen.prevToken;
  707. decl.nextToken = dupDecl.nextToken;
  708. }
  709. // Stick old partial definition's body just
  710. // in front of new partial definition's body.
  711. if(dupBrcOpen.nextToken != dupDecl.endToken)
  712. {
  713. dupBrcOpen.nextToken.prevToken = brcOpen;
  714. dupDecl.endToken.prevToken.nextToken = body;
  715. body.prevToken = dupDecl.endToken.prevToken;
  716. brcOpen.nextToken = dupBrcOpen.nextToken;
  717. }
  718. // Null out old definition's extends/implementeds list and body
  719. // by having the declaration token be the only thing left.
  720. dupDecl.nextToken = dupDecl.endToken.nextToken;
  721. dupDecl.nextToken.prevToken = dupDecl;
  722. dupDecl.endToken = dupDecl;
  723. return body;
  724. }
  725. /**
  726. * @brief Determine whether or not the generic parameters of two class declarations match exactly.
  727. */
  728. private static bool GenericParametersMatch(TokenDeclSDType c1, TokenDeclSDType c2)
  729. {
  730. if((c1.genParams == null) && (c2.genParams == null))
  731. return true;
  732. if((c1.genParams == null) || (c2.genParams == null))
  733. return false;
  734. Dictionary<string, int> gp1 = c1.genParams;
  735. Dictionary<string, int> gp2 = c2.genParams;
  736. if(gp1.Count != gp2.Count)
  737. return false;
  738. foreach(KeyValuePair<string, int> kvp1 in gp1)
  739. {
  740. int v2;
  741. if(!gp2.TryGetValue(kvp1.Key, out v2))
  742. return false;
  743. if(v2 != kvp1.Value)
  744. return false;
  745. }
  746. return true;
  747. }
  748. /**
  749. * @brief Replace all TokenName tokens that refer to the script-defined types with
  750. * corresponding TokenTypeSDType{Class,Delegate,GenParam,Interface} tokens.
  751. * Also handle generic references, ie, recognize that 'List<integer>' is an
  752. * instantiation of 'List<>' and instantiate the generic.
  753. */
  754. private const uint REPEAT_NOTYPE = 1;
  755. private const uint REPEAT_INSTGEN = 2;
  756. private const uint REPEAT_SUBST = 4;
  757. private void ParseSDTypePreScanPassTwo(Token tokenBegin)
  758. {
  759. List<Token> noTypes = new List<Token>();
  760. TokenDeclSDType outerSDType;
  761. uint repeat;
  762. do
  763. {
  764. repeat = 0;
  765. outerSDType = null;
  766. noTypes.Clear();
  767. for(Token t = tokenBegin; !((t = t.nextToken) is TokenEnd);)
  768. {
  769. // Maybe it's time to pop out of an outer class definition.
  770. if((outerSDType != null) && (outerSDType.endToken == t))
  771. {
  772. outerSDType = outerSDType.outerSDType;
  773. continue;
  774. }
  775. // Skip completely over any script-defined generic prototypes.
  776. // We only need to process their instantiations which are non-
  777. // generic versions of the generics.
  778. if((t is TokenDeclSDType) && (((TokenDeclSDType)t).genParams != null))
  779. {
  780. t = ((TokenDeclSDType)t).endToken;
  781. continue;
  782. }
  783. // Check for beginning of non-generic script-defined type definitions.
  784. // They can have nested definitions in their innerSDTypes[] that match
  785. // name tokens, so add them to the stack.
  786. //
  787. // But just ignore any preliminary partial definitions as they have had
  788. // their entire contents spliced out and spliced into a subsequent partial
  789. // definition. So if we originally had:
  790. // partial class Abc { public intenger one; }
  791. // partial class Abc { public intenger two; }
  792. // We now have:
  793. // partial_class_Abc <== if we are here, just ignore the partial_class_Abc token
  794. // partial_class_Abc { public intenger one; public intenger two; }
  795. if(t is TokenDeclSDType)
  796. {
  797. if(((TokenDeclSDType)t).endToken != t)
  798. outerSDType = (TokenDeclSDType)t;
  799. continue;
  800. }
  801. // For names not preceded by a '.', scan the script-defined type definition
  802. // stack for that name. Splice the name out and replace with equivalent token.
  803. if((t is TokenName) && !(t.prevToken is TokenKwDot))
  804. t = TrySpliceTypeRef(t, outerSDType, ref repeat, noTypes);
  805. // This handles types such as integer[,][], List<string>[], etc.
  806. // They are an instantiation of an internally generated type of the same name, brackets and all.
  807. // Note that to malloc an array, use something like 'new float[,][](3,5)', not 'new float[3,5][]'.
  808. //
  809. // Note that we must not get confused by $idxprop property declarations such as:
  810. // float [string kee] { get { ... } }
  811. // ... and try to convert 'float' '[' to an array type.
  812. if((t is TokenType) && (t.nextToken is TokenKwBrkOpen))
  813. {
  814. if((t.nextToken.nextToken is TokenKwBrkClose) ||
  815. (t.nextToken.nextToken is TokenKwComma))
  816. {
  817. t = InstantiateJaggedArray(t, tokenBegin, ref repeat);
  818. }
  819. }
  820. }
  821. // If we instantiated a generic, loop back to process its contents
  822. // just as if the source code had the instantiated code to begin with.
  823. // Also repeat if we found a non-type inside the <> of a generic reference
  824. // provided we have made at least one name->type substitution.
  825. } while(((repeat & REPEAT_INSTGEN) != 0) ||
  826. ((repeat & (REPEAT_NOTYPE | REPEAT_SUBST)) == (REPEAT_NOTYPE | REPEAT_SUBST)));
  827. // These are places where we required a type be present,
  828. // eg, a generic type argument or the body of a typedef.
  829. foreach(Token t in noTypes)
  830. ErrorMsg(t, "looking for type");
  831. }
  832. /**
  833. * @brief Try to convert the source token string to a type reference
  834. * and splice the type reference into the source token string
  835. * replacing the original token(s).
  836. * @param t = points to the initial TokenName token
  837. * @param outerSDType = null: this is a top-level code reference
  838. * else: this code is within outerSDType
  839. * @returns pointer to last token parsed
  840. * possibly with spliced-in type token
  841. * repeat = possibly set true if need to do another pass
  842. */
  843. private Token TrySpliceTypeRef(Token t, TokenDeclSDType outerSDType, ref uint repeat, List<Token> noTypes)
  844. {
  845. Token start = t;
  846. string tnamestr = ((TokenName)t).val;
  847. // Look for the name as a type declared by outerSDType or anything
  848. // even farther out than that. If not found, simply return
  849. // without updating t, meaning that t isn't the name of a type.
  850. TokenDeclSDType decl = null;
  851. while(outerSDType != null)
  852. {
  853. if(outerSDType.innerSDTypes.TryGetValue(tnamestr, out decl))
  854. break;
  855. outerSDType = outerSDType.outerSDType;
  856. }
  857. if((outerSDType == null) && !tokenScript.sdSrcTypesTryGetValue(tnamestr, out decl))
  858. return t;
  859. TokenDeclSDType instdecl;
  860. while(true)
  861. {
  862. // If it is a generic type, it must be followed by instantiation arguments.
  863. instdecl = decl;
  864. if(decl.genParams != null)
  865. {
  866. t = t.nextToken;
  867. if(!(t is TokenKwCmpLT))
  868. {
  869. ErrorMsg(t, "expecting < for generic argument list");
  870. return t;
  871. }
  872. tnamestr += "<";
  873. int nArgs = decl.genParams.Count;
  874. TokenType[] genArgs = new TokenType[nArgs];
  875. for(int i = 0; i < nArgs;)
  876. {
  877. t = t.nextToken;
  878. if(!(t is TokenType))
  879. {
  880. repeat |= REPEAT_NOTYPE;
  881. noTypes.Add(t);
  882. return t.prevToken; // make sure name gets processed
  883. // so substitution can occur on it
  884. }
  885. TokenType ga = (TokenType)t;
  886. genArgs[i] = ga;
  887. tnamestr += ga.ToString();
  888. t = t.nextToken;
  889. if(++i < nArgs)
  890. {
  891. if(!(t is TokenKwComma))
  892. {
  893. ErrorMsg(t, "expecting , for more generic arguments");
  894. return t;
  895. }
  896. tnamestr += ",";
  897. }
  898. }
  899. if(t is TokenKwRSh)
  900. { // idiot >>
  901. Token u = new TokenKwCmpGT(t);
  902. Token v = new TokenKwCmpGT(t);
  903. v.posn++;
  904. u.prevToken = t.prevToken;
  905. u.nextToken = v;
  906. v.nextToken = t.nextToken;
  907. v.prevToken = u;
  908. u.prevToken.nextToken = u;
  909. v.nextToken.prevToken = v;
  910. t = u;
  911. }
  912. if(!(t is TokenKwCmpGT))
  913. {
  914. ErrorMsg(t, "expecting > at end of generic argument list");
  915. return t;
  916. }
  917. tnamestr += ">";
  918. if(outerSDType != null)
  919. {
  920. outerSDType.innerSDTypes.TryGetValue(tnamestr, out instdecl);
  921. }
  922. else
  923. {
  924. tokenScript.sdSrcTypesTryGetValue(tnamestr, out instdecl);
  925. }
  926. // Couldn't find 'List<string>' but found 'List' and we have genArgs = 'string'.
  927. // Instantiate the generic to create 'List<string>'. This splices the definition
  928. // of 'List<string>' into the source token stream just as if it had been there all
  929. // along. We have to then repeat the scan to process the instance's contents.
  930. if(instdecl == null)
  931. {
  932. instdecl = decl.InstantiateGeneric(tnamestr, genArgs, this);
  933. CatalogSDTypeDecl(instdecl);
  934. repeat |= REPEAT_INSTGEN;
  935. }
  936. }
  937. // Maybe caller wants a subtype by putting a '.' following all that.
  938. if(!(t.nextToken is TokenKwDot))
  939. break;
  940. if(!(t.nextToken.nextToken is TokenName))
  941. break;
  942. tnamestr = ((TokenName)t.nextToken.nextToken).val;
  943. if(!instdecl.innerSDTypes.TryGetValue(tnamestr, out decl))
  944. break;
  945. t = t.nextToken.nextToken;
  946. outerSDType = instdecl;
  947. }
  948. // Create a reference in the source to the definition
  949. // that encapsulates the long dotted type name given in
  950. // the source, and replace the long dotted type name in
  951. // the source with the reference token, eg, replace
  952. // 'Dictionary' '<' 'string' ',' 'integer' '>' '.' 'ValueList'
  953. // with 'Dictionary<string,integer>.ValueList'.
  954. TokenType refer = instdecl.MakeRefToken(start);
  955. if(refer == null)
  956. {
  957. // typedef body is not yet a type
  958. noTypes.Add(start);
  959. repeat |= REPEAT_NOTYPE;
  960. return start;
  961. }
  962. refer.prevToken = start.prevToken; // start points right at the first TokenName
  963. refer.nextToken = t.nextToken; // t points at the last TokenName or TokenKwCmpGT
  964. refer.prevToken.nextToken = refer;
  965. refer.nextToken.prevToken = refer;
  966. repeat |= REPEAT_SUBST;
  967. return refer;
  968. }
  969. /**
  970. * @brief We are known to have <type>'[' so make an equivalent array type.
  971. * @param t = points to the TokenType
  972. * @param tokenBegin = where we can safely splice in new array class definitions
  973. * @param repeat = set REPEAT_INSTGEN if new type created
  974. * @returns pointer to last token parsed
  975. * possibly with spliced-in type token
  976. * repeat = possibly set true if need to do another pass
  977. */
  978. private Token InstantiateJaggedArray(Token t, Token tokenBegin, ref uint repeat)
  979. {
  980. Token start = t;
  981. TokenType ofType = (TokenType)t;
  982. Stack<int> ranks = new Stack<int>();
  983. // When script specifies 'float[,][]' it means a two-dimensional matrix
  984. // that points to one-dimensional vectors of floats. So we would push
  985. // a 2 then a 1 in this parsing code...
  986. do
  987. {
  988. t = t.nextToken; // point at '['
  989. int rank = 0;
  990. do
  991. {
  992. rank++; // count '[' and ','s
  993. t = t.nextToken; // point at ',' or ']'
  994. } while(t is TokenKwComma);
  995. if(!(t is TokenKwBrkClose))
  996. {
  997. ErrorMsg(t, "expecting only [ , or ] for array type specification");
  998. return t;
  999. }
  1000. ranks.Push(rank);
  1001. } while(t.nextToken is TokenKwBrkOpen);
  1002. // Now we build the types in reverse order. For the example above we will:
  1003. // first, create a type that is a one-dimensional vector of floats, float[]
  1004. // second, create a type that is a two-dimensional matrix of that.
  1005. // This keeps declaration and referencing similar, eg,
  1006. // float[,][] jag = new float[,][] (3,4);
  1007. // jag[i,j][k] ... is used to access the elements
  1008. do
  1009. {
  1010. int rank = ranks.Pop();
  1011. TokenDeclSDType decl = InstantiateFixedArray(rank, ofType, tokenBegin, ref repeat);
  1012. ofType = decl.MakeRefToken(ofType);
  1013. } while(ranks.Count > 0);
  1014. // Finally splice in the resultant array type to replace the original tokens.
  1015. ofType.prevToken = start.prevToken;
  1016. ofType.nextToken = t.nextToken;
  1017. ofType.prevToken.nextToken = ofType;
  1018. ofType.nextToken.prevToken = ofType;
  1019. // Resume parsing just after the spliced-in array type token.
  1020. return ofType;
  1021. }
  1022. /**
  1023. * @brief Instantiate a script-defined class type to handle fixed-dimension arrays.
  1024. * @param rank = number of dimensions for the array
  1025. * @param ofType = type of each element of the array
  1026. * @returns script-defined class declaration created to handle the array
  1027. */
  1028. private TokenDeclSDType InstantiateFixedArray(int rank, TokenType ofType, Token tokenBegin, ref uint repeat)
  1029. {
  1030. // Create the array type's name.
  1031. // If starting with a non-array type, just append the rank to it, eg, float + rank=1 -> float[]
  1032. // If starting with an array type, slip this rank in front of existing array, eg, float[] + rank=2 -> float[,][].
  1033. // This makes it consistent with what the script-writer sees for both a type specification and when
  1034. // referencing elements in a jagged array.
  1035. string name = ofType.ToString();
  1036. StringBuilder sb = new StringBuilder(name);
  1037. int ix = name.IndexOf('[');
  1038. if(ix < 0)
  1039. ix = name.Length;
  1040. sb.Insert(ix++, '[');
  1041. for(int i = 0; ++i < rank;)
  1042. {
  1043. sb.Insert(ix++, ',');
  1044. }
  1045. sb.Insert(ix, ']');
  1046. name = sb.ToString();
  1047. TokenDeclSDType fa;
  1048. if(!tokenScript.sdSrcTypesTryGetValue(name, out fa))
  1049. {
  1050. char suffix = 'O';
  1051. if(ofType is TokenTypeChar)
  1052. suffix = 'C';
  1053. if(ofType is TokenTypeFloat)
  1054. suffix = 'F';
  1055. if(ofType is TokenTypeInt)
  1056. suffix = 'I';
  1057. // Don't already have one, create a new skeleton struct.
  1058. // Splice in a definition for the class at beginning of source file.
  1059. //
  1060. // class <arraytypename> {
  1061. fa = new TokenDeclSDTypeClass(new TokenName(tokenScript, name), false);
  1062. CatalogSDTypeDecl(fa);
  1063. repeat |= REPEAT_INSTGEN;
  1064. ((TokenDeclSDTypeClass)fa).arrayOfType = ofType;
  1065. ((TokenDeclSDTypeClass)fa).arrayOfRank = rank;
  1066. Token t = SpliceAfter(tokenBegin, fa);
  1067. t = SpliceAfter(t, new TokenKwBrcOpen(t));
  1068. // public integer len0;
  1069. // public integer len1;
  1070. // ...
  1071. // public object obj;
  1072. for(int i = 0; i < rank; i++)
  1073. {
  1074. t = SpliceAfter(t, new TokenKwPublic(t));
  1075. t = SpliceAfter(t, new TokenTypeInt(t));
  1076. t = SpliceAfter(t, new TokenName(t, "len" + i));
  1077. t = SpliceAfter(t, new TokenKwSemi(t));
  1078. }
  1079. t = SpliceAfter(t, new TokenKwPublic(t));
  1080. t = SpliceAfter(t, new TokenTypeObject(t));
  1081. t = SpliceAfter(t, new TokenName(t, "obj"));
  1082. t = SpliceAfter(t, new TokenKwSemi(t));
  1083. // public constructor (integer len0, integer len1, ...) {
  1084. // this.len0 = len0;
  1085. // this.len1 = len1;
  1086. // ...
  1087. // this.obj = xmrFixedArrayAlloc<suffix> (len0 * len1 * ...);
  1088. // }
  1089. t = SpliceAfter(t, new TokenKwPublic(t));
  1090. t = SpliceAfter(t, new TokenKwConstructor(t));
  1091. t = SpliceAfter(t, new TokenKwParOpen(t));
  1092. for(int i = 0; i < rank; i++)
  1093. {
  1094. if(i > 0)
  1095. t = SpliceAfter(t, new TokenKwComma(t));
  1096. t = SpliceAfter(t, new TokenTypeInt(t));
  1097. t = SpliceAfter(t, new TokenName(t, "len" + i));
  1098. }
  1099. t = SpliceAfter(t, new TokenKwParClose(t));
  1100. t = SpliceAfter(t, new TokenKwBrcOpen(t));
  1101. for(int i = 0; i < rank; i++)
  1102. {
  1103. t = SpliceAfter(t, new TokenKwThis(t));
  1104. t = SpliceAfter(t, new TokenKwDot(t));
  1105. t = SpliceAfter(t, new TokenName(t, "len" + i));
  1106. t = SpliceAfter(t, new TokenKwAssign(t));
  1107. t = SpliceAfter(t, new TokenName(t, "len" + i));
  1108. t = SpliceAfter(t, new TokenKwSemi(t));
  1109. }
  1110. t = SpliceAfter(t, new TokenKwThis(t));
  1111. t = SpliceAfter(t, new TokenKwDot(t));
  1112. t = SpliceAfter(t, new TokenName(t, "obj"));
  1113. t = SpliceAfter(t, new TokenKwAssign(t));
  1114. t = SpliceAfter(t, new TokenName(t, "xmrFixedArrayAlloc" + suffix));
  1115. t = SpliceAfter(t, new TokenKwParOpen(t));
  1116. for(int i = 0; i < rank; i++)
  1117. {
  1118. if(i > 0)
  1119. t = SpliceAfter(t, new TokenKwMul(t));
  1120. t = SpliceAfter(t, new TokenName(t, "len" + i));
  1121. }
  1122. t = SpliceAfter(t, new TokenKwParClose(t));
  1123. t = SpliceAfter(t, new TokenKwSemi(t));
  1124. t = SpliceAfter(t, new TokenKwBrcClose(t));
  1125. // public integer Length { get {
  1126. // return this.len0 * this.len1 * ... ;
  1127. // } }
  1128. t = SpliceAfter(t, new TokenKwPublic(t));
  1129. t = SpliceAfter(t, new TokenTypeInt(t));
  1130. t = SpliceAfter(t, new TokenName(t, "Length"));
  1131. t = SpliceAfter(t, new TokenKwBrcOpen(t));
  1132. t = SpliceAfter(t, new TokenKwGet(t));
  1133. t = SpliceAfter(t, new TokenKwBrcOpen(t));
  1134. t = SpliceAfter(t, new TokenKwRet(t));
  1135. for(int i = 0; i < rank; i++)
  1136. {
  1137. if(i > 0)
  1138. t = SpliceAfter(t, new TokenKwMul(t));
  1139. t = SpliceAfter(t, new TokenKwThis(t));
  1140. t = SpliceAfter(t, new TokenKwDot(t));
  1141. t = SpliceAfter(t, new TokenName(t, "len" + i));
  1142. }
  1143. t = SpliceAfter(t, new TokenKwSemi(t));
  1144. t = SpliceAfter(t, new TokenKwBrcClose(t));
  1145. t = SpliceAfter(t, new TokenKwBrcClose(t));
  1146. // public integer Length (integer dim) {
  1147. // switch (dim) {
  1148. // case 0: return this.len0;
  1149. // case 1: return this.len1;
  1150. // ...
  1151. // }
  1152. // return 0;
  1153. // }
  1154. t = SpliceAfter(t, new TokenKwPublic(t));
  1155. t = SpliceAfter(t, new TokenTypeInt(t));
  1156. t = SpliceAfter(t, new TokenName(t, "Length"));
  1157. t = SpliceAfter(t, new TokenKwParOpen(t));
  1158. t = SpliceAfter(t, new TokenTypeInt(t));
  1159. t = SpliceAfter(t, new TokenName(t, "dim"));
  1160. t = SpliceAfter(t, new TokenKwParClose(t));
  1161. t = SpliceAfter(t, new TokenKwBrcOpen(t));
  1162. t = SpliceAfter(t, new TokenKwSwitch(t));
  1163. t = SpliceAfter(t, new TokenKwParOpen(t));
  1164. t = SpliceAfter(t, new TokenName(t, "dim"));
  1165. t = SpliceAfter(t, new TokenKwParClose(t));
  1166. t = SpliceAfter(t, new TokenKwBrcOpen(t));
  1167. for(int i = 0; i < rank; i++)
  1168. {
  1169. t = SpliceAfter(t, new TokenKwCase(t));
  1170. t = SpliceAfter(t, new TokenInt(t, i));
  1171. t = SpliceAfter(t, new TokenKwColon(t));
  1172. t = SpliceAfter(t, new TokenKwRet(t));
  1173. t = SpliceAfter(t, new TokenKwThis(t));
  1174. t = SpliceAfter(t, new TokenKwDot(t));
  1175. t = SpliceAfter(t, new TokenName(t, "len" + i));
  1176. t = SpliceAfter(t, new TokenKwSemi(t));
  1177. }
  1178. t = SpliceAfter(t, new TokenKwBrcClose(t));
  1179. t = SpliceAfter(t, new TokenKwRet(t));
  1180. t = SpliceAfter(t, new TokenInt(t, 0));
  1181. t = SpliceAfter(t, new TokenKwSemi(t));
  1182. t = SpliceAfter(t, new TokenKwBrcClose(t));
  1183. // public integer Index (integer idx0, integet idx1, ...) {
  1184. // integer idx = idx0;
  1185. // idx *= this.len1; idx += idx1;
  1186. // idx *= this.len2; idx += idx2;
  1187. // ...
  1188. // return idx;
  1189. // }
  1190. t = SpliceAfter(t, new TokenKwPublic(t));
  1191. t = SpliceAfter(t, new TokenTypeInt(t));
  1192. t = SpliceAfter(t, new TokenName(t, "Index"));
  1193. t = SpliceAfter(t, new TokenKwParOpen(t));
  1194. for(int i = 0; i < rank; i++)
  1195. {
  1196. if(i > 0)
  1197. t = SpliceAfter(t, new TokenKwComma(t));
  1198. t = SpliceAfter(t, new TokenTypeInt(t));
  1199. t = SpliceAfter(t, new TokenName(t, "idx" + i));
  1200. }
  1201. t = SpliceAfter(t, new TokenKwParClose(t));
  1202. t = SpliceAfter(t, new TokenKwBrcOpen(t));
  1203. t = SpliceAfter(t, new TokenTypeInt(t));
  1204. t = SpliceAfter(t, new TokenName(t, "idx"));
  1205. t = SpliceAfter(t, new TokenKwAssign(t));
  1206. t = SpliceAfter(t, new TokenName(t, "idx0"));
  1207. t = SpliceAfter(t, new TokenKwSemi(t));
  1208. for(int i = 1; i < rank; i++)
  1209. {
  1210. t = SpliceAfter(t, new TokenName(t, "idx"));
  1211. t = SpliceAfter(t, new TokenKwAsnMul(t));
  1212. t = SpliceAfter(t, new TokenKwThis(t));
  1213. t = SpliceAfter(t, new TokenKwDot(t));
  1214. t = SpliceAfter(t, new TokenName(t, "len" + i));
  1215. t = SpliceAfter(t, new TokenKwSemi(t));
  1216. t = SpliceAfter(t, new TokenName(t, "idx"));
  1217. t = SpliceAfter(t, new TokenKwAsnAdd(t));
  1218. t = SpliceAfter(t, new TokenName(t, "idx" + i));
  1219. t = SpliceAfter(t, new TokenKwSemi(t));
  1220. }
  1221. t = SpliceAfter(t, new TokenKwRet(t));
  1222. t = SpliceAfter(t, new TokenName(t, "idx"));
  1223. t = SpliceAfter(t, new TokenKwSemi(t));
  1224. t = SpliceAfter(t, new TokenKwBrcClose(t));
  1225. // public <oftype> Get (integer idx0, integet idx1, ...) {
  1226. // integer idx = idx0;
  1227. // idx *= this.len1; idx += idx1;
  1228. // idx *= this.len2; idx += idx2;
  1229. // ...
  1230. // return (<oftype>) xmrFixedArrayGet<suffix> (this.obj, idx);
  1231. // }
  1232. t = SpliceAfter(t, new TokenKwPublic(t));
  1233. t = SpliceAfter(t, ofType.CopyToken(t));
  1234. t = SpliceAfter(t, new TokenName(t, "Get"));
  1235. t = SpliceAfter(t, new TokenKwParOpen(t));
  1236. for(int i = 0; i < rank; i++)
  1237. {
  1238. if(i > 0)
  1239. t = SpliceAfter(t, new TokenKwComma(t));
  1240. t = SpliceAfter(t, new TokenTypeInt(t));
  1241. t = SpliceAfter(t, new TokenName(t, "idx" + i));
  1242. }
  1243. t = SpliceAfter(t, new TokenKwParClose(t));
  1244. t = SpliceAfter(t, new TokenKwBrcOpen(t));
  1245. t = SpliceAfter(t, new TokenTypeInt(t));
  1246. t = SpliceAfter(t, new TokenName(t, "idx"));
  1247. t = SpliceAfter(t, new TokenKwAssign(t));
  1248. t = SpliceAfter(t, new TokenName(t, "idx0"));
  1249. t = SpliceAfter(t, new TokenKwSemi(t));
  1250. for(int i = 1; i < rank; i++)
  1251. {
  1252. t = SpliceAfter(t, new TokenName(t, "idx"));
  1253. t = SpliceAfter(t, new TokenKwAsnMul(t));
  1254. t = SpliceAfter(t, new TokenKwThis(t));
  1255. t = SpliceAfter(t, new TokenKwDot(t));
  1256. t = SpliceAfter(t, new TokenName(t, "len" + i));
  1257. t = SpliceAfter(t, new TokenKwSemi(t));
  1258. t = SpliceAfter(t, new TokenName(t, "idx"));
  1259. t = SpliceAfter(t, new TokenKwAsnAdd(t));
  1260. t = SpliceAfter(t, new TokenName(t, "idx" + i));
  1261. t = SpliceAfter(t, new TokenKwSemi(t));
  1262. }
  1263. t = SpliceAfter(t, new TokenKwRet(t));
  1264. if(suffix == 'O')
  1265. {
  1266. t = SpliceAfter(t, new TokenKwParOpen(t));
  1267. t = SpliceAfter(t, ofType.CopyToken(t));
  1268. t = SpliceAfter(t, new TokenKwParClose(t));
  1269. }
  1270. t = SpliceAfter(t, new TokenName(t, "xmrFixedArrayGet" + suffix));
  1271. t = SpliceAfter(t, new TokenKwParOpen(t));
  1272. t = SpliceAfter(t, new TokenKwThis(t));
  1273. t = SpliceAfter(t, new TokenKwDot(t));
  1274. t = SpliceAfter(t, new TokenName(t, "obj"));
  1275. t = SpliceAfter(t, new TokenKwComma(t));
  1276. t = SpliceAfter(t, new TokenName(t, "idx"));
  1277. t = SpliceAfter(t, new TokenKwParClose(t));
  1278. t = SpliceAfter(t, new TokenKwSemi(t));
  1279. t = SpliceAfter(t, new TokenKwBrcClose(t));
  1280. // public void Set (integer idx0, integer idx1, ..., <oftype> val) {
  1281. // integer idx = idx0;
  1282. // idx *= this.len1; idx += idx1;
  1283. // idx *= this.len2; idx += idx2;
  1284. // ...
  1285. // xmrFixedArraySet<suffix> (this.obj, idx, val);
  1286. // }
  1287. t = SpliceAfter(t, new TokenKwPublic(t));
  1288. t = SpliceAfter(t, new TokenTypeVoid(t));
  1289. t = SpliceAfter(t, new TokenName(t, "Set"));
  1290. t = SpliceAfter(t, new TokenKwParOpen(t));
  1291. for(int i = 0; i < rank; i++)
  1292. {
  1293. t = SpliceAfter(t, new TokenTypeInt(t));
  1294. t = SpliceAfter(t, new TokenName(t, "idx" + i));
  1295. t = SpliceAfter(t, new TokenKwComma(t));
  1296. }
  1297. t = SpliceAfter(t, ofType.CopyToken(t));
  1298. t = SpliceAfter(t, new TokenName(t, "val"));
  1299. t = SpliceAfter(t, new TokenKwParClose(t));
  1300. t = SpliceAfter(t, new TokenKwBrcOpen(t));
  1301. t = SpliceAfter(t, new TokenTypeInt(t));
  1302. t = SpliceAfter(t, new TokenName(t, "idx"));
  1303. t = SpliceAfter(t, new TokenKwAssign(t));
  1304. t = SpliceAfter(t, new TokenName(t, "idx0"));
  1305. t = SpliceAfter(t, new TokenKwSemi(t));
  1306. for(int i = 1; i < rank; i++)
  1307. {
  1308. t = SpliceAfter(t, new TokenName(t, "idx"));
  1309. t = SpliceAfter(t, new TokenKwAsnMul(t));
  1310. t = SpliceAfter(t, new TokenKwThis(t));
  1311. t = SpliceAfter(t, new TokenKwDot(t));
  1312. t = SpliceAfter(t, new TokenName(t, "len" + i));
  1313. t = SpliceAfter(t, new TokenKwSemi(t));
  1314. t = SpliceAfter(t, new TokenName(t, "idx"));
  1315. t = SpliceAfter(t, new TokenKwAsnAdd(t));
  1316. t = SpliceAfter(t, new TokenName(t, "idx" + i));
  1317. t = SpliceAfter(t, new TokenKwSemi(t));
  1318. }
  1319. t = SpliceAfter(t, new TokenName(t, "xmrFixedArraySet" + suffix));
  1320. t = SpliceAfter(t, new TokenKwParOpen(t));
  1321. t = SpliceAfter(t, new TokenKwThis(t));
  1322. t = SpliceAfter(t, new TokenKwDot(t));
  1323. t = SpliceAfter(t, new TokenName(t, "obj"));
  1324. t = SpliceAfter(t, new TokenKwComma(t));
  1325. t = SpliceAfter(t, new TokenName(t, "idx"));
  1326. t = SpliceAfter(t, new TokenKwComma(t));
  1327. t = SpliceAfter(t, new TokenName(t, "val"));
  1328. t = SpliceAfter(t, new TokenKwParClose(t));
  1329. t = SpliceAfter(t, new TokenKwSemi(t));
  1330. t = SpliceAfter(t, new TokenKwBrcClose(t));
  1331. t = SpliceAfter(t, new TokenKwBrcClose(t));
  1332. }
  1333. return fa;
  1334. }
  1335. private Token SpliceAfter(Token before, Token after)
  1336. {
  1337. after.nextToken = before.nextToken;
  1338. after.prevToken = before;
  1339. before.nextToken = after;
  1340. after.nextToken.prevToken = after;
  1341. return after;
  1342. }
  1343. /**
  1344. * @brief Parse script-defined type declarations.
  1345. * @param token = points to possible script-defined type keyword
  1346. * @param outerSDType = null: top-level type
  1347. * else: sub-type of this type
  1348. * @param flags = access level (SDT_{PRIVATE,PROTECTED,PUBLIC})
  1349. * @returns true: something defined; else: not a sd type def
  1350. */
  1351. private bool ParseDeclSDTypes(ref Token token, TokenDeclSDType outerSDType, uint flags)
  1352. {
  1353. if(!(token is TokenDeclSDType))
  1354. return false;
  1355. TokenDeclSDType decl = (TokenDeclSDType)token;
  1356. /*
  1357. * If declaration of generic type, skip it.
  1358. * The instantiations get parsed (ie, when we know the concrete types)
  1359. * below because they appear as non-generic types.
  1360. */
  1361. if(decl.genParams != null)
  1362. {
  1363. token = decl.endToken.nextToken;
  1364. return true;
  1365. }
  1366. /*
  1367. * Also skip over any typedefs. They were all processed in
  1368. * ParseSDTypePreScanPassTwo().
  1369. */
  1370. if(decl is TokenDeclSDTypeTypedef)
  1371. {
  1372. token = decl.endToken.nextToken;
  1373. return true;
  1374. }
  1375. /*
  1376. * Non-generic types get parsed inline because we know all their types.
  1377. */
  1378. if(decl is TokenDeclSDTypeClass)
  1379. {
  1380. ParseDeclClass(ref token, outerSDType, flags);
  1381. return true;
  1382. }
  1383. if(decl is TokenDeclSDTypeDelegate)
  1384. {
  1385. ParseDeclDelegate(ref token, outerSDType, flags);
  1386. return true;
  1387. }
  1388. if(decl is TokenDeclSDTypeInterface)
  1389. {
  1390. ParseDeclInterface(ref token, outerSDType, flags);
  1391. return true;
  1392. }
  1393. throw new Exception("unhandled token " + token.GetType().ToString());
  1394. }
  1395. /**
  1396. * @brief Parse a class declaration.
  1397. * @param token = points to TokenDeclSDTypeClass token
  1398. * points just past closing '}' on return
  1399. * @param outerSDType = null: this is a top-level class
  1400. * else: this class is being defined inside this type
  1401. * @param flags = SDT_{PRIVATE,PROTECTED,PUBLIC}
  1402. */
  1403. private void ParseDeclClass(ref Token token, TokenDeclSDType outerSDType, uint flags)
  1404. {
  1405. bool haveExplicitConstructor = false;
  1406. Token u = token;
  1407. TokenDeclSDTypeClass tokdeclcl;
  1408. tokdeclcl = (TokenDeclSDTypeClass)u;
  1409. tokdeclcl.outerSDType = outerSDType;
  1410. tokdeclcl.accessLevel = flags;
  1411. u = u.nextToken;
  1412. // maybe it is a partial class that had its body snipped out
  1413. // by a later partial class declaration of the same class
  1414. if(tokdeclcl.endToken == tokdeclcl)
  1415. {
  1416. token = u;
  1417. return;
  1418. }
  1419. // make this class the currently compiled class
  1420. // used for retrieving stuff like 'this' possibly
  1421. // in field initialization code
  1422. TokenDeclSDType saveCurSDType = currentDeclSDType;
  1423. currentDeclSDType = tokdeclcl;
  1424. // next can be ':' followed by list of implemented
  1425. // interfaces and one extended class
  1426. if(u is TokenKwColon)
  1427. {
  1428. u = u.nextToken;
  1429. while(true)
  1430. {
  1431. if(u is TokenTypeSDTypeClass)
  1432. {
  1433. TokenDeclSDTypeClass c = ((TokenTypeSDTypeClass)u).decl;
  1434. if(tokdeclcl.extends == null)
  1435. {
  1436. tokdeclcl.extends = c;
  1437. }
  1438. else if(tokdeclcl.extends != c)
  1439. {
  1440. ErrorMsg(u, "can extend from only one class");
  1441. }
  1442. }
  1443. else if(u is TokenTypeSDTypeInterface)
  1444. {
  1445. TokenDeclSDTypeInterface i = ((TokenTypeSDTypeInterface)u).decl;
  1446. i.AddToClassDecl(tokdeclcl);
  1447. }
  1448. else
  1449. {
  1450. ErrorMsg(u, "expecting class or interface name");
  1451. if(u is TokenKwBrcOpen)
  1452. break;
  1453. }
  1454. u = u.nextToken;
  1455. // allow : in case it is spliced from multiple partial class definitions
  1456. if(!(u is TokenKwComma) && !(u is TokenKwColon))
  1457. break;
  1458. u = u.nextToken;
  1459. }
  1460. }
  1461. // next must be '{' to open class declaration body
  1462. if(!(u is TokenKwBrcOpen))
  1463. {
  1464. ErrorMsg(u, "expecting { to open class declaration body");
  1465. token = SkipPastSemi(token);
  1466. goto ret;
  1467. }
  1468. token = u.nextToken;
  1469. // push a var frame to put all the class members in
  1470. tokdeclcl.members.thisClass = tokdeclcl;
  1471. tokenScript.PushVarFrame(tokdeclcl.members);
  1472. // Create a function $instfieldnit to hold all explicit
  1473. // instance field initializations.
  1474. TokenDeclVar ifiFunc = new TokenDeclVar(tokdeclcl, null, tokenScript);
  1475. ifiFunc.name = new TokenName(ifiFunc, "$instfieldinit");
  1476. ifiFunc.retType = new TokenTypeVoid(ifiFunc);
  1477. ifiFunc.argDecl = new TokenArgDecl(ifiFunc);
  1478. ifiFunc.sdtClass = tokdeclcl;
  1479. ifiFunc.sdtFlags = SDT_PUBLIC | SDT_NEW;
  1480. TokenStmtBlock ifiBody = new TokenStmtBlock(ifiFunc);
  1481. ifiBody.function = ifiFunc;
  1482. ifiFunc.body = ifiBody;
  1483. tokdeclcl.instFieldInit = ifiFunc;
  1484. tokenScript.AddVarEntry(ifiFunc);
  1485. // Create a function $staticfieldnit to hold all explicit
  1486. // static field initializations.
  1487. TokenDeclVar sfiFunc = new TokenDeclVar(tokdeclcl, null, tokenScript);
  1488. sfiFunc.name = new TokenName(sfiFunc, "$staticfieldinit");
  1489. sfiFunc.retType = new TokenTypeVoid(sfiFunc);
  1490. sfiFunc.argDecl = new TokenArgDecl(sfiFunc);
  1491. sfiFunc.sdtClass = tokdeclcl;
  1492. sfiFunc.sdtFlags = SDT_PUBLIC | SDT_STATIC | SDT_NEW;
  1493. TokenStmtBlock sfiBody = new TokenStmtBlock(sfiFunc);
  1494. sfiBody.function = sfiFunc;
  1495. sfiFunc.body = sfiBody;
  1496. tokdeclcl.staticFieldInit = sfiFunc;
  1497. tokenScript.AddVarEntry(sfiFunc);
  1498. // process declaration statements until '}'
  1499. while(!(token is TokenKwBrcClose))
  1500. {
  1501. if(token is TokenKwSemi)
  1502. {
  1503. token = token.nextToken;
  1504. continue;
  1505. }
  1506. // Check for all qualifiers.
  1507. // typedef has an implied 'public' qualifier.
  1508. flags = SDT_PUBLIC;
  1509. if(!(token is TokenDeclSDTypeTypedef))
  1510. {
  1511. flags = ParseQualifierFlags(ref token);
  1512. }
  1513. // Parse nested script-defined type definitions.
  1514. if(ParseDeclSDTypes(ref token, tokdeclcl, flags))
  1515. continue;
  1516. // constant <name> = <rval> ;
  1517. if(token is TokenKwConst)
  1518. {
  1519. if((flags & (SDT_ABSTRACT | SDT_NEW | SDT_OVERRIDE | SDT_VIRTUAL)) != 0)
  1520. {
  1521. ErrorMsg(token, "cannot have abstract, new, override or virtual field");
  1522. }
  1523. TokenDeclVar var = ParseDeclVar(ref token, null);
  1524. if(var != null)
  1525. {
  1526. var.sdtClass = tokdeclcl;
  1527. var.sdtFlags = flags | SDT_STATIC;
  1528. }
  1529. continue;
  1530. }
  1531. // <type> <name> ;
  1532. // <type> <name> = <rval> ;
  1533. if((token is TokenType) &&
  1534. (token.nextToken is TokenName) &&
  1535. ((token.nextToken.nextToken is TokenKwSemi) ||
  1536. (token.nextToken.nextToken is TokenKwAssign)))
  1537. {
  1538. if((flags & (SDT_ABSTRACT | SDT_FINAL | SDT_NEW | SDT_OVERRIDE | SDT_VIRTUAL)) != 0)
  1539. {
  1540. ErrorMsg(token, "cannot have abstract, final, new, override or virtual field");
  1541. }
  1542. TokenDeclVar var = ParseDeclVar(ref token, ifiFunc);
  1543. if(var != null)
  1544. {
  1545. var.sdtClass = tokdeclcl;
  1546. var.sdtFlags = flags;
  1547. if((flags & SDT_STATIC) != 0)
  1548. {
  1549. // <type>.<name> = <init>;
  1550. TokenLValSField left = new TokenLValSField(var.init);
  1551. left.baseType = tokdeclcl.MakeRefToken(var);
  1552. left.fieldName = var.name;
  1553. DoVarInit(sfiFunc, left, var.init);
  1554. }
  1555. else if(var.init != null)
  1556. {
  1557. // this.<name> = <init>;
  1558. TokenLValIField left = new TokenLValIField(var.init);
  1559. left.baseRVal = new TokenRValThis(var.init, tokdeclcl);
  1560. left.fieldName = var.name;
  1561. DoVarInit(ifiFunc, left, var.init);
  1562. }
  1563. }
  1564. continue;
  1565. }
  1566. // <type> <name> [ : <implintfs> ] { [ get { <body> } ] [ set { <body> } ] }
  1567. // <type> '[' ... ']' [ : <implintfs> ] { [ get { <body> } ] [ set { <body> } ] }
  1568. bool prop = (token is TokenType) &&
  1569. (token.nextToken is TokenName) &&
  1570. (token.nextToken.nextToken is TokenKwBrcOpen ||
  1571. token.nextToken.nextToken is TokenKwColon);
  1572. prop |= (token is TokenType) && (token.nextToken is TokenKwBrkOpen);
  1573. if(prop)
  1574. {
  1575. TokenDeclVar var = ParseProperty(ref token, (flags & SDT_ABSTRACT) != 0, true);
  1576. if(var != null)
  1577. {
  1578. var.sdtClass = tokdeclcl;
  1579. var.sdtFlags = flags;
  1580. if(var.getProp != null)
  1581. {
  1582. var.getProp.sdtClass = tokdeclcl;
  1583. var.getProp.sdtFlags = flags;
  1584. }
  1585. if(var.setProp != null)
  1586. {
  1587. var.setProp.sdtClass = tokdeclcl;
  1588. var.setProp.sdtFlags = flags;
  1589. }
  1590. }
  1591. continue;
  1592. }
  1593. // 'constructor' '(' arglist ')' [ ':' [ 'base' ] '(' baseconstructorcall ')' ] '{' body '}'
  1594. if(token is TokenKwConstructor)
  1595. {
  1596. ParseSDTClassCtorDecl(ref token, flags, tokdeclcl);
  1597. haveExplicitConstructor = true;
  1598. continue;
  1599. }
  1600. // <type> <name> <funcargs> <funcbody>
  1601. // method with explicit return type
  1602. if(token is TokenType)
  1603. {
  1604. ParseSDTClassMethodDecl(ref token, flags, tokdeclcl);
  1605. continue;
  1606. }
  1607. // <name> <funcargs> <funcbody>
  1608. // method returning void
  1609. if((token is TokenName) || ((token is TokenKw) && ((TokenKw)token).sdtClassOp))
  1610. {
  1611. ParseSDTClassMethodDecl(ref token, flags, tokdeclcl);
  1612. continue;
  1613. }
  1614. // That's all we support in a class declaration.
  1615. ErrorMsg(token, "expecting field or method declaration");
  1616. token = SkipPastSemi(token);
  1617. }
  1618. // If script didn't specify any constructor, create a default no-argument one.
  1619. if(!haveExplicitConstructor)
  1620. {
  1621. TokenDeclVar tokenDeclFunc = new TokenDeclVar(token, null, tokenScript);
  1622. tokenDeclFunc.name = new TokenName(token, "$ctor");
  1623. tokenDeclFunc.retType = new TokenTypeVoid(token);
  1624. tokenDeclFunc.argDecl = new TokenArgDecl(token);
  1625. tokenDeclFunc.sdtClass = tokdeclcl;
  1626. tokenDeclFunc.sdtFlags = SDT_PUBLIC | SDT_NEW;
  1627. tokenDeclFunc.body = new TokenStmtBlock(token);
  1628. tokenDeclFunc.body.function = tokenDeclFunc;
  1629. if(tokdeclcl.extends != null)
  1630. {
  1631. SetUpDefaultBaseCtorCall(tokenDeclFunc);
  1632. }
  1633. else
  1634. {
  1635. // default constructor that doesn't do anything is trivial
  1636. tokenDeclFunc.triviality = Triviality.trivial;
  1637. }
  1638. tokenScript.AddVarEntry(tokenDeclFunc);
  1639. }
  1640. // Skip over the closing brace and pop corresponding var frame.
  1641. token = token.nextToken;
  1642. tokenScript.PopVarFrame();
  1643. ret:
  1644. currentDeclSDType = saveCurSDType;
  1645. }
  1646. /**
  1647. * @brief Parse out abstract/override/private/protected/public/static/virtual keywords.
  1648. * @param token = first token to evaluate
  1649. * @returns flags found; token = unprocessed token
  1650. */
  1651. private Dictionary<uint, Token> foundFlags = new Dictionary<uint, Token>();
  1652. private uint ParseQualifierFlags(ref Token token)
  1653. {
  1654. foundFlags.Clear();
  1655. while(true)
  1656. {
  1657. if(token is TokenKwPrivate)
  1658. {
  1659. token = AddQualifierFlag(token, SDT_PRIVATE, SDT_PROTECTED | SDT_PUBLIC);
  1660. continue;
  1661. }
  1662. if(token is TokenKwProtected)
  1663. {
  1664. token = AddQualifierFlag(token, SDT_PROTECTED, SDT_PRIVATE | SDT_PUBLIC);
  1665. continue;
  1666. }
  1667. if(token is TokenKwPublic)
  1668. {
  1669. token = AddQualifierFlag(token, SDT_PUBLIC, SDT_PRIVATE | SDT_PROTECTED);
  1670. continue;
  1671. }
  1672. if(token is TokenKwAbstract)
  1673. {
  1674. token = AddQualifierFlag(token, SDT_ABSTRACT, SDT_FINAL | SDT_STATIC | SDT_VIRTUAL);
  1675. continue;
  1676. }
  1677. if(token is TokenKwFinal)
  1678. {
  1679. token = AddQualifierFlag(token, SDT_FINAL, SDT_ABSTRACT | SDT_VIRTUAL);
  1680. continue;
  1681. }
  1682. if(token is TokenKwNew)
  1683. {
  1684. token = AddQualifierFlag(token, SDT_NEW, SDT_OVERRIDE);
  1685. continue;
  1686. }
  1687. if(token is TokenKwOverride)
  1688. {
  1689. token = AddQualifierFlag(token, SDT_OVERRIDE, SDT_NEW | SDT_STATIC);
  1690. continue;
  1691. }
  1692. if(token is TokenKwStatic)
  1693. {
  1694. token = AddQualifierFlag(token, SDT_STATIC, SDT_ABSTRACT | SDT_OVERRIDE | SDT_VIRTUAL);
  1695. continue;
  1696. }
  1697. if(token is TokenKwVirtual)
  1698. {
  1699. token = AddQualifierFlag(token, SDT_VIRTUAL, SDT_ABSTRACT | SDT_STATIC);
  1700. continue;
  1701. }
  1702. break;
  1703. }
  1704. uint flags = 0;
  1705. foreach(uint flag in foundFlags.Keys)
  1706. flags |= flag;
  1707. if((flags & (SDT_PRIVATE | SDT_PROTECTED | SDT_PUBLIC)) == 0)
  1708. ErrorMsg(token, "must specify exactly one of private, protected or public");
  1709. return flags;
  1710. }
  1711. private Token AddQualifierFlag(Token token, uint add, uint confs)
  1712. {
  1713. while(confs != 0)
  1714. {
  1715. uint conf = (uint)(confs & -confs);
  1716. Token confToken;
  1717. if(foundFlags.TryGetValue(conf, out confToken))
  1718. {
  1719. ErrorMsg(token, "conflicts with " + confToken.ToString());
  1720. }
  1721. confs -= conf;
  1722. }
  1723. foundFlags[add] = token;
  1724. return token.nextToken;
  1725. }
  1726. /**
  1727. * @brief Parse a property declaration.
  1728. * @param token = points to the property type token on entry
  1729. * points just past the closing brace on return
  1730. * @param abs = true: property is abstract
  1731. * false: property is concrete
  1732. * @param imp = allow implemented interface specs
  1733. * @returns null: parse failure
  1734. * else: property
  1735. *
  1736. * <type> <name> [ : <implintfs> ] { [ get { <body> } ] [ set { <body> } ] }
  1737. * <type> '[' ... ']' [ : <implintfs> ] { [ get { <body> } ] [ set { <body> } ] }
  1738. */
  1739. private TokenDeclVar ParseProperty(ref Token token, bool abs, bool imp)
  1740. {
  1741. // Parse out the property's type and name.
  1742. // <type> <name>
  1743. TokenType type = (TokenType)token;
  1744. TokenName name;
  1745. TokenArgDecl args;
  1746. Token argTokens = null;
  1747. token = token.nextToken;
  1748. if(token is TokenKwBrkOpen)
  1749. {
  1750. argTokens = token;
  1751. name = new TokenName(token, "$idxprop");
  1752. args = ParseFuncArgs(ref token, typeof(TokenKwBrkClose));
  1753. }
  1754. else
  1755. {
  1756. name = (TokenName)token;
  1757. token = token.nextToken;
  1758. args = new TokenArgDecl(token);
  1759. }
  1760. // Maybe it claims to implement some interface properties.
  1761. // [ ':' <ifacetype>[.<propname>] ',' ... ]
  1762. TokenIntfImpl implements = null;
  1763. if(token is TokenKwColon)
  1764. {
  1765. implements = ParseImplements(ref token, name);
  1766. if(implements == null)
  1767. return null;
  1768. if(!imp)
  1769. {
  1770. ErrorMsg(token, "cannot implement interface property");
  1771. }
  1772. }
  1773. // Should have an opening brace.
  1774. if(!(token is TokenKwBrcOpen))
  1775. {
  1776. ErrorMsg(token, "expect { to open property definition");
  1777. token = SkipPastSemi(token);
  1778. return null;
  1779. }
  1780. token = token.nextToken;
  1781. // Parse out the getter and/or setter.
  1782. // 'get' { <body> | ';' }
  1783. // 'set' { <body> | ';' }
  1784. TokenDeclVar getFunc = null;
  1785. TokenDeclVar setFunc = null;
  1786. while(!(token is TokenKwBrcClose))
  1787. {
  1788. // Maybe create a getter function.
  1789. if(token is TokenKwGet)
  1790. {
  1791. getFunc = new TokenDeclVar(token, null, tokenScript);
  1792. getFunc.name = new TokenName(token, name.val + "$get");
  1793. getFunc.retType = type;
  1794. getFunc.argDecl = args;
  1795. getFunc.implements = MakePropertyImplements(implements, "$get");
  1796. token = token.nextToken;
  1797. if(!ParseFunctionBody(ref token, getFunc, abs))
  1798. {
  1799. getFunc = null;
  1800. }
  1801. else if(!tokenScript.AddVarEntry(getFunc))
  1802. {
  1803. ErrorMsg(getFunc, "duplicate getter");
  1804. }
  1805. continue;
  1806. }
  1807. // Maybe create a setter function.
  1808. if(token is TokenKwSet)
  1809. {
  1810. TokenArgDecl argDecl = args;
  1811. if(getFunc != null)
  1812. {
  1813. argDecl = (argTokens == null) ? new TokenArgDecl(token) :
  1814. ParseFuncArgs(ref argTokens, typeof(TokenKwBrkClose));
  1815. }
  1816. argDecl.AddArg(type, new TokenName(token, "value"));
  1817. setFunc = new TokenDeclVar(token, null, tokenScript);
  1818. setFunc.name = new TokenName(token, name.val + "$set");
  1819. setFunc.retType = new TokenTypeVoid(token);
  1820. setFunc.argDecl = argDecl;
  1821. setFunc.implements = MakePropertyImplements(implements, "$set");
  1822. token = token.nextToken;
  1823. if(!ParseFunctionBody(ref token, setFunc, abs))
  1824. {
  1825. setFunc = null;
  1826. }
  1827. else if(!tokenScript.AddVarEntry(setFunc))
  1828. {
  1829. ErrorMsg(setFunc, "duplicate setter");
  1830. }
  1831. continue;
  1832. }
  1833. ErrorMsg(token, "expecting get or set");
  1834. token = SkipPastSemi(token);
  1835. return null;
  1836. }
  1837. token = token.nextToken;
  1838. if((getFunc == null) && (setFunc == null))
  1839. {
  1840. ErrorMsg(name, "must specify at least one of get, set");
  1841. return null;
  1842. }
  1843. // Set up a variable for the property.
  1844. TokenDeclVar tokenDeclVar = new TokenDeclVar(name, null, tokenScript);
  1845. tokenDeclVar.type = type;
  1846. tokenDeclVar.name = name;
  1847. tokenDeclVar.getProp = getFunc;
  1848. tokenDeclVar.setProp = setFunc;
  1849. // Can't be same name already in block.
  1850. if(!tokenScript.AddVarEntry(tokenDeclVar))
  1851. {
  1852. ErrorMsg(tokenDeclVar, "duplicate member " + name.val);
  1853. return null;
  1854. }
  1855. return tokenDeclVar;
  1856. }
  1857. /**
  1858. * @brief Given a list of implemented interface methods, create a similar list with suffix added to all the names
  1859. * @param implements = original list of implemented interface methods
  1860. * @param suffix = string to be added to end of implemented interface method names
  1861. * @returns list similar to implements with suffix added to end of implemented interface method names
  1862. */
  1863. private TokenIntfImpl MakePropertyImplements(TokenIntfImpl implements, string suffix)
  1864. {
  1865. TokenIntfImpl gsimpls = null;
  1866. for(TokenIntfImpl impl = implements; impl != null; impl = (TokenIntfImpl)impl.nextToken)
  1867. {
  1868. TokenIntfImpl gsimpl = new TokenIntfImpl(impl.intfType,
  1869. new TokenName(impl.methName, impl.methName.val + suffix));
  1870. gsimpl.nextToken = gsimpls;
  1871. gsimpls = gsimpl;
  1872. }
  1873. return gsimpls;
  1874. }
  1875. /**
  1876. * @brief Parse a constructor definition for a script-defined type class.
  1877. * @param token = points to 'constructor' keyword
  1878. * @param flags = abstract/override/static/virtual flags
  1879. * @param tokdeclcl = which script-defined type class this method is in
  1880. * @returns with method parsed and cataloged (or error message(s) printed)
  1881. */
  1882. private void ParseSDTClassCtorDecl(ref Token token, uint flags, TokenDeclSDTypeClass tokdeclcl)
  1883. {
  1884. if((flags & (SDT_ABSTRACT | SDT_OVERRIDE | SDT_STATIC | SDT_VIRTUAL)) != 0)
  1885. {
  1886. ErrorMsg(token, "cannot have abstract, override, static or virtual constructor");
  1887. }
  1888. TokenDeclVar tokenDeclFunc = new TokenDeclVar(token, null, tokenScript);
  1889. tokenDeclFunc.name = new TokenName(tokenDeclFunc, "$ctor");
  1890. tokenDeclFunc.retType = new TokenTypeVoid(token);
  1891. tokenDeclFunc.sdtClass = tokdeclcl;
  1892. tokenDeclFunc.sdtFlags = flags | SDT_NEW;
  1893. token = token.nextToken;
  1894. if(!(token is TokenKwParOpen))
  1895. {
  1896. ErrorMsg(token, "expecting ( for constructor argument list");
  1897. token = SkipPastSemi(token);
  1898. return;
  1899. }
  1900. tokenDeclFunc.argDecl = ParseFuncArgs(ref token, typeof(TokenKwParClose));
  1901. if(tokenDeclFunc.argDecl == null)
  1902. return;
  1903. TokenDeclVar saveDeclFunc = currentDeclFunc;
  1904. currentDeclFunc = tokenDeclFunc;
  1905. tokenScript.PushVarFrame(tokenDeclFunc.argDecl.varDict);
  1906. try
  1907. {
  1908. // Set up reference to base constructor.
  1909. TokenLValBaseField baseCtor = new TokenLValBaseField(token,
  1910. new TokenName(token, "$ctor"),
  1911. tokdeclcl);
  1912. // Parse any base constructor call as if it were the first statement of the
  1913. // constructor itself.
  1914. if(token is TokenKwColon)
  1915. {
  1916. token = token.nextToken;
  1917. if(token is TokenKwBase)
  1918. {
  1919. token = token.nextToken;
  1920. }
  1921. if(!(token is TokenKwParOpen))
  1922. {
  1923. ErrorMsg(token, "expecting ( for base constructor call arguments");
  1924. token = SkipPastSemi(token);
  1925. return;
  1926. }
  1927. TokenRValCall rvc = ParseRValCall(ref token, baseCtor);
  1928. if(rvc == null)
  1929. return;
  1930. if(tokdeclcl.extends != null)
  1931. {
  1932. tokenDeclFunc.baseCtorCall = rvc;
  1933. tokenDeclFunc.unknownTrivialityCalls.AddLast(rvc);
  1934. }
  1935. else
  1936. {
  1937. ErrorMsg(rvc, "base constructor call cannot be specified if not extending anything");
  1938. }
  1939. }
  1940. else if(tokdeclcl.extends != null)
  1941. {
  1942. // Caller didn't specify a constructor but we are extending, so we will
  1943. // call the extended class's default constructor.
  1944. SetUpDefaultBaseCtorCall(tokenDeclFunc);
  1945. }
  1946. // Parse the constructor body.
  1947. tokenDeclFunc.body = ParseStmtBlock(ref token);
  1948. if(tokenDeclFunc.body == null)
  1949. return;
  1950. if(tokenDeclFunc.argDecl == null)
  1951. return;
  1952. }
  1953. finally
  1954. {
  1955. tokenScript.PopVarFrame();
  1956. currentDeclFunc = saveDeclFunc;
  1957. }
  1958. // Add to list of methods defined by this class.
  1959. // It has the name "$ctor(argsig)".
  1960. if(!tokenScript.AddVarEntry(tokenDeclFunc))
  1961. {
  1962. ErrorMsg(tokenDeclFunc, "duplicate constructor definition");
  1963. }
  1964. }
  1965. /**
  1966. * @brief Set up a call from a constructor to its default base constructor.
  1967. */
  1968. private void SetUpDefaultBaseCtorCall(TokenDeclVar thisCtor)
  1969. {
  1970. TokenLValBaseField baseCtor = new TokenLValBaseField(thisCtor,
  1971. new TokenName(thisCtor, "$ctor"),
  1972. (TokenDeclSDTypeClass)thisCtor.sdtClass);
  1973. TokenRValCall rvc = new TokenRValCall(thisCtor);
  1974. rvc.meth = baseCtor;
  1975. thisCtor.baseCtorCall = rvc;
  1976. thisCtor.unknownTrivialityCalls.AddLast(rvc);
  1977. }
  1978. /**
  1979. * @brief Parse a method definition for a script-defined type class.
  1980. * @param token = points to return type (or method name for implicit return type of void)
  1981. * @param flags = abstract/override/static/virtual flags
  1982. * @param tokdeclcl = which script-defined type class this method is in
  1983. * @returns with method parsed and cataloged (or error message(s) printed)
  1984. */
  1985. private void ParseSDTClassMethodDecl(ref Token token, uint flags, TokenDeclSDTypeClass tokdeclcl)
  1986. {
  1987. TokenDeclVar tokenDeclFunc = ParseDeclFunc(ref token,
  1988. (flags & SDT_ABSTRACT) != 0,
  1989. (flags & SDT_STATIC) == 0,
  1990. (flags & SDT_STATIC) == 0);
  1991. if(tokenDeclFunc != null)
  1992. {
  1993. tokenDeclFunc.sdtClass = tokdeclcl;
  1994. tokenDeclFunc.sdtFlags = flags;
  1995. if(!tokenScript.AddVarEntry(tokenDeclFunc))
  1996. {
  1997. string funcNameSig = tokenDeclFunc.funcNameSig.val;
  1998. ErrorMsg(tokenDeclFunc.funcNameSig, "duplicate method name " + funcNameSig);
  1999. }
  2000. }
  2001. }
  2002. /**
  2003. * @brief Parse a delegate declaration statement.
  2004. * @param token = points to TokenDeclSDTypeDelegate token on entry
  2005. * points just past ';' on return
  2006. * @param outerSDType = null: this is a top-level delegate
  2007. * else: this delegate is being defined inside this type
  2008. * @param flags = SDT_{PRIVATE,PROTECTED,PUBLIC}
  2009. */
  2010. private void ParseDeclDelegate(ref Token token, TokenDeclSDType outerSDType, uint flags)
  2011. {
  2012. Token u = token;
  2013. TokenDeclSDTypeDelegate tokdecldel;
  2014. TokenType retType;
  2015. tokdecldel = (TokenDeclSDTypeDelegate)u;
  2016. tokdecldel.outerSDType = outerSDType;
  2017. tokdecldel.accessLevel = flags;
  2018. // first thing following that should be return type
  2019. // but we will fill in 'void' if it is missing
  2020. u = u.nextToken;
  2021. if(u is TokenType)
  2022. {
  2023. retType = (TokenType)u;
  2024. u = u.nextToken;
  2025. }
  2026. else
  2027. {
  2028. retType = new TokenTypeVoid(u);
  2029. }
  2030. // get list of argument types until we see a ')'
  2031. List<TokenType> args = new List<TokenType>();
  2032. bool first = true;
  2033. do
  2034. {
  2035. if(first)
  2036. {
  2037. // first time should have '(' ')' or '(' <type>
  2038. if(!(u is TokenKwParOpen))
  2039. {
  2040. ErrorMsg(u, "expecting ( after delegate name");
  2041. token = SkipPastSemi(token);
  2042. return;
  2043. }
  2044. first = false;
  2045. u = u.nextToken;
  2046. if(u is TokenKwParClose)
  2047. break;
  2048. }
  2049. else
  2050. {
  2051. // other times should have ',' <type>
  2052. if(!(u is TokenKwComma))
  2053. {
  2054. ErrorMsg(u, "expecting , separating arg types");
  2055. token = SkipPastSemi(token);
  2056. return;
  2057. }
  2058. u = u.nextToken;
  2059. }
  2060. if(!(u is TokenType))
  2061. {
  2062. ErrorMsg(u, "expecting argument type");
  2063. token = SkipPastSemi(token);
  2064. return;
  2065. }
  2066. args.Add((TokenType)u);
  2067. u = u.nextToken;
  2068. // they can put in a dummy name that we toss out
  2069. if(u is TokenName)
  2070. u = u.nextToken;
  2071. // scanning ends on a ')'
  2072. } while(!(u is TokenKwParClose));
  2073. // fill in the return type and argment type array
  2074. tokdecldel.SetRetArgTypes(retType, args.ToArray());
  2075. // and finally must have ';' to finish the delegate declaration statement
  2076. u = u.nextToken;
  2077. if(!(u is TokenKwSemi))
  2078. {
  2079. ErrorMsg(u, "expecting ; after ) in delegate");
  2080. token = SkipPastSemi(token);
  2081. return;
  2082. }
  2083. token = u.nextToken;
  2084. }
  2085. /**
  2086. * @brief Parse an interface declaration.
  2087. * @param token = points to TokenDeclSDTypeInterface token on entry
  2088. * points just past closing '}' on return
  2089. * @param outerSDType = null: this is a top-level interface
  2090. * else: this interface is being defined inside this type
  2091. * @param flags = SDT_{PRIVATE,PROTECTED,PUBLIC}
  2092. */
  2093. private void ParseDeclInterface(ref Token token, TokenDeclSDType outerSDType, uint flags)
  2094. {
  2095. Token u = token;
  2096. TokenDeclSDTypeInterface tokdeclin;
  2097. tokdeclin = (TokenDeclSDTypeInterface)u;
  2098. tokdeclin.outerSDType = outerSDType;
  2099. tokdeclin.accessLevel = flags;
  2100. u = u.nextToken;
  2101. // next can be ':' followed by list of implemented interfaces
  2102. if(u is TokenKwColon)
  2103. {
  2104. u = u.nextToken;
  2105. while(true)
  2106. {
  2107. if(u is TokenTypeSDTypeInterface)
  2108. {
  2109. TokenDeclSDTypeInterface i = ((TokenTypeSDTypeInterface)u).decl;
  2110. if(!tokdeclin.implements.Contains(i))
  2111. {
  2112. tokdeclin.implements.Add(i);
  2113. }
  2114. }
  2115. else
  2116. {
  2117. ErrorMsg(u, "expecting interface name");
  2118. if(u is TokenKwBrcOpen)
  2119. break;
  2120. }
  2121. u = u.nextToken;
  2122. if(!(u is TokenKwComma))
  2123. break;
  2124. u = u.nextToken;
  2125. }
  2126. }
  2127. // next must be '{' to open interface declaration body
  2128. if(!(u is TokenKwBrcOpen))
  2129. {
  2130. ErrorMsg(u, "expecting { to open interface declaration body");
  2131. token = SkipPastSemi(token);
  2132. return;
  2133. }
  2134. token = u.nextToken;
  2135. // start a var definition frame to collect the interface members
  2136. tokenScript.PushVarFrame(false);
  2137. tokdeclin.methsNProps = tokenScript.variablesStack;
  2138. // process declaration statements until '}'
  2139. while(!(token is TokenKwBrcClose))
  2140. {
  2141. if(token is TokenKwSemi)
  2142. {
  2143. token = token.nextToken;
  2144. continue;
  2145. }
  2146. // Parse nested script-defined type definitions.
  2147. if(ParseDeclSDTypes(ref token, tokdeclin, SDT_PUBLIC))
  2148. continue;
  2149. // <type> <name> <funcargs> ;
  2150. // abstract method with explicit return type
  2151. if((token is TokenType) &&
  2152. (token.nextToken is TokenName) &&
  2153. (token.nextToken.nextToken is TokenKwParOpen))
  2154. {
  2155. Token name = token.nextToken;
  2156. TokenDeclVar tokenDeclFunc = ParseDeclFunc(ref token, true, false, false);
  2157. if(tokenDeclFunc == null)
  2158. continue;
  2159. if(!tokenScript.AddVarEntry(tokenDeclFunc))
  2160. {
  2161. ErrorMsg(name, "duplicate method name");
  2162. continue;
  2163. }
  2164. continue;
  2165. }
  2166. // <name> <funcargs> ;
  2167. // abstract method returning void
  2168. if((token is TokenName) &&
  2169. (token.nextToken is TokenKwParOpen))
  2170. {
  2171. Token name = token;
  2172. TokenDeclVar tokenDeclFunc = ParseDeclFunc(ref token, true, false, false);
  2173. if(tokenDeclFunc == null)
  2174. continue;
  2175. if(!tokenScript.AddVarEntry(tokenDeclFunc))
  2176. {
  2177. ErrorMsg(name, "duplicate method name");
  2178. }
  2179. continue;
  2180. }
  2181. // <type> <name> { [ get ; ] [ set ; ] }
  2182. // <type> '[' ... ']' { [ get ; ] [ set ; ] }
  2183. // abstract property
  2184. bool prop = (token is TokenType) &&
  2185. (token.nextToken is TokenName) &&
  2186. (token.nextToken.nextToken is TokenKwBrcOpen ||
  2187. token.nextToken.nextToken is TokenKwColon);
  2188. prop |= (token is TokenType) && (token.nextToken is TokenKwBrkOpen);
  2189. if(prop)
  2190. {
  2191. ParseProperty(ref token, true, false);
  2192. continue;
  2193. }
  2194. // That's all we support in an interface declaration.
  2195. ErrorMsg(token, "expecting method or property prototype");
  2196. token = SkipPastSemi(token);
  2197. }
  2198. // Skip over the closing brace and pop the corresponding var frame.
  2199. token = token.nextToken;
  2200. tokenScript.PopVarFrame();
  2201. }
  2202. /**
  2203. * @brief parse state body (including all its event handlers)
  2204. * @param token = points to TokenKwBrcOpen
  2205. * @returns null: state body parse error
  2206. * else: token representing state
  2207. * token = points past close brace
  2208. */
  2209. private TokenStateBody ParseStateBody(ref Token token)
  2210. {
  2211. TokenStateBody tokenStateBody = new TokenStateBody(token);
  2212. if(!(token is TokenKwBrcOpen))
  2213. {
  2214. ErrorMsg(token, "expecting { at beg of state");
  2215. token = SkipPastSemi(token);
  2216. return null;
  2217. }
  2218. token = token.nextToken;
  2219. while(!(token is TokenKwBrcClose))
  2220. {
  2221. if(token is TokenEnd)
  2222. {
  2223. ErrorMsg(tokenStateBody, "eof parsing state body");
  2224. return null;
  2225. }
  2226. TokenDeclVar tokenDeclFunc = ParseDeclFunc(ref token, false, false, false);
  2227. if(tokenDeclFunc == null)
  2228. return null;
  2229. if(!(tokenDeclFunc.retType is TokenTypeVoid))
  2230. {
  2231. ErrorMsg(tokenDeclFunc.retType, "event handlers don't have return types");
  2232. return null;
  2233. }
  2234. tokenDeclFunc.nextToken = tokenStateBody.eventFuncs;
  2235. tokenStateBody.eventFuncs = tokenDeclFunc;
  2236. }
  2237. token = token.nextToken;
  2238. return tokenStateBody;
  2239. }
  2240. /**
  2241. * @brief Parse a function declaration, including its arg list and body
  2242. * @param token = points to function return type token (or function name token if return type void)
  2243. * @param abs = false: concrete function; true: abstract declaration
  2244. * @param imp = allow implemented interface specs
  2245. * @param ops = accept operators (==, +, etc) for function name
  2246. * @returns null: error parsing function definition
  2247. * else: function declaration
  2248. * token = advanced just past function, ie, just past the closing brace
  2249. */
  2250. private TokenDeclVar ParseDeclFunc(ref Token token, bool abs, bool imp, bool ops)
  2251. {
  2252. TokenType retType;
  2253. if(token is TokenType)
  2254. {
  2255. retType = (TokenType)token;
  2256. token = token.nextToken;
  2257. }
  2258. else
  2259. {
  2260. retType = new TokenTypeVoid(token);
  2261. }
  2262. TokenName simpleName;
  2263. if((token is TokenKw) && ((TokenKw)token).sdtClassOp)
  2264. {
  2265. if(!ops)
  2266. ErrorMsg(token, "operator functions disallowed in static contexts");
  2267. simpleName = new TokenName(token, "$op" + token.ToString());
  2268. }
  2269. else if(!(token is TokenName))
  2270. {
  2271. ErrorMsg(token, "expecting function name");
  2272. token = SkipPastSemi(token);
  2273. return null;
  2274. }
  2275. else
  2276. {
  2277. simpleName = (TokenName)token;
  2278. }
  2279. token = token.nextToken;
  2280. return ParseDeclFunc(ref token, abs, imp, retType, simpleName);
  2281. }
  2282. /**
  2283. * @brief Parse a function declaration, including its arg list and body
  2284. * This version enters with token pointing to the '(' at beginning of arg list
  2285. * @param token = points to the '(' of the arg list
  2286. * @param abs = false: concrete function; true: abstract declaration
  2287. * @param imp = allow implemented interface specs
  2288. * @param retType = return type (TokenTypeVoid if void, never null)
  2289. * @param simpleName = function name without any signature
  2290. * @returns null: error parsing remainder of function definition
  2291. * else: function declaration
  2292. * token = advanced just past function, ie, just past the closing brace
  2293. */
  2294. private TokenDeclVar ParseDeclFunc(ref Token token, bool abs, bool imp, TokenType retType, TokenName simpleName)
  2295. {
  2296. TokenDeclVar tokenDeclFunc = new TokenDeclVar(simpleName, null, tokenScript);
  2297. tokenDeclFunc.name = simpleName;
  2298. tokenDeclFunc.retType = retType;
  2299. tokenDeclFunc.argDecl = ParseFuncArgs(ref token, typeof(TokenKwParClose));
  2300. if(tokenDeclFunc.argDecl == null)
  2301. return null;
  2302. if(token is TokenKwColon)
  2303. {
  2304. tokenDeclFunc.implements = ParseImplements(ref token, simpleName);
  2305. if(tokenDeclFunc.implements == null)
  2306. return null;
  2307. if(!imp)
  2308. {
  2309. ErrorMsg(tokenDeclFunc.implements, "cannot implement interface method");
  2310. tokenDeclFunc.implements = null;
  2311. }
  2312. }
  2313. if(!ParseFunctionBody(ref token, tokenDeclFunc, abs))
  2314. return null;
  2315. if(tokenDeclFunc.argDecl == null)
  2316. return null;
  2317. return tokenDeclFunc;
  2318. }
  2319. /**
  2320. * @brief Parse interface implementation list.
  2321. * @param token = points to ':' on entry
  2322. * points just past list on return
  2323. * @param simpleName = simple name (no arg signature) of method/property that
  2324. * is implementing the interface method/property
  2325. * @returns list of implemented interface methods/properties
  2326. */
  2327. private TokenIntfImpl ParseImplements(ref Token token, TokenName simpleName)
  2328. {
  2329. TokenIntfImpl implements = null;
  2330. do
  2331. {
  2332. token = token.nextToken;
  2333. if(!(token is TokenTypeSDTypeInterface))
  2334. {
  2335. ErrorMsg(token, "expecting interface type");
  2336. token = SkipPastSemi(token);
  2337. return null;
  2338. }
  2339. TokenTypeSDTypeInterface intfType = (TokenTypeSDTypeInterface)token;
  2340. token = token.nextToken;
  2341. TokenName methName = simpleName;
  2342. if((token is TokenKwDot) && (token.nextToken is TokenName))
  2343. {
  2344. methName = (TokenName)token.nextToken;
  2345. token = token.nextToken.nextToken;
  2346. }
  2347. TokenIntfImpl intfImpl = new TokenIntfImpl(intfType, methName);
  2348. intfImpl.nextToken = implements;
  2349. implements = intfImpl;
  2350. } while(token is TokenKwComma);
  2351. return implements;
  2352. }
  2353. /**
  2354. * @brief Parse function declaration's body
  2355. * @param token = points to body, ie, ';' or '{'
  2356. * @param tokenDeclFunc = function being declared
  2357. * @param abs = false: concrete function; true: abstract declaration
  2358. * @returns whether or not the function definition parsed correctly
  2359. */
  2360. private bool ParseFunctionBody(ref Token token, TokenDeclVar tokenDeclFunc, bool abs)
  2361. {
  2362. if(token is TokenKwSemi)
  2363. {
  2364. if(!abs)
  2365. {
  2366. ErrorMsg(token, "concrete function must have body");
  2367. token = SkipPastSemi(token);
  2368. return false;
  2369. }
  2370. token = token.nextToken;
  2371. return true;
  2372. }
  2373. // Declare this function as being the one currently being processed
  2374. // for anything that cares. We also start a variable frame that
  2375. // includes all the declared parameters.
  2376. TokenDeclVar saveDeclFunc = currentDeclFunc;
  2377. currentDeclFunc = tokenDeclFunc;
  2378. tokenScript.PushVarFrame(tokenDeclFunc.argDecl.varDict);
  2379. // Now parse the function statement block.
  2380. tokenDeclFunc.body = ParseStmtBlock(ref token);
  2381. // Pop the var frame that contains the arguments.
  2382. tokenScript.PopVarFrame();
  2383. currentDeclFunc = saveDeclFunc;
  2384. // Check final errors.
  2385. if(tokenDeclFunc.body == null)
  2386. return false;
  2387. if(abs)
  2388. {
  2389. ErrorMsg(tokenDeclFunc.body, "abstract function must not have body");
  2390. tokenDeclFunc.body = null;
  2391. return false;
  2392. }
  2393. return true;
  2394. }
  2395. /**
  2396. * @brief Parse statement
  2397. * @param token = first token of statement
  2398. * @returns null: parse error
  2399. * else: token representing whole statement
  2400. * token = points past statement
  2401. */
  2402. private TokenStmt ParseStmt(ref Token token)
  2403. {
  2404. // Statements that begin with a specific keyword.
  2405. if(token is TokenKwAt)
  2406. return ParseStmtLabel(ref token);
  2407. if(token is TokenKwBrcOpen)
  2408. return ParseStmtBlock(ref token);
  2409. if(token is TokenKwBreak)
  2410. return ParseStmtBreak(ref token);
  2411. if(token is TokenKwCont)
  2412. return ParseStmtCont(ref token);
  2413. if(token is TokenKwDo)
  2414. return ParseStmtDo(ref token);
  2415. if(token is TokenKwFor)
  2416. return ParseStmtFor(ref token);
  2417. if(token is TokenKwForEach)
  2418. return ParseStmtForEach(ref token);
  2419. if(token is TokenKwIf)
  2420. return ParseStmtIf(ref token);
  2421. if(token is TokenKwJump)
  2422. return ParseStmtJump(ref token);
  2423. if(token is TokenKwRet)
  2424. return ParseStmtRet(ref token);
  2425. if(token is TokenKwSemi)
  2426. return ParseStmtNull(ref token);
  2427. if(token is TokenKwState)
  2428. return ParseStmtState(ref token);
  2429. if(token is TokenKwSwitch)
  2430. return ParseStmtSwitch(ref token);
  2431. if(token is TokenKwThrow)
  2432. return ParseStmtThrow(ref token);
  2433. if(token is TokenKwTry)
  2434. return ParseStmtTry(ref token);
  2435. if(token is TokenKwWhile)
  2436. return ParseStmtWhile(ref token);
  2437. // Try to parse anything else as an expression, possibly calling
  2438. // something and/or writing to a variable.
  2439. TokenRVal tokenRVal = ParseRVal(ref token, semiOnly);
  2440. if(tokenRVal != null)
  2441. {
  2442. TokenStmtRVal tokenStmtRVal = new TokenStmtRVal(tokenRVal);
  2443. tokenStmtRVal.rVal = tokenRVal;
  2444. return tokenStmtRVal;
  2445. }
  2446. // Who knows what it is...
  2447. ErrorMsg(token, "unknown statement");
  2448. token = SkipPastSemi(token);
  2449. return null;
  2450. }
  2451. /**
  2452. * @brief parse a statement block, ie, group of statements between braces
  2453. * @param token = points to { token
  2454. * @returns null: error parsing
  2455. * else: statements bundled in this token
  2456. * token = advanced just past the } token
  2457. */
  2458. private TokenStmtBlock ParseStmtBlock(ref Token token)
  2459. {
  2460. if(!(token is TokenKwBrcOpen))
  2461. {
  2462. ErrorMsg(token, "statement block body must begin with a {");
  2463. token = SkipPastSemi(token);
  2464. return null;
  2465. }
  2466. TokenStmtBlock tokenStmtBlock = new TokenStmtBlock(token);
  2467. tokenStmtBlock.function = currentDeclFunc;
  2468. tokenStmtBlock.outerStmtBlock = currentStmtBlock;
  2469. currentStmtBlock = tokenStmtBlock;
  2470. VarDict outerVariablesStack = tokenScript.variablesStack;
  2471. try
  2472. {
  2473. Token prevStmt = null;
  2474. token = token.nextToken;
  2475. while(!(token is TokenKwBrcClose))
  2476. {
  2477. if(token is TokenEnd)
  2478. {
  2479. ErrorMsg(tokenStmtBlock, "missing }");
  2480. return null;
  2481. }
  2482. Token thisStmt;
  2483. if(((token is TokenType) && (token.nextToken is TokenName)) ||
  2484. (token is TokenKwConst))
  2485. {
  2486. thisStmt = ParseDeclVar(ref token, null);
  2487. }
  2488. else
  2489. {
  2490. thisStmt = ParseStmt(ref token);
  2491. }
  2492. if(thisStmt == null)
  2493. return null;
  2494. if(prevStmt == null)
  2495. tokenStmtBlock.statements = thisStmt;
  2496. else
  2497. prevStmt.nextToken = thisStmt;
  2498. prevStmt = thisStmt;
  2499. }
  2500. token = token.nextToken;
  2501. }
  2502. finally
  2503. {
  2504. tokenScript.variablesStack = outerVariablesStack;
  2505. currentStmtBlock = tokenStmtBlock.outerStmtBlock;
  2506. }
  2507. return tokenStmtBlock;
  2508. }
  2509. /**
  2510. * @brief parse a 'break' statement
  2511. * @param token = points to break keyword token
  2512. * @returns null: error parsing
  2513. * else: statements bundled in this token
  2514. * token = advanced just past the ; token
  2515. */
  2516. private TokenStmtBreak ParseStmtBreak(ref Token token)
  2517. {
  2518. TokenStmtBreak tokenStmtBreak = new TokenStmtBreak(token);
  2519. token = token.nextToken;
  2520. if(!(token is TokenKwSemi))
  2521. {
  2522. ErrorMsg(token, "expecting ;");
  2523. token = SkipPastSemi(token);
  2524. return null;
  2525. }
  2526. token = token.nextToken;
  2527. return tokenStmtBreak;
  2528. }
  2529. /**
  2530. * @brief parse a 'continue' statement
  2531. * @param token = points to continue keyword token
  2532. * @returns null: error parsing
  2533. * else: statements bundled in this token
  2534. * token = advanced just past the ; token
  2535. */
  2536. private TokenStmtCont ParseStmtCont(ref Token token)
  2537. {
  2538. TokenStmtCont tokenStmtCont = new TokenStmtCont(token);
  2539. token = token.nextToken;
  2540. if(!(token is TokenKwSemi))
  2541. {
  2542. ErrorMsg(token, "expecting ;");
  2543. token = SkipPastSemi(token);
  2544. return null;
  2545. }
  2546. token = token.nextToken;
  2547. return tokenStmtCont;
  2548. }
  2549. /**
  2550. * @brief parse a 'do' statement
  2551. * @params token = points to 'do' keyword token
  2552. * @returns null: parse error
  2553. * else: pointer to token encapsulating the do statement, including body
  2554. * token = advanced just past the body statement
  2555. */
  2556. private TokenStmtDo ParseStmtDo(ref Token token)
  2557. {
  2558. currentDeclFunc.triviality = Triviality.complex;
  2559. TokenStmtDo tokenStmtDo = new TokenStmtDo(token);
  2560. token = token.nextToken;
  2561. tokenStmtDo.bodyStmt = ParseStmt(ref token);
  2562. if(tokenStmtDo.bodyStmt == null)
  2563. return null;
  2564. if(!(token is TokenKwWhile))
  2565. {
  2566. ErrorMsg(token, "expecting while clause");
  2567. return null;
  2568. }
  2569. token = token.nextToken;
  2570. tokenStmtDo.testRVal = ParseRValParen(ref token);
  2571. if(tokenStmtDo.testRVal == null)
  2572. return null;
  2573. if(!(token is TokenKwSemi))
  2574. {
  2575. ErrorMsg(token, "while clause must terminate on semicolon");
  2576. token = SkipPastSemi(token);
  2577. return null;
  2578. }
  2579. token = token.nextToken;
  2580. return tokenStmtDo;
  2581. }
  2582. /**
  2583. * @brief parse a for statement
  2584. * @param token = points to 'for' keyword token
  2585. * @returns null: parse error
  2586. * else: pointer to encapsulated for statement token
  2587. * token = advanced just past for body statement
  2588. */
  2589. private TokenStmt ParseStmtFor(ref Token token)
  2590. {
  2591. currentDeclFunc.triviality = Triviality.complex;
  2592. // Create encapsulating token and skip past 'for ('
  2593. TokenStmtFor tokenStmtFor = new TokenStmtFor(token);
  2594. token = token.nextToken;
  2595. if(!(token is TokenKwParOpen))
  2596. {
  2597. ErrorMsg(token, "for must be followed by (");
  2598. return null;
  2599. }
  2600. token = token.nextToken;
  2601. // If a plain for, ie, not declaring a variable, it's straightforward.
  2602. if(!(token is TokenType))
  2603. {
  2604. tokenStmtFor.initStmt = ParseStmt(ref token);
  2605. if(tokenStmtFor.initStmt == null)
  2606. return null;
  2607. return ParseStmtFor2(tokenStmtFor, ref token) ? tokenStmtFor : null;
  2608. }
  2609. // Initialization declares a variable, so encapsulate it in a block so
  2610. // variable has scope only in the for statement, including its body.
  2611. TokenStmtBlock forStmtBlock = new TokenStmtBlock(tokenStmtFor);
  2612. forStmtBlock.outerStmtBlock = currentStmtBlock;
  2613. forStmtBlock.function = currentDeclFunc;
  2614. currentStmtBlock = forStmtBlock;
  2615. tokenScript.PushVarFrame(true);
  2616. TokenDeclVar tokenDeclVar = ParseDeclVar(ref token, null);
  2617. if(tokenDeclVar == null)
  2618. {
  2619. tokenScript.PopVarFrame();
  2620. currentStmtBlock = forStmtBlock.outerStmtBlock;
  2621. return null;
  2622. }
  2623. forStmtBlock.statements = tokenDeclVar;
  2624. tokenDeclVar.nextToken = tokenStmtFor;
  2625. bool ok = ParseStmtFor2(tokenStmtFor, ref token);
  2626. tokenScript.PopVarFrame();
  2627. currentStmtBlock = forStmtBlock.outerStmtBlock;
  2628. return ok ? forStmtBlock : null;
  2629. }
  2630. /**
  2631. * @brief parse rest of 'for' statement starting with the test expression.
  2632. * @param tokenStmtFor = token encapsulating the for statement
  2633. * @param token = points to test expression
  2634. * @returns false: parse error
  2635. * true: successful
  2636. * token = points just past body statement
  2637. */
  2638. private bool ParseStmtFor2(TokenStmtFor tokenStmtFor, ref Token token)
  2639. {
  2640. if(token is TokenKwSemi)
  2641. {
  2642. token = token.nextToken;
  2643. }
  2644. else
  2645. {
  2646. tokenStmtFor.testRVal = ParseRVal(ref token, semiOnly);
  2647. if(tokenStmtFor.testRVal == null)
  2648. return false;
  2649. }
  2650. if(token is TokenKwParClose)
  2651. {
  2652. token = token.nextToken;
  2653. }
  2654. else
  2655. {
  2656. tokenStmtFor.incrRVal = ParseRVal(ref token, parCloseOnly);
  2657. if(tokenStmtFor.incrRVal == null)
  2658. return false;
  2659. }
  2660. tokenStmtFor.bodyStmt = ParseStmt(ref token);
  2661. return tokenStmtFor.bodyStmt != null;
  2662. }
  2663. /**
  2664. * @brief parse a foreach statement
  2665. * @param token = points to 'foreach' keyword token
  2666. * @returns null: parse error
  2667. * else: pointer to encapsulated foreach statement token
  2668. * token = advanced just past for body statement
  2669. */
  2670. private TokenStmt ParseStmtForEach(ref Token token)
  2671. {
  2672. currentDeclFunc.triviality = Triviality.complex;
  2673. // Create encapsulating token and skip past 'foreach ('
  2674. TokenStmtForEach tokenStmtForEach = new TokenStmtForEach(token);
  2675. token = token.nextToken;
  2676. if(!(token is TokenKwParOpen))
  2677. {
  2678. ErrorMsg(token, "foreach must be followed by (");
  2679. return null;
  2680. }
  2681. token = token.nextToken;
  2682. if(token is TokenName)
  2683. {
  2684. tokenStmtForEach.keyLVal = new TokenLValName((TokenName)token, tokenScript.variablesStack);
  2685. token = token.nextToken;
  2686. }
  2687. if(!(token is TokenKwComma))
  2688. {
  2689. ErrorMsg(token, "expecting comma");
  2690. token = SkipPastSemi(token);
  2691. return null;
  2692. }
  2693. token = token.nextToken;
  2694. if(token is TokenName)
  2695. {
  2696. tokenStmtForEach.valLVal = new TokenLValName((TokenName)token, tokenScript.variablesStack);
  2697. token = token.nextToken;
  2698. }
  2699. if(!(token is TokenKwIn))
  2700. {
  2701. ErrorMsg(token, "expecting 'in'");
  2702. token = SkipPastSemi(token);
  2703. return null;
  2704. }
  2705. token = token.nextToken;
  2706. tokenStmtForEach.arrayRVal = GetOperand(ref token);
  2707. if(tokenStmtForEach.arrayRVal == null)
  2708. return null;
  2709. if(!(token is TokenKwParClose))
  2710. {
  2711. ErrorMsg(token, "expecting )");
  2712. token = SkipPastSemi(token);
  2713. return null;
  2714. }
  2715. token = token.nextToken;
  2716. tokenStmtForEach.bodyStmt = ParseStmt(ref token);
  2717. if(tokenStmtForEach.bodyStmt == null)
  2718. return null;
  2719. return tokenStmtForEach;
  2720. }
  2721. private TokenStmtIf ParseStmtIf(ref Token token)
  2722. {
  2723. TokenStmtIf tokenStmtIf = new TokenStmtIf(token);
  2724. token = token.nextToken;
  2725. tokenStmtIf.testRVal = ParseRValParen(ref token);
  2726. if(tokenStmtIf.testRVal == null)
  2727. return null;
  2728. tokenStmtIf.trueStmt = ParseStmt(ref token);
  2729. if(tokenStmtIf.trueStmt == null)
  2730. return null;
  2731. if(token is TokenKwElse)
  2732. {
  2733. token = token.nextToken;
  2734. tokenStmtIf.elseStmt = ParseStmt(ref token);
  2735. if(tokenStmtIf.elseStmt == null)
  2736. return null;
  2737. }
  2738. return tokenStmtIf;
  2739. }
  2740. private TokenStmtJump ParseStmtJump(ref Token token)
  2741. {
  2742. // Create jump statement token to encapsulate the whole statement.
  2743. TokenStmtJump tokenStmtJump = new TokenStmtJump(token);
  2744. token = token.nextToken;
  2745. if(!(token is TokenName) || !(token.nextToken is TokenKwSemi))
  2746. {
  2747. ErrorMsg(token, "expecting label;");
  2748. token = SkipPastSemi(token);
  2749. return null;
  2750. }
  2751. tokenStmtJump.label = (TokenName)token;
  2752. token = token.nextToken.nextToken;
  2753. // If label is already defined, it means this is a backward (looping)
  2754. // jump, so remember the label has backward jump references.
  2755. // We also then assume the function is complex, ie, it has a loop.
  2756. if(currentDeclFunc.labels.ContainsKey(tokenStmtJump.label.val))
  2757. {
  2758. currentDeclFunc.labels[tokenStmtJump.label.val].hasBkwdRefs = true;
  2759. currentDeclFunc.triviality = Triviality.complex;
  2760. }
  2761. return tokenStmtJump;
  2762. }
  2763. /**
  2764. * @brief parse a jump target label statement
  2765. * @param token = points to the '@' token
  2766. * @returns null: error parsing
  2767. * else: the label
  2768. * token = advanced just past the ;
  2769. */
  2770. private TokenStmtLabel ParseStmtLabel(ref Token token)
  2771. {
  2772. if(!(token.nextToken is TokenName) ||
  2773. !(token.nextToken.nextToken is TokenKwSemi))
  2774. {
  2775. ErrorMsg(token, "invalid label");
  2776. token = SkipPastSemi(token);
  2777. return null;
  2778. }
  2779. TokenStmtLabel stmtLabel = new TokenStmtLabel(token);
  2780. stmtLabel.name = (TokenName)token.nextToken;
  2781. stmtLabel.block = currentStmtBlock;
  2782. if(currentDeclFunc.labels.ContainsKey(stmtLabel.name.val))
  2783. {
  2784. ErrorMsg(token.nextToken, "duplicate label");
  2785. ErrorMsg(currentDeclFunc.labels[stmtLabel.name.val], "previously defined here");
  2786. token = SkipPastSemi(token);
  2787. return null;
  2788. }
  2789. currentDeclFunc.labels.Add(stmtLabel.name.val, stmtLabel);
  2790. token = token.nextToken.nextToken.nextToken;
  2791. return stmtLabel;
  2792. }
  2793. private TokenStmtNull ParseStmtNull(ref Token token)
  2794. {
  2795. TokenStmtNull tokenStmtNull = new TokenStmtNull(token);
  2796. token = token.nextToken;
  2797. return tokenStmtNull;
  2798. }
  2799. private TokenStmtRet ParseStmtRet(ref Token token)
  2800. {
  2801. TokenStmtRet tokenStmtRet = new TokenStmtRet(token);
  2802. token = token.nextToken;
  2803. if(token is TokenKwSemi)
  2804. {
  2805. token = token.nextToken;
  2806. }
  2807. else
  2808. {
  2809. tokenStmtRet.rVal = ParseRVal(ref token, semiOnly);
  2810. if(tokenStmtRet.rVal == null)
  2811. return null;
  2812. }
  2813. return tokenStmtRet;
  2814. }
  2815. private TokenStmtSwitch ParseStmtSwitch(ref Token token)
  2816. {
  2817. TokenStmtSwitch tokenStmtSwitch = new TokenStmtSwitch(token);
  2818. token = token.nextToken;
  2819. tokenStmtSwitch.testRVal = ParseRValParen(ref token);
  2820. if(tokenStmtSwitch.testRVal == null)
  2821. return null;
  2822. if(!(token is TokenKwBrcOpen))
  2823. {
  2824. ErrorMsg(token, "expecting open brace");
  2825. token = SkipPastSemi(token);
  2826. return null;
  2827. }
  2828. token = token.nextToken;
  2829. TokenSwitchCase tokenSwitchCase = null;
  2830. bool haveComplained = false;
  2831. while(!(token is TokenKwBrcClose))
  2832. {
  2833. if(token is TokenKwCase)
  2834. {
  2835. tokenSwitchCase = new TokenSwitchCase(token);
  2836. if(tokenStmtSwitch.lastCase == null)
  2837. {
  2838. tokenStmtSwitch.cases = tokenSwitchCase;
  2839. }
  2840. else
  2841. {
  2842. tokenStmtSwitch.lastCase.nextCase = tokenSwitchCase;
  2843. }
  2844. tokenStmtSwitch.lastCase = tokenSwitchCase;
  2845. token = token.nextToken;
  2846. tokenSwitchCase.rVal1 = ParseRVal(ref token, colonOrDotDotDot);
  2847. if(tokenSwitchCase.rVal1 == null)
  2848. return null;
  2849. if(token is TokenKwDotDotDot)
  2850. {
  2851. token = token.nextToken;
  2852. tokenSwitchCase.rVal2 = ParseRVal(ref token, colonOnly);
  2853. if(tokenSwitchCase.rVal2 == null)
  2854. return null;
  2855. }
  2856. else
  2857. {
  2858. if(!(token is TokenKwColon))
  2859. {
  2860. ErrorMsg(token, "expecting : or ...");
  2861. token = SkipPastSemi(token);
  2862. return null;
  2863. }
  2864. token = token.nextToken;
  2865. }
  2866. }
  2867. else if(token is TokenKwDefault)
  2868. {
  2869. tokenSwitchCase = new TokenSwitchCase(token);
  2870. if(tokenStmtSwitch.lastCase == null)
  2871. {
  2872. tokenStmtSwitch.cases = tokenSwitchCase;
  2873. }
  2874. else
  2875. {
  2876. tokenStmtSwitch.lastCase.nextCase = tokenSwitchCase;
  2877. }
  2878. tokenStmtSwitch.lastCase = tokenSwitchCase;
  2879. token = token.nextToken;
  2880. if(!(token is TokenKwColon))
  2881. {
  2882. ErrorMsg(token, "expecting :");
  2883. token = SkipPastSemi(token);
  2884. return null;
  2885. }
  2886. token = token.nextToken;
  2887. }
  2888. else if(tokenSwitchCase != null)
  2889. {
  2890. TokenStmt bodyStmt = ParseStmt(ref token);
  2891. if(bodyStmt == null)
  2892. return null;
  2893. if(tokenSwitchCase.lastStmt == null)
  2894. {
  2895. tokenSwitchCase.stmts = bodyStmt;
  2896. }
  2897. else
  2898. {
  2899. tokenSwitchCase.lastStmt.nextToken = bodyStmt;
  2900. }
  2901. tokenSwitchCase.lastStmt = bodyStmt;
  2902. bodyStmt.nextToken = null;
  2903. }
  2904. else if(!haveComplained)
  2905. {
  2906. ErrorMsg(token, "expecting case or default label");
  2907. token = SkipPastSemi(token);
  2908. haveComplained = true;
  2909. }
  2910. }
  2911. token = token.nextToken;
  2912. return tokenStmtSwitch;
  2913. }
  2914. private TokenStmtState ParseStmtState(ref Token token)
  2915. {
  2916. TokenStmtState tokenStmtState = new TokenStmtState(token);
  2917. token = token.nextToken;
  2918. if((!(token is TokenName) && !(token is TokenKwDefault)) || !(token.nextToken is TokenKwSemi))
  2919. {
  2920. ErrorMsg(token, "expecting state;");
  2921. token = SkipPastSemi(token);
  2922. return null;
  2923. }
  2924. if(token is TokenName)
  2925. {
  2926. tokenStmtState.state = (TokenName)token;
  2927. }
  2928. token = token.nextToken.nextToken;
  2929. return tokenStmtState;
  2930. }
  2931. private TokenStmtThrow ParseStmtThrow(ref Token token)
  2932. {
  2933. TokenStmtThrow tokenStmtThrow = new TokenStmtThrow(token);
  2934. token = token.nextToken;
  2935. if(token is TokenKwSemi)
  2936. {
  2937. token = token.nextToken;
  2938. }
  2939. else
  2940. {
  2941. tokenStmtThrow.rVal = ParseRVal(ref token, semiOnly);
  2942. if(tokenStmtThrow.rVal == null)
  2943. return null;
  2944. }
  2945. return tokenStmtThrow;
  2946. }
  2947. /**
  2948. * @brief Parse a try { ... } catch { ... } finally { ... } statement block
  2949. * @param token = point to 'try' keyword on entry
  2950. * points past last '}' processed on return
  2951. * @returns encapsulated try/catch/finally or null if parsing error
  2952. */
  2953. private TokenStmtTry ParseStmtTry(ref Token token)
  2954. {
  2955. // Parse out the 'try { ... }' part
  2956. Token tryKw = token;
  2957. token = token.nextToken;
  2958. TokenStmt body = ParseStmtBlock(ref token);
  2959. while(true)
  2960. {
  2961. TokenStmtTry tokenStmtTry;
  2962. if(token is TokenKwCatch)
  2963. {
  2964. if(!(token.nextToken is TokenKwParOpen) ||
  2965. !(token.nextToken.nextToken is TokenType) ||
  2966. !(token.nextToken.nextToken.nextToken is TokenName) ||
  2967. !(token.nextToken.nextToken.nextToken.nextToken is TokenKwParClose))
  2968. {
  2969. ErrorMsg(token, "catch must be followed by ( <type> <varname> ) { <statement>... }");
  2970. return null;
  2971. }
  2972. token = token.nextToken.nextToken; // skip over 'catch' '('
  2973. TokenDeclVar tag = new TokenDeclVar(token.nextToken, currentDeclFunc, tokenScript);
  2974. tag.type = (TokenType)token;
  2975. token = token.nextToken; // skip over <type>
  2976. tag.name = (TokenName)token;
  2977. token = token.nextToken.nextToken; // skip over <varname> ')'
  2978. if((!(tag.type is TokenTypeExc)) && (!(tag.type is TokenTypeStr)))
  2979. {
  2980. ErrorMsg(tag.type, "must be type 'exception' or 'string'");
  2981. }
  2982. tokenStmtTry = new TokenStmtTry(tryKw);
  2983. tokenStmtTry.tryStmt = WrapTryCatFinInBlock(body);
  2984. tokenStmtTry.catchVar = tag;
  2985. tokenScript.PushVarFrame(false);
  2986. tokenScript.AddVarEntry(tag);
  2987. tokenStmtTry.catchStmt = ParseStmtBlock(ref token);
  2988. tokenScript.PopVarFrame();
  2989. if(tokenStmtTry.catchStmt == null)
  2990. return null;
  2991. tokenStmtTry.tryStmt.isTry = true;
  2992. tokenStmtTry.tryStmt.tryStmt = tokenStmtTry;
  2993. tokenStmtTry.catchStmt.isCatch = true;
  2994. tokenStmtTry.catchStmt.tryStmt = tokenStmtTry;
  2995. }
  2996. else if(token is TokenKwFinally)
  2997. {
  2998. token = token.nextToken;
  2999. tokenStmtTry = new TokenStmtTry(tryKw);
  3000. tokenStmtTry.tryStmt = WrapTryCatFinInBlock(body);
  3001. tokenStmtTry.finallyStmt = ParseStmtBlock(ref token);
  3002. if(tokenStmtTry.finallyStmt == null)
  3003. return null;
  3004. tokenStmtTry.tryStmt.isTry = true;
  3005. tokenStmtTry.tryStmt.tryStmt = tokenStmtTry;
  3006. tokenStmtTry.finallyStmt.isFinally = true;
  3007. tokenStmtTry.finallyStmt.tryStmt = tokenStmtTry;
  3008. }
  3009. else
  3010. break;
  3011. body = tokenStmtTry;
  3012. }
  3013. if(!(body is TokenStmtTry))
  3014. {
  3015. ErrorMsg(body, "try must have a matching catch and/or finally");
  3016. return null;
  3017. }
  3018. return (TokenStmtTry)body;
  3019. }
  3020. /**
  3021. * @brief Wrap a possible try/catch/finally statement block in a block statement.
  3022. *
  3023. * Given body = try { } catch (string s) { }
  3024. *
  3025. * we return { try { } catch (string s) { } }
  3026. *
  3027. * @param body = a TokenStmtTry or a TokenStmtBlock
  3028. * @returns a TokenStmtBlock
  3029. */
  3030. private TokenStmtBlock WrapTryCatFinInBlock(TokenStmt body)
  3031. {
  3032. if(body is TokenStmtBlock)
  3033. return (TokenStmtBlock)body;
  3034. TokenStmtTry innerTry = (TokenStmtTry)body;
  3035. TokenStmtBlock wrapper = new TokenStmtBlock(body);
  3036. wrapper.statements = innerTry;
  3037. wrapper.outerStmtBlock = currentStmtBlock;
  3038. wrapper.function = currentDeclFunc;
  3039. innerTry.tryStmt.outerStmtBlock = wrapper;
  3040. if(innerTry.catchStmt != null)
  3041. innerTry.catchStmt.outerStmtBlock = wrapper;
  3042. if(innerTry.finallyStmt != null)
  3043. innerTry.finallyStmt.outerStmtBlock = wrapper;
  3044. return wrapper;
  3045. }
  3046. private TokenStmtWhile ParseStmtWhile(ref Token token)
  3047. {
  3048. currentDeclFunc.triviality = Triviality.complex;
  3049. TokenStmtWhile tokenStmtWhile = new TokenStmtWhile(token);
  3050. token = token.nextToken;
  3051. tokenStmtWhile.testRVal = ParseRValParen(ref token);
  3052. if(tokenStmtWhile.testRVal == null)
  3053. return null;
  3054. tokenStmtWhile.bodyStmt = ParseStmt(ref token);
  3055. if(tokenStmtWhile.bodyStmt == null)
  3056. return null;
  3057. return tokenStmtWhile;
  3058. }
  3059. /**
  3060. * @brief parse a variable declaration statement, including init value if any.
  3061. * @param token = points to type or 'constant' token
  3062. * @param initFunc = null: parsing a local var declaration
  3063. * put initialization code in .init
  3064. * else: parsing a global var or field var declaration
  3065. * put initialization code in initFunc.body
  3066. * @returns null: parsing error
  3067. * else: variable declaration encapulating token
  3068. * token = advanced just past semi-colon
  3069. * variables = modified to include the new variable
  3070. */
  3071. private TokenDeclVar ParseDeclVar(ref Token token, TokenDeclVar initFunc)
  3072. {
  3073. TokenDeclVar tokenDeclVar = new TokenDeclVar(token.nextToken, currentDeclFunc, tokenScript);
  3074. // Handle constant declaration.
  3075. // It ends up in the declared variables list for the statement block just like
  3076. // any other variable, except it has .constant = true.
  3077. // The code generator will test that the initialization expression is constant.
  3078. //
  3079. // constant <name> = <value> ;
  3080. if(token is TokenKwConst)
  3081. {
  3082. token = token.nextToken;
  3083. if(!(token is TokenName))
  3084. {
  3085. ErrorMsg(token, "expecting constant name");
  3086. token = SkipPastSemi(token);
  3087. return null;
  3088. }
  3089. tokenDeclVar.name = (TokenName)token;
  3090. token = token.nextToken;
  3091. if(!(token is TokenKwAssign))
  3092. {
  3093. ErrorMsg(token, "expecting =");
  3094. token = SkipPastSemi(token);
  3095. return null;
  3096. }
  3097. token = token.nextToken;
  3098. TokenRVal rVal = ParseRVal(ref token, semiOnly);
  3099. if(rVal == null)
  3100. return null;
  3101. tokenDeclVar.init = rVal;
  3102. tokenDeclVar.constant = true;
  3103. }
  3104. // Otherwise, normal variable declaration with optional initialization value.
  3105. else
  3106. {
  3107. // Build basic encapsulating token with type and name.
  3108. tokenDeclVar.type = (TokenType)token;
  3109. token = token.nextToken;
  3110. if(!(token is TokenName))
  3111. {
  3112. ErrorMsg(token, "expecting variable name");
  3113. token = SkipPastSemi(token);
  3114. return null;
  3115. }
  3116. tokenDeclVar.name = (TokenName)token;
  3117. token = token.nextToken;
  3118. // If just a ;, there is no explicit initialization value.
  3119. // Otherwise, look for an =RVal; expression that has init value.
  3120. if(token is TokenKwSemi)
  3121. {
  3122. token = token.nextToken;
  3123. if(initFunc != null)
  3124. {
  3125. tokenDeclVar.init = TokenRValInitDef.Construct(tokenDeclVar);
  3126. }
  3127. }
  3128. else if(token is TokenKwAssign)
  3129. {
  3130. token = token.nextToken;
  3131. if(initFunc != null)
  3132. {
  3133. currentDeclFunc = initFunc;
  3134. tokenDeclVar.init = ParseRVal(ref token, semiOnly);
  3135. currentDeclFunc = null;
  3136. }
  3137. else
  3138. {
  3139. tokenDeclVar.init = ParseRVal(ref token, semiOnly);
  3140. }
  3141. if(tokenDeclVar.init == null)
  3142. return null;
  3143. }
  3144. else
  3145. {
  3146. ErrorMsg(token, "expecting = or ;");
  3147. token = SkipPastSemi(token);
  3148. return null;
  3149. }
  3150. }
  3151. // If doing local vars, each var goes in its own var frame,
  3152. // to make sure no code before this point can reference it.
  3153. if(currentStmtBlock != null)
  3154. {
  3155. tokenScript.PushVarFrame(true);
  3156. }
  3157. // Can't be same name already in block.
  3158. if(!tokenScript.AddVarEntry(tokenDeclVar))
  3159. {
  3160. ErrorMsg(tokenDeclVar, "duplicate variable " + tokenDeclVar.name.val);
  3161. return null;
  3162. }
  3163. return tokenDeclVar;
  3164. }
  3165. /**
  3166. * @brief Add variable initialization to $globalvarinit, $staticfieldinit or $instfieldinit function.
  3167. * @param initFunc = $globalvarinit, $staticfieldinit or $instfieldinit function
  3168. * @param left = variable being initialized
  3169. * @param init = null: initialize to default value
  3170. * else: initialize to this value
  3171. */
  3172. private void DoVarInit(TokenDeclVar initFunc, TokenLVal left, TokenRVal init)
  3173. {
  3174. // Make a statement that assigns the initialization value to the variable.
  3175. TokenStmt stmt;
  3176. if(init == null)
  3177. {
  3178. TokenStmtVarIniDef tsvid = new TokenStmtVarIniDef(left);
  3179. tsvid.var = left;
  3180. stmt = tsvid;
  3181. }
  3182. else
  3183. {
  3184. TokenKw op = new TokenKwAssign(left);
  3185. TokenStmtRVal tsrv = new TokenStmtRVal(init);
  3186. tsrv.rVal = new TokenRValOpBin(left, op, init);
  3187. stmt = tsrv;
  3188. }
  3189. // Add statement to end of initialization function.
  3190. // Be sure to execute them in same order as in source
  3191. // as some doofus scripts depend on it.
  3192. Token lastStmt = initFunc.body.statements;
  3193. if(lastStmt == null)
  3194. {
  3195. initFunc.body.statements = stmt;
  3196. }
  3197. else
  3198. {
  3199. Token nextStmt;
  3200. while((nextStmt = lastStmt.nextToken) != null)
  3201. {
  3202. lastStmt = nextStmt;
  3203. }
  3204. lastStmt.nextToken = stmt;
  3205. }
  3206. }
  3207. /**
  3208. * @brief parse function declaration argument list
  3209. * @param token = points to TokenKwParOpen
  3210. * @returns null: parse error
  3211. * else: points to token with types and names
  3212. * token = updated past the TokenKw{Brk,Par}Close
  3213. */
  3214. private TokenArgDecl ParseFuncArgs(ref Token token, Type end)
  3215. {
  3216. TokenArgDecl tokenArgDecl = new TokenArgDecl(token);
  3217. bool first = true;
  3218. do
  3219. {
  3220. token = token.nextToken;
  3221. if((token.GetType() == end) && first)
  3222. break;
  3223. if(!(token is TokenType))
  3224. {
  3225. ErrorMsg(token, "expecting arg type");
  3226. token = SkipPastSemi(token);
  3227. return null;
  3228. }
  3229. TokenType type = (TokenType)token;
  3230. token = token.nextToken;
  3231. if(!(token is TokenName))
  3232. {
  3233. ErrorMsg(token, "expecting arg name");
  3234. token = SkipPastSemi(token);
  3235. return null;
  3236. }
  3237. TokenName name = (TokenName)token;
  3238. token = token.nextToken;
  3239. if(!tokenArgDecl.AddArg(type, name))
  3240. {
  3241. ErrorMsg(name, "duplicate arg name");
  3242. }
  3243. first = false;
  3244. } while(token is TokenKwComma);
  3245. if(token.GetType() != end)
  3246. {
  3247. ErrorMsg(token, "expecting comma or close bracket/paren");
  3248. token = SkipPastSemi(token);
  3249. return null;
  3250. }
  3251. token = token.nextToken;
  3252. return tokenArgDecl;
  3253. }
  3254. /**
  3255. * @brief parse right-hand value expression
  3256. * this is where arithmetic-like expressions are processed
  3257. * @param token = points to first token expression
  3258. * @param termTokenType = expression termination token type
  3259. * @returns null: not an RVal
  3260. * else: single token representing whole expression
  3261. * token = if termTokenType.Length == 1, points just past terminating token
  3262. * else, points right at terminating token
  3263. */
  3264. public TokenRVal ParseRVal(ref Token token, Type[] termTokenTypes)
  3265. {
  3266. // Start with pushing the first operand on operand stack.
  3267. BinOp binOps = null;
  3268. TokenRVal operands = GetOperand(ref token);
  3269. if(operands == null)
  3270. return null;
  3271. // Keep scanning until we hit the termination token.
  3272. while(true)
  3273. {
  3274. Type tokType = token.GetType();
  3275. for(int i = termTokenTypes.Length; --i >= 0;)
  3276. {
  3277. if(tokType == termTokenTypes[i])
  3278. goto done;
  3279. }
  3280. // Special form:
  3281. // <operand> is <typeexp>
  3282. if(token is TokenKwIs)
  3283. {
  3284. TokenRValIsType tokenRValIsType = new TokenRValIsType(token);
  3285. token = token.nextToken;
  3286. // Parse the <typeexp>.
  3287. tokenRValIsType.typeExp = ParseTypeExp(ref token);
  3288. if(tokenRValIsType.typeExp == null)
  3289. return null;
  3290. // Replace top operand with result of <operand> is <typeexp>
  3291. tokenRValIsType.rValExp = operands;
  3292. tokenRValIsType.nextToken = operands.nextToken;
  3293. operands = tokenRValIsType;
  3294. // token points just past <typeexp> so see if it is another operator.
  3295. continue;
  3296. }
  3297. // Peek at next operator.
  3298. BinOp binOp = GetOperator(ref token);
  3299. if(binOp == null)
  3300. return null;
  3301. // If there are stacked operators of higher or same precedence than new one,
  3302. // perform their computation then push result back on operand stack.
  3303. //
  3304. // higher or same = left-to-right application of operators
  3305. // eg, a - b - c becomes (a - b) - c
  3306. //
  3307. // higher precedence = right-to-left application of operators
  3308. // eg, a - b - c becomes a - (b - c)
  3309. //
  3310. // Now of course, there is some ugliness necessary:
  3311. // we want: a - b - c => (a - b) - c so we do 'higher or same'
  3312. // but we want: a += b = c => a += (b = c) so we do 'higher only'
  3313. //
  3314. // binOps is the first operator (or null if only one)
  3315. // binOp is the second operator (or first if only one)
  3316. while(binOps != null)
  3317. {
  3318. if(binOps.preced < binOp.preced)
  3319. break; // 1st operator lower than 2nd, so leave 1st on stack to do later
  3320. if(binOps.preced > binOp.preced)
  3321. goto do1st; // 1st op higher than 2nd, so we always do 1st op first
  3322. if(binOps.preced == ASNPR)
  3323. break; // equal preced, if assignment type, leave 1st on stack to do later
  3324. // if non-asn type, do 1st op first (ie left-to-right)
  3325. do1st:
  3326. TokenRVal result = PerformBinOp((TokenRVal)operands.prevToken, binOps, (TokenRVal)operands);
  3327. result.prevToken = operands.prevToken.prevToken;
  3328. operands = result;
  3329. binOps = binOps.pop;
  3330. }
  3331. // Handle conditional expression as a special form:
  3332. // <condexp> ? <trueexp> : <falseexp>
  3333. if(binOp.token is TokenKwQMark)
  3334. {
  3335. TokenRValCondExpr condExpr = new TokenRValCondExpr(binOp.token);
  3336. condExpr.condExpr = operands;
  3337. condExpr.trueExpr = ParseRVal(ref token, new Type[] { typeof(TokenKwColon) });
  3338. condExpr.falseExpr = ParseRVal(ref token, termTokenTypes);
  3339. condExpr.prevToken = operands.prevToken;
  3340. operands = condExpr;
  3341. termTokenTypes = new Type[0];
  3342. goto done;
  3343. }
  3344. // Push new operator on its stack.
  3345. binOp.pop = binOps;
  3346. binOps = binOp;
  3347. // Push next operand on its stack.
  3348. TokenRVal operand = GetOperand(ref token);
  3349. if(operand == null)
  3350. return null;
  3351. operand.prevToken = operands;
  3352. operands = operand;
  3353. }
  3354. done:
  3355. // At end of expression, perform any stacked computations.
  3356. while(binOps != null)
  3357. {
  3358. TokenRVal result = PerformBinOp((TokenRVal)operands.prevToken, binOps, (TokenRVal)operands);
  3359. result.prevToken = operands.prevToken.prevToken;
  3360. operands = result;
  3361. binOps = binOps.pop;
  3362. }
  3363. // There should be exactly one remaining operand on the stack which is our final result.
  3364. if(operands.prevToken != null)
  3365. throw new Exception("too many operands");
  3366. // If only one terminator type possible, advance past the terminator.
  3367. if(termTokenTypes.Length == 1)
  3368. token = token.nextToken;
  3369. return operands;
  3370. }
  3371. private TokenTypeExp ParseTypeExp(ref Token token)
  3372. {
  3373. TokenTypeExp leftOperand = GetTypeExp(ref token);
  3374. if(leftOperand == null)
  3375. return null;
  3376. while((token is TokenKwAnd) || (token is TokenKwOr))
  3377. {
  3378. Token typeBinOp = token;
  3379. token = token.nextToken;
  3380. TokenTypeExp rightOperand = GetTypeExp(ref token);
  3381. if(rightOperand == null)
  3382. return null;
  3383. TokenTypeExpBinOp typeExpBinOp = new TokenTypeExpBinOp(typeBinOp);
  3384. typeExpBinOp.leftOp = leftOperand;
  3385. typeExpBinOp.binOp = typeBinOp;
  3386. typeExpBinOp.rightOp = rightOperand;
  3387. leftOperand = typeExpBinOp;
  3388. }
  3389. return leftOperand;
  3390. }
  3391. private TokenTypeExp GetTypeExp(ref Token token)
  3392. {
  3393. if(token is TokenKwTilde)
  3394. {
  3395. TokenTypeExpNot typeExpNot = new TokenTypeExpNot(token);
  3396. token = token.nextToken;
  3397. typeExpNot.typeExp = GetTypeExp(ref token);
  3398. if(typeExpNot.typeExp == null)
  3399. return null;
  3400. return typeExpNot;
  3401. }
  3402. if(token is TokenKwParOpen)
  3403. {
  3404. TokenTypeExpPar typeExpPar = new TokenTypeExpPar(token);
  3405. token = token.nextToken;
  3406. typeExpPar.typeExp = GetTypeExp(ref token);
  3407. if(typeExpPar.typeExp == null)
  3408. return null;
  3409. if(!(token is TokenKwParClose))
  3410. {
  3411. ErrorMsg(token, "expected close parenthesis");
  3412. token = SkipPastSemi(token);
  3413. return null;
  3414. }
  3415. return typeExpPar;
  3416. }
  3417. if(token is TokenKwUndef)
  3418. {
  3419. TokenTypeExpUndef typeExpUndef = new TokenTypeExpUndef(token);
  3420. token = token.nextToken;
  3421. return typeExpUndef;
  3422. }
  3423. if(token is TokenType)
  3424. {
  3425. TokenTypeExpType typeExpType = new TokenTypeExpType(token);
  3426. typeExpType.typeToken = (TokenType)token;
  3427. token = token.nextToken;
  3428. return typeExpType;
  3429. }
  3430. ErrorMsg(token, "expected type");
  3431. token = SkipPastSemi(token);
  3432. return null;
  3433. }
  3434. /**
  3435. * @brief get a right-hand operand expression token
  3436. * @param token = first token of operand to parse
  3437. * @returns null: invalid operand
  3438. * else: token that bundles or wraps the operand
  3439. * token = points to token following last operand token
  3440. */
  3441. private TokenRVal GetOperand(ref Token token)
  3442. {
  3443. // Prefix unary operators (eg ++, --) requiring an L-value.
  3444. if((token is TokenKwIncr) || (token is TokenKwDecr))
  3445. {
  3446. TokenRValAsnPre asnPre = new TokenRValAsnPre(token);
  3447. asnPre.prefix = token;
  3448. token = token.nextToken;
  3449. TokenRVal op = GetOperand(ref token);
  3450. if(op == null)
  3451. return null;
  3452. if(!(op is TokenLVal))
  3453. {
  3454. ErrorMsg(op, "can pre{in,de}crement only an L-value");
  3455. return null;
  3456. }
  3457. asnPre.lVal = (TokenLVal)op;
  3458. return asnPre;
  3459. }
  3460. // Get the bulk of the operand, ie, without any of the below suffixes.
  3461. TokenRVal operand = GetOperandNoMods(ref token);
  3462. if(operand == null)
  3463. return null;
  3464. modifiers:
  3465. // If followed by '++' or '--', it is post-{in,de}cremented.
  3466. if((token is TokenKwIncr) || (token is TokenKwDecr))
  3467. {
  3468. TokenRValAsnPost asnPost = new TokenRValAsnPost(token);
  3469. asnPost.postfix = token;
  3470. token = token.nextToken;
  3471. if(!(operand is TokenLVal))
  3472. {
  3473. ErrorMsg(operand, "can post{in,de}crement only an L-value");
  3474. return null;
  3475. }
  3476. asnPost.lVal = (TokenLVal)operand;
  3477. return asnPost;
  3478. }
  3479. // If followed by a '.', it is an instance field or instance method reference.
  3480. if(token is TokenKwDot)
  3481. {
  3482. token = token.nextToken;
  3483. if(!(token is TokenName))
  3484. {
  3485. ErrorMsg(token, ". must be followed by field/method name");
  3486. return null;
  3487. }
  3488. TokenLValIField field = new TokenLValIField(token);
  3489. field.baseRVal = operand;
  3490. field.fieldName = (TokenName)token;
  3491. operand = field;
  3492. token = token.nextToken;
  3493. goto modifiers;
  3494. }
  3495. // If followed by a '[', it is an array subscript.
  3496. if(token is TokenKwBrkOpen)
  3497. {
  3498. TokenLValArEle tokenLValArEle = new TokenLValArEle(token);
  3499. token = token.nextToken;
  3500. // Parse subscript(s) expression.
  3501. tokenLValArEle.subRVal = ParseRVal(ref token, brkCloseOnly);
  3502. if(tokenLValArEle.subRVal == null)
  3503. {
  3504. ErrorMsg(tokenLValArEle, "invalid subscript");
  3505. return null;
  3506. }
  3507. // See if comma-separated list of values.
  3508. TokenRVal subscriptRVals;
  3509. int numSubscripts = SplitCommaRVals(tokenLValArEle.subRVal, out subscriptRVals);
  3510. if(numSubscripts > 1)
  3511. {
  3512. // If so, put the values in an LSL_List object.
  3513. TokenRValList rValList = new TokenRValList(tokenLValArEle);
  3514. rValList.rVal = subscriptRVals;
  3515. rValList.nItems = numSubscripts;
  3516. tokenLValArEle.subRVal = rValList;
  3517. }
  3518. // Either way, save array variable name
  3519. // and substitute whole reference for L-value
  3520. tokenLValArEle.baseRVal = operand;
  3521. operand = tokenLValArEle;
  3522. goto modifiers;
  3523. }
  3524. // If followed by a '(', it is a function/method call.
  3525. if(token is TokenKwParOpen)
  3526. {
  3527. operand = ParseRValCall(ref token, operand);
  3528. goto modifiers;
  3529. }
  3530. // If 'new' arraytipe '{', it is an array initializer.
  3531. if((token is TokenKwBrcOpen) && (operand is TokenLValSField) &&
  3532. (((TokenLValSField)operand).fieldName.val == "$new") &&
  3533. ((TokenLValSField)operand).baseType.ToString().EndsWith("]"))
  3534. {
  3535. operand = ParseRValNewArIni(ref token, (TokenLValSField)operand);
  3536. if(operand != null)
  3537. goto modifiers;
  3538. }
  3539. return operand;
  3540. }
  3541. /**
  3542. * @brief same as GetOperand() except doesn't check for any modifiers
  3543. */
  3544. private TokenRVal GetOperandNoMods(ref Token token)
  3545. {
  3546. // Simple unary operators.
  3547. if((token is TokenKwSub) ||
  3548. (token is TokenKwTilde) ||
  3549. (token is TokenKwExclam))
  3550. {
  3551. Token uop = token;
  3552. token = token.nextToken;
  3553. TokenRVal rVal = GetOperand(ref token);
  3554. if(rVal == null)
  3555. return null;
  3556. return PerformUnOp(uop, rVal);
  3557. }
  3558. // Type casting.
  3559. if((token is TokenKwParOpen) &&
  3560. (token.nextToken is TokenType) &&
  3561. (token.nextToken.nextToken is TokenKwParClose))
  3562. {
  3563. TokenType type = (TokenType)token.nextToken;
  3564. token = token.nextToken.nextToken.nextToken;
  3565. TokenRVal rVal = GetOperand(ref token);
  3566. if(rVal == null)
  3567. return null;
  3568. return new TokenRValCast(type, rVal);
  3569. }
  3570. // Parenthesized expression.
  3571. if(token is TokenKwParOpen)
  3572. {
  3573. return ParseRValParen(ref token);
  3574. }
  3575. // Constants.
  3576. if(token is TokenChar)
  3577. {
  3578. TokenRValConst rValConst = new TokenRValConst(token, ((TokenChar)token).val);
  3579. token = token.nextToken;
  3580. return rValConst;
  3581. }
  3582. if(token is TokenFloat)
  3583. {
  3584. TokenRValConst rValConst = new TokenRValConst(token, ((TokenFloat)token).val);
  3585. token = token.nextToken;
  3586. return rValConst;
  3587. }
  3588. if(token is TokenInt)
  3589. {
  3590. TokenRValConst rValConst = new TokenRValConst(token, ((TokenInt)token).val);
  3591. token = token.nextToken;
  3592. return rValConst;
  3593. }
  3594. if(token is TokenStr)
  3595. {
  3596. TokenRValConst rValConst = new TokenRValConst(token, ((TokenStr)token).val);
  3597. token = token.nextToken;
  3598. return rValConst;
  3599. }
  3600. if(token is TokenKwUndef)
  3601. {
  3602. TokenRValUndef rValUndef = new TokenRValUndef((TokenKwUndef)token);
  3603. token = token.nextToken;
  3604. return rValUndef;
  3605. }
  3606. // '<'value,...'>', ie, rotation or vector
  3607. if(token is TokenKwCmpLT)
  3608. {
  3609. Token openBkt = token;
  3610. token = token.nextToken;
  3611. TokenRVal rValAll = ParseRVal(ref token, cmpGTOnly);
  3612. if(rValAll == null)
  3613. return null;
  3614. TokenRVal rVals;
  3615. int nVals = SplitCommaRVals(rValAll, out rVals);
  3616. switch(nVals)
  3617. {
  3618. case 3:
  3619. {
  3620. TokenRValVec rValVec = new TokenRValVec(openBkt);
  3621. rValVec.xRVal = rVals;
  3622. rValVec.yRVal = (TokenRVal)rVals.nextToken;
  3623. rValVec.zRVal = (TokenRVal)rVals.nextToken.nextToken;
  3624. return rValVec;
  3625. }
  3626. case 4:
  3627. {
  3628. TokenRValRot rValRot = new TokenRValRot(openBkt);
  3629. rValRot.xRVal = rVals;
  3630. rValRot.yRVal = (TokenRVal)rVals.nextToken;
  3631. rValRot.zRVal = (TokenRVal)rVals.nextToken.nextToken;
  3632. rValRot.wRVal = (TokenRVal)rVals.nextToken.nextToken.nextToken;
  3633. return rValRot;
  3634. }
  3635. default:
  3636. {
  3637. ErrorMsg(openBkt, "bad rotation/vector");
  3638. token = SkipPastSemi(token);
  3639. return null;
  3640. }
  3641. }
  3642. }
  3643. // '['value,...']', ie, list
  3644. if(token is TokenKwBrkOpen)
  3645. {
  3646. TokenRValList rValList = new TokenRValList(token);
  3647. token = token.nextToken;
  3648. if(token is TokenKwBrkClose)
  3649. {
  3650. token = token.nextToken; // empty list
  3651. }
  3652. else
  3653. {
  3654. TokenRVal rValAll = ParseRVal(ref token, brkCloseOnly);
  3655. if(rValAll == null)
  3656. return null;
  3657. rValList.nItems = SplitCommaRVals(rValAll, out rValList.rVal);
  3658. }
  3659. return rValList;
  3660. }
  3661. // Maybe we have <type>.<name> referencing a static field or method of some type.
  3662. if((token is TokenType) && (token.nextToken is TokenKwDot) && (token.nextToken.nextToken is TokenName))
  3663. {
  3664. TokenLValSField field = new TokenLValSField(token.nextToken.nextToken);
  3665. field.baseType = (TokenType)token;
  3666. field.fieldName = (TokenName)token.nextToken.nextToken;
  3667. token = token.nextToken.nextToken.nextToken;
  3668. return field;
  3669. }
  3670. // Maybe we have 'this' referring to the object of the instance method.
  3671. if(token is TokenKwThis)
  3672. {
  3673. if((currentDeclSDType == null) || !(currentDeclSDType is TokenDeclSDTypeClass))
  3674. {
  3675. ErrorMsg(token, "using 'this' outside class definition");
  3676. token = SkipPastSemi(token);
  3677. return null;
  3678. }
  3679. TokenRValThis zhis = new TokenRValThis(token, (TokenDeclSDTypeClass)currentDeclSDType);
  3680. token = token.nextToken;
  3681. return zhis;
  3682. }
  3683. // Maybe we have 'base' referring to a field/method of the extended class.
  3684. if(token is TokenKwBase)
  3685. {
  3686. if((currentDeclFunc == null) || (currentDeclFunc.sdtClass == null) || !(currentDeclFunc.sdtClass is TokenDeclSDTypeClass))
  3687. {
  3688. ErrorMsg(token, "using 'base' outside method");
  3689. token = SkipPastSemi(token);
  3690. return null;
  3691. }
  3692. if(!(token.nextToken is TokenKwDot) || !(token.nextToken.nextToken is TokenName))
  3693. {
  3694. ErrorMsg(token, "base must be followed by . then field or method name");
  3695. TokenRValThis zhis = new TokenRValThis(token, (TokenDeclSDTypeClass)currentDeclFunc.sdtClass);
  3696. token = token.nextToken;
  3697. return zhis;
  3698. }
  3699. TokenLValBaseField baseField = new TokenLValBaseField(token,
  3700. (TokenName)token.nextToken.nextToken,
  3701. (TokenDeclSDTypeClass)currentDeclFunc.sdtClass);
  3702. token = token.nextToken.nextToken.nextToken;
  3703. return baseField;
  3704. }
  3705. // Maybe we have 'new <script-defined-type>' saying to create an object instance.
  3706. // This ends up generating a call to static function <script-defined-type>.$new(...)
  3707. // whose CIL code is generated by GenerateNewobjBody().
  3708. if(token is TokenKwNew)
  3709. {
  3710. if(!(token.nextToken is TokenType))
  3711. {
  3712. ErrorMsg(token.nextToken, "new must be followed by type");
  3713. token = SkipPastSemi(token);
  3714. return null;
  3715. }
  3716. TokenLValSField field = new TokenLValSField(token.nextToken.nextToken);
  3717. field.baseType = (TokenType)token.nextToken;
  3718. field.fieldName = new TokenName(token, "$new");
  3719. token = token.nextToken.nextToken;
  3720. return field;
  3721. }
  3722. // All we got left is <name>, eg, arg, function, global or local variable reference
  3723. if(token is TokenName)
  3724. {
  3725. TokenLValName name = new TokenLValName((TokenName)token, tokenScript.variablesStack);
  3726. token = token.nextToken;
  3727. return name;
  3728. }
  3729. // Who knows what it is supposed to be?
  3730. ErrorMsg(token, "invalid operand token");
  3731. token = SkipPastSemi(token);
  3732. return null;
  3733. }
  3734. /**
  3735. * @brief Parse a call expression
  3736. * @param token = points to arg list '('
  3737. * @param meth = points to method name being called
  3738. * @returns call expression value
  3739. * token = points just past arg list ')'
  3740. */
  3741. private TokenRValCall ParseRValCall(ref Token token, TokenRVal meth)
  3742. {
  3743. // Set up basic function call struct with function name.
  3744. TokenRValCall rValCall = new TokenRValCall(token);
  3745. rValCall.meth = meth;
  3746. // Parse the call parameters, if any.
  3747. token = token.nextToken;
  3748. if(token is TokenKwParClose)
  3749. {
  3750. token = token.nextToken;
  3751. }
  3752. else
  3753. {
  3754. rValCall.args = ParseRVal(ref token, parCloseOnly);
  3755. if(rValCall.args == null)
  3756. return null;
  3757. rValCall.nArgs = SplitCommaRVals(rValCall.args, out rValCall.args);
  3758. }
  3759. currentDeclFunc.unknownTrivialityCalls.AddLast(rValCall);
  3760. return rValCall;
  3761. }
  3762. /**
  3763. * @brief decode binary operator token
  3764. * @param token = points to token to decode
  3765. * @returns null: invalid operator token
  3766. * else: operator token and precedence
  3767. */
  3768. private BinOp GetOperator(ref Token token)
  3769. {
  3770. BinOp binOp = new BinOp();
  3771. if(precedence.TryGetValue(token.GetType(), out binOp.preced))
  3772. {
  3773. binOp.token = (TokenKw)token;
  3774. token = token.nextToken;
  3775. return binOp;
  3776. }
  3777. if((token is TokenKwSemi) || (token is TokenKwBrcOpen) || (token is TokenKwBrcClose))
  3778. {
  3779. ErrorMsg(token, "premature expression end");
  3780. }
  3781. else
  3782. {
  3783. ErrorMsg(token, "invalid operator");
  3784. }
  3785. token = SkipPastSemi(token);
  3786. return null;
  3787. }
  3788. private class BinOp
  3789. {
  3790. public BinOp pop;
  3791. public TokenKw token;
  3792. public int preced;
  3793. }
  3794. /**
  3795. * @brief Return an R-value expression token that will be used to
  3796. * generate code to perform the operation at runtime.
  3797. * @param left = left-hand operand
  3798. * @param binOp = operator
  3799. * @param right = right-hand operand
  3800. * @returns resultant expression
  3801. */
  3802. private TokenRVal PerformBinOp(TokenRVal left, BinOp binOp, TokenRVal right)
  3803. {
  3804. return new TokenRValOpBin(left, binOp.token, right);
  3805. }
  3806. /**
  3807. * @brief Return an R-value expression token that will be used to
  3808. * generate code to perform the operation at runtime.
  3809. * @param unOp = operator
  3810. * @param right = right-hand operand
  3811. * @returns resultant constant or expression
  3812. */
  3813. private TokenRVal PerformUnOp(Token unOp, TokenRVal right)
  3814. {
  3815. return new TokenRValOpUn((TokenKw)unOp, right);
  3816. }
  3817. /**
  3818. * @brief Parse an array initialization expression.
  3819. * @param token = points to '{' on entry
  3820. * @param newCall = encapsulates a '$new' call
  3821. * @return resultant operand encapsulating '$new' call and initializers
  3822. * token = points just past terminating '}'
  3823. * ...or null if parse error
  3824. */
  3825. private TokenRVal ParseRValNewArIni(ref Token token, TokenLValSField newCall)
  3826. {
  3827. Stack<TokenList> stack = new Stack<TokenList>();
  3828. TokenRValNewArIni arini = new TokenRValNewArIni(token);
  3829. arini.arrayType = newCall.baseType;
  3830. TokenList values = null;
  3831. while(true)
  3832. {
  3833. // open brace means start a (sub-)list
  3834. if(token is TokenKwBrcOpen)
  3835. {
  3836. stack.Push(values);
  3837. values = new TokenList(token);
  3838. token = token.nextToken;
  3839. continue;
  3840. }
  3841. // close brace means end of (sub-)list
  3842. // if final '}' all done parsing
  3843. if(token is TokenKwBrcClose)
  3844. {
  3845. token = token.nextToken; // skip over the '}'
  3846. TokenList innerds = values; // save the list just closed
  3847. arini.valueList = innerds; // it's the top list if it's the last closed
  3848. values = stack.Pop(); // pop to next outer list
  3849. if(values == null)
  3850. return arini; // final '}', we are done
  3851. values.tl.Add(innerds); // put the inner list on end of outer list
  3852. if(token is TokenKwComma)
  3853. { // should have a ',' or '}' next
  3854. token = token.nextToken; // skip over the ','
  3855. }
  3856. else if(!(token is TokenKwBrcClose))
  3857. {
  3858. ErrorMsg(token, "expecting , or } after sublist");
  3859. }
  3860. continue;
  3861. }
  3862. // this is a comma that doesn't have a value expression before it
  3863. // so we take it to mean skip initializing element (leave it zeroes/null etc)
  3864. if(token is TokenKwComma)
  3865. {
  3866. values.tl.Add(token);
  3867. token = token.nextToken;
  3868. continue;
  3869. }
  3870. // parse value expression and skip terminating ',' if any
  3871. TokenRVal append = ParseRVal(ref token, commaOrBrcClose);
  3872. if(append == null)
  3873. return null;
  3874. values.tl.Add(append);
  3875. if(token is TokenKwComma)
  3876. {
  3877. token = token.nextToken;
  3878. }
  3879. }
  3880. }
  3881. /**
  3882. * @brief parse out a parenthesized expression.
  3883. * @param token = points to open parenthesis
  3884. * @returns null: invalid expression
  3885. * else: parenthesized expression token or constant token
  3886. * token = points past the close parenthesis
  3887. */
  3888. private TokenRValParen ParseRValParen(ref Token token)
  3889. {
  3890. if(!(token is TokenKwParOpen))
  3891. {
  3892. ErrorMsg(token, "expecting (");
  3893. token = SkipPastSemi(token);
  3894. return null;
  3895. }
  3896. TokenRValParen tokenRValParen = new TokenRValParen(token);
  3897. token = token.nextToken;
  3898. tokenRValParen.rVal = ParseRVal(ref token, parCloseOnly);
  3899. if(tokenRValParen.rVal == null)
  3900. return null;
  3901. return tokenRValParen;
  3902. }
  3903. /**
  3904. * @brief Split a comma'd RVal into separate expressions
  3905. * @param rValAll = expression containing commas
  3906. * @returns number of comma separated values
  3907. * rVals = values in a null-terminated list linked by rVals.nextToken
  3908. */
  3909. private int SplitCommaRVals(TokenRVal rValAll, out TokenRVal rVals)
  3910. {
  3911. if(!(rValAll is TokenRValOpBin) || !(((TokenRValOpBin)rValAll).opcode is TokenKwComma))
  3912. {
  3913. rVals = rValAll;
  3914. if(rVals.nextToken != null)
  3915. throw new Exception("expected null");
  3916. return 1;
  3917. }
  3918. TokenRValOpBin opBin = (TokenRValOpBin)rValAll;
  3919. TokenRVal rValLeft, rValRight;
  3920. int leftCount = SplitCommaRVals(opBin.rValLeft, out rValLeft);
  3921. int rightCount = SplitCommaRVals(opBin.rValRight, out rValRight);
  3922. rVals = rValLeft;
  3923. while(rValLeft.nextToken != null)
  3924. rValLeft = (TokenRVal)rValLeft.nextToken;
  3925. rValLeft.nextToken = rValRight;
  3926. return leftCount + rightCount;
  3927. }
  3928. /**
  3929. * @brief output error message and remember that there is an error.
  3930. * @param token = what token is associated with the error
  3931. * @param message = error message string
  3932. */
  3933. private void ErrorMsg(Token token, string message)
  3934. {
  3935. if(!errors || (token.file != lastErrorFile) || (token.line > lastErrorLine))
  3936. {
  3937. errors = true;
  3938. lastErrorFile = token.file;
  3939. lastErrorLine = token.line;
  3940. token.ErrorMsg(message);
  3941. }
  3942. }
  3943. /**
  3944. * @brief Skip past the next semicolon (or matched braces)
  3945. * @param token = points to token to skip over
  3946. * @returns token just after the semicolon or close brace
  3947. */
  3948. private Token SkipPastSemi(Token token)
  3949. {
  3950. int braceLevel = 0;
  3951. while(!(token is TokenEnd))
  3952. {
  3953. if((token is TokenKwSemi) && (braceLevel == 0))
  3954. {
  3955. return token.nextToken;
  3956. }
  3957. if(token is TokenKwBrcOpen)
  3958. {
  3959. braceLevel++;
  3960. }
  3961. if((token is TokenKwBrcClose) && (--braceLevel <= 0))
  3962. {
  3963. return token.nextToken;
  3964. }
  3965. token = token.nextToken;
  3966. }
  3967. return token;
  3968. }
  3969. }
  3970. /**
  3971. * @brief Script-defined type declarations
  3972. */
  3973. public abstract class TokenDeclSDType: Token
  3974. {
  3975. protected const byte CLASS = 0;
  3976. protected const byte DELEGATE = 1;
  3977. protected const byte INTERFACE = 2;
  3978. protected const byte TYPEDEF = 3;
  3979. // stuff that gets cloned/copied/transformed when instantiating a generic
  3980. // see InstantiateGeneric() below
  3981. public TokenDeclSDType outerSDType; // null if top-level
  3982. // else points to defining script-defined type
  3983. public Dictionary<string, TokenDeclSDType> innerSDTypes = new Dictionary<string, TokenDeclSDType>();
  3984. // indexed by shortName
  3985. public Token begToken; // token that begins the definition (might be this or something like 'public')
  3986. public Token endToken; // the '}' or ';' that ends the definition
  3987. // generic instantiation assumes none of the rest needs to be cloned (well except for the shortName)
  3988. public int sdTypeIndex = -1; // index in scriptObjCode.sdObjTypesIndx[] array
  3989. public TokenDeclSDTypeClass extends; // only non-null for TokenDeclSDTypeClass's
  3990. public uint accessLevel; // SDT_PRIVATE, SDT_PROTECTED or SDT_PUBLIC
  3991. // ... all top-level types are SDT_PUBLIC
  3992. public VarDict members = new VarDict(false); // declared fields, methods, properties if any
  3993. public Dictionary<string, int> genParams; // list of parameters for generic prototypes
  3994. // null for non-generic prototypes
  3995. // eg, for 'Dictionary<K,V>'
  3996. // ...genParams gives K->0; V->1
  3997. public bool isPartial; // was declared with 'partial' keyword
  3998. // classes only, all others always false
  3999. /*
  4000. * Name of the type.
  4001. * shortName = doesn't include outer class type names
  4002. * eg, 'Engine' for non-generic
  4003. * 'Dictionary<,>' for generic prototype
  4004. * 'Dictionary<string,integer>' for generic instantiation
  4005. * longName = includes all outer class type names if any
  4006. */
  4007. private TokenName _shortName;
  4008. private TokenName _longName;
  4009. public TokenName shortName
  4010. {
  4011. get
  4012. {
  4013. return _shortName;
  4014. }
  4015. set
  4016. {
  4017. _shortName = value;
  4018. _longName = null;
  4019. }
  4020. }
  4021. public TokenName longName
  4022. {
  4023. get
  4024. {
  4025. if(_longName == null)
  4026. {
  4027. _longName = _shortName;
  4028. if(outerSDType != null)
  4029. {
  4030. _longName = new TokenName(_shortName, outerSDType.longName.val + "." + _shortName.val);
  4031. }
  4032. }
  4033. return _longName;
  4034. }
  4035. }
  4036. /*
  4037. * Dictionary used when reading from object file that holds all script-defined types.
  4038. * Not complete though until all types have been read from the object file.
  4039. */
  4040. private Dictionary<string, TokenDeclSDType> sdTypes;
  4041. public TokenDeclSDType(Token t) : base(t) { }
  4042. protected abstract TokenDeclSDType MakeBlank(TokenName shortName);
  4043. public abstract TokenType MakeRefToken(Token t);
  4044. public abstract Type GetSysType();
  4045. public abstract void WriteToFile(BinaryWriter objFileWriter);
  4046. public abstract void ReadFromFile(BinaryReader objFileReader, TextWriter asmFileWriter);
  4047. /**
  4048. * @brief Given that this is a generic prototype, apply the supplied genArgs
  4049. * to create an equivalent instantiated non-generic. This basically
  4050. * makes a copy replacing all the parameter types with the actual
  4051. * argument types.
  4052. * @param this = the prototype to be instantiated, eg, 'Dictionary<string,integer>.Converter'
  4053. * @param name = short name with arguments, eg, 'Converter<float>'.
  4054. * @param genArgs = argument types of just this level, eg, 'float'.
  4055. * @returns clone of this but with arguments applied and spliced in source token stream
  4056. */
  4057. public TokenDeclSDType InstantiateGeneric(string name, TokenType[] genArgs, ScriptReduce reduce)
  4058. {
  4059. // Malloc the struct and give it a name.
  4060. TokenDeclSDType instdecl = this.MakeBlank(new TokenName(this, name));
  4061. // If the original had an outer type, then so does the new one.
  4062. // The outer type will never be a generic prototype, eg, if this
  4063. // is 'ValueList' it will always be inside 'Dictionary<string,integer>'
  4064. // not 'Dictionary' at this point.
  4065. if((this.outerSDType != null) && (this.outerSDType.genParams != null))
  4066. throw new Exception();
  4067. instdecl.outerSDType = this.outerSDType;
  4068. // The generic prototype may have stuff like 'public' just before it and we need to copy that too.
  4069. Token prefix;
  4070. for(prefix = this; (prefix = prefix.prevToken) != null;)
  4071. {
  4072. if(!(prefix is TokenKwPublic) && !(prefix is TokenKwProtected) && !(prefix is TokenKwPrivate))
  4073. break;
  4074. }
  4075. this.begToken = prefix.nextToken;
  4076. // Splice in a copy of the prefix tokens, just before the beginning token of prototype (this.begToken).
  4077. while((prefix = prefix.nextToken) != this)
  4078. {
  4079. SpliceSourceToken(prefix.CopyToken(prefix));
  4080. }
  4081. // Splice instantiation (instdecl) in just before the beginning token of prototype (this.begToken).
  4082. SpliceSourceToken(instdecl);
  4083. // Now for the fun part... Copy the rest of the prototype body to the
  4084. // instantiated body, replacing all generic parameter type tokens with
  4085. // the corresponding generic argument types. Note that the parameters
  4086. // are numbered starting with the outermost so we need the full genArgs
  4087. // array. Eg if we are doing 'Converter<V=float>' from
  4088. // 'Dictionary<T=string,U=integer>.Converter<V=float>', any V's are
  4089. // numbered [2]. Any [0]s or [1]s should be gone by now but it doesn't
  4090. // matter.
  4091. int index;
  4092. Token it, pt;
  4093. TokenDeclSDType innerProto = this;
  4094. TokenDeclSDType innerInst = instdecl;
  4095. for(pt = this; (pt = pt.nextToken) != this.endToken;)
  4096. {
  4097. // Coming across a sub-type's declaration involves a deep copy of the
  4098. // declaration token. Fortunately we are early on in parsing, so there
  4099. // really isn't much to copy:
  4100. // 1) short name is the same, eg, doing List of Dictionary<string,integer>.List is same short name as Dictionary<T,U>.List
  4101. // if generic, eg doing Converter<W> of Dictionary<T,U>.Converter<W>, we have to manually copy the W as well.
  4102. // 2) outerSDType is transformed from Dictionary<T,U> to Dictionary<string,integer>.
  4103. // 3) innerSDTypes is rebuilt when/if we find classes that are inner to this one.
  4104. if(pt is TokenDeclSDType)
  4105. {
  4106. // Make a new TokenDeclSDType{Class,Delegate,Interface}.
  4107. TokenDeclSDType ptSDType = (TokenDeclSDType)pt;
  4108. TokenDeclSDType itSDType = ptSDType.MakeBlank(new TokenName(ptSDType.shortName, ptSDType.shortName.val));
  4109. // Set up the transformed outerSDType.
  4110. // Eg, if we are creating Enumerator of Dictionary<string,integer>.Enumerator,
  4111. // innerProto = Dictionary<T,U> and innerInst = Dictionary<string,integer>.
  4112. itSDType.outerSDType = innerInst;
  4113. // This clone is an inner type of its next outer level.
  4114. reduce.CatalogSDTypeDecl(itSDType);
  4115. // We need to manually copy any generic parameters of the class declaration being cloned.
  4116. // eg, if we are cloning Converter<W>, this is where the W gets copied.
  4117. // Since it is an immutable array of strings, just copy the array pointer, if any.
  4118. itSDType.genParams = ptSDType.genParams;
  4119. // We are now processing tokens for this cloned type declaration.
  4120. innerProto = ptSDType;
  4121. innerInst = itSDType;
  4122. // Splice this clone token in.
  4123. it = itSDType;
  4124. }
  4125. // Check for an generic parameter to substitute out.
  4126. else if((pt is TokenName) && this.genParams.TryGetValue(((TokenName)pt).val, out index))
  4127. {
  4128. it = genArgs[index].CopyToken(pt);
  4129. }
  4130. // Everything else is a simple copy.
  4131. else
  4132. it = pt.CopyToken(pt);
  4133. // Whatever we came up with, splice it into the source token stream.
  4134. SpliceSourceToken(it);
  4135. // Maybe we just finished copying an inner type definition.
  4136. // If so, remember where it ends and pop it from the stack.
  4137. if(innerProto.endToken == pt)
  4138. {
  4139. innerInst.endToken = it;
  4140. innerProto = innerProto.outerSDType;
  4141. innerInst = innerInst.outerSDType;
  4142. }
  4143. }
  4144. // Clone and insert the terminator, either '}' or ';'
  4145. it = pt.CopyToken(pt);
  4146. SpliceSourceToken(it);
  4147. instdecl.endToken = it;
  4148. return instdecl;
  4149. }
  4150. /**
  4151. * @brief Splice a source token in just before the type's beginning keyword.
  4152. */
  4153. private void SpliceSourceToken(Token it)
  4154. {
  4155. it.nextToken = this.begToken;
  4156. (it.prevToken = this.begToken.prevToken).nextToken = it;
  4157. this.begToken.prevToken = it;
  4158. }
  4159. /**
  4160. * @brief Read one of these in from the object file.
  4161. * @param sdTypes = dictionary of script-defined types, not yet complete
  4162. * @param name = script-visible name of this type
  4163. * @param objFileReader = reads from the object file
  4164. * @param asmFileWriter = writes to the disassembly file (might be null)
  4165. */
  4166. public static TokenDeclSDType ReadFromFile(Dictionary<string, TokenDeclSDType> sdTypes, string name,
  4167. BinaryReader objFileReader, TextWriter asmFileWriter)
  4168. {
  4169. string file = objFileReader.ReadString();
  4170. int line = objFileReader.ReadInt32();
  4171. int posn = objFileReader.ReadInt32();
  4172. byte code = objFileReader.ReadByte();
  4173. TokenName n = new TokenName(null, file, line, posn, name);
  4174. TokenDeclSDType sdt;
  4175. switch(code)
  4176. {
  4177. case CLASS:
  4178. {
  4179. sdt = new TokenDeclSDTypeClass(n, false);
  4180. break;
  4181. }
  4182. case DELEGATE:
  4183. {
  4184. sdt = new TokenDeclSDTypeDelegate(n);
  4185. break;
  4186. }
  4187. case INTERFACE:
  4188. {
  4189. sdt = new TokenDeclSDTypeInterface(n);
  4190. break;
  4191. }
  4192. case TYPEDEF:
  4193. {
  4194. sdt = new TokenDeclSDTypeTypedef(n);
  4195. break;
  4196. }
  4197. default:
  4198. throw new Exception();
  4199. }
  4200. sdt.sdTypes = sdTypes;
  4201. sdt.sdTypeIndex = objFileReader.ReadInt32();
  4202. sdt.ReadFromFile(objFileReader, asmFileWriter);
  4203. return sdt;
  4204. }
  4205. /**
  4206. * @brief Convert a typename string to a type token
  4207. * @param name = script-visible name of token to create,
  4208. * either a script-defined type or an LSL-defined type
  4209. * @returns type token
  4210. */
  4211. protected TokenType MakeTypeToken(string name)
  4212. {
  4213. TokenDeclSDType sdtdecl;
  4214. if(sdTypes.TryGetValue(name, out sdtdecl))
  4215. return sdtdecl.MakeRefToken(this);
  4216. return TokenType.FromLSLType(this, name);
  4217. }
  4218. // debugging - returns, eg, 'Dictionary<T,U>.Enumerator.Node'
  4219. public override void DebString(StringBuilder sb)
  4220. {
  4221. // get long name broken down into segments from outermost to this
  4222. Stack<TokenDeclSDType> declStack = new Stack<TokenDeclSDType>();
  4223. for(TokenDeclSDType decl = this; decl != null; decl = decl.outerSDType)
  4224. {
  4225. declStack.Push(decl);
  4226. }
  4227. // output each segment's name followed by our args for it
  4228. // starting with outermost and ending with this
  4229. while(declStack.Count > 0)
  4230. {
  4231. TokenDeclSDType decl = declStack.Pop();
  4232. sb.Append(decl.shortName.val);
  4233. if(decl.genParams != null)
  4234. {
  4235. sb.Append('<');
  4236. string[] parms = new string[decl.genParams.Count];
  4237. foreach(KeyValuePair<string, int> kvp in decl.genParams)
  4238. {
  4239. parms[kvp.Value] = kvp.Key;
  4240. }
  4241. for(int j = 0; j < parms.Length;)
  4242. {
  4243. sb.Append(parms[j]);
  4244. if(++j < parms.Length)
  4245. sb.Append(',');
  4246. }
  4247. sb.Append('>');
  4248. }
  4249. if(declStack.Count > 0)
  4250. sb.Append('.');
  4251. }
  4252. }
  4253. }
  4254. public class TokenDeclSDTypeClass: TokenDeclSDType
  4255. {
  4256. public List<TokenDeclSDTypeInterface> implements = new List<TokenDeclSDTypeInterface>();
  4257. public TokenDeclVar instFieldInit; // $instfieldinit function to do instance field initializations
  4258. public TokenDeclVar staticFieldInit; // $staticfieldinit function to do static field initializations
  4259. public Dictionary<string, int> intfIndices = new Dictionary<string, int>(); // longname => this.iFaces index
  4260. public TokenDeclSDTypeInterface[] iFaces; // array of implemented interfaces
  4261. // low-end entries copied from rootward classes
  4262. public TokenDeclVar[][] iImplFunc; // iImplFunc[i][j]:
  4263. // low-end [i] entries copied from rootward classes
  4264. // i = interface number from this.intfIndices[name]
  4265. // j = method of interface from iface.methods[name].vTableIndex
  4266. public TokenType arrayOfType; // if array, it's an array of this type, else null
  4267. public int arrayOfRank; // if array, it has this number of dimensions, else zero
  4268. public bool slotsAssigned; // set true when slots have been assigned...
  4269. public XMRInstArSizes instSizes = new XMRInstArSizes();
  4270. // number of instance fields of various types
  4271. public int numVirtFuncs; // number of virtual functions
  4272. public int numInterfaces; // number of implemented interfaces
  4273. private string extendsStr;
  4274. private string arrayOfTypeStr;
  4275. private List<StackedMethod> stackedMethods;
  4276. private List<StackedIFace> stackedIFaces;
  4277. public DynamicMethod[] vDynMeths; // virtual method entrypoints
  4278. public Type[] vMethTypes; // virtual method delegate types
  4279. public DynamicMethod[][] iDynMeths; // interface method entrypoints
  4280. public Type[][] iMethTypes; // interface method types
  4281. // low-end [i] entries copied from rootward classes
  4282. // i = interface number from this.intfIndices[name]
  4283. // j = method of interface from iface.methods[name].vTableIndex
  4284. public TokenDeclSDTypeClass(TokenName shortName, bool isPartial) : base(shortName)
  4285. {
  4286. this.shortName = shortName;
  4287. this.isPartial = isPartial;
  4288. }
  4289. protected override TokenDeclSDType MakeBlank(TokenName shortName)
  4290. {
  4291. return new TokenDeclSDTypeClass(shortName, false);
  4292. }
  4293. public override TokenType MakeRefToken(Token t)
  4294. {
  4295. return new TokenTypeSDTypeClass(t, this);
  4296. }
  4297. public override Type GetSysType()
  4298. {
  4299. return typeof(XMRSDTypeClObj);
  4300. }
  4301. /**
  4302. * @brief See if the class implements the interface.
  4303. * Do a recursive (deep) check in all rootward classes.
  4304. */
  4305. public bool CanCastToIntf(TokenDeclSDTypeInterface intf)
  4306. {
  4307. if(this.implements.Contains(intf))
  4308. return true;
  4309. if(this.extends == null)
  4310. return false;
  4311. return this.extends.CanCastToIntf(intf);
  4312. }
  4313. /**
  4314. * @brief Write enough out so we can reconstruct with ReadFromFile.
  4315. */
  4316. public override void WriteToFile(BinaryWriter objFileWriter)
  4317. {
  4318. objFileWriter.Write(this.file);
  4319. objFileWriter.Write(this.line);
  4320. objFileWriter.Write(this.posn);
  4321. objFileWriter.Write((byte)CLASS);
  4322. objFileWriter.Write(this.sdTypeIndex);
  4323. this.instSizes.WriteToFile(objFileWriter);
  4324. objFileWriter.Write(numVirtFuncs);
  4325. if(extends == null)
  4326. {
  4327. objFileWriter.Write("");
  4328. }
  4329. else
  4330. {
  4331. objFileWriter.Write(extends.longName.val);
  4332. }
  4333. objFileWriter.Write(arrayOfRank);
  4334. if(arrayOfRank > 0)
  4335. objFileWriter.Write(arrayOfType.ToString());
  4336. foreach(TokenDeclVar meth in members)
  4337. {
  4338. if((meth.retType != null) && (meth.vTableIndex >= 0))
  4339. {
  4340. objFileWriter.Write(meth.vTableIndex);
  4341. objFileWriter.Write(meth.GetObjCodeName());
  4342. objFileWriter.Write(meth.GetDelType().decl.GetWholeSig());
  4343. }
  4344. }
  4345. objFileWriter.Write(-1);
  4346. int numIFaces = iImplFunc.Length;
  4347. objFileWriter.Write(numIFaces);
  4348. for(int i = 0; i < numIFaces; i++)
  4349. {
  4350. objFileWriter.Write(iFaces[i].longName.val);
  4351. TokenDeclVar[] meths = iImplFunc[i];
  4352. int numMeths = 0;
  4353. if(meths != null)
  4354. numMeths = meths.Length;
  4355. objFileWriter.Write(numMeths);
  4356. for(int j = 0; j < numMeths; j++)
  4357. {
  4358. TokenDeclVar meth = meths[j];
  4359. objFileWriter.Write(meth.vTableIndex);
  4360. objFileWriter.Write(meth.GetObjCodeName());
  4361. objFileWriter.Write(meth.GetDelType().decl.GetWholeSig());
  4362. }
  4363. }
  4364. }
  4365. /**
  4366. * @brief Reconstruct from the file.
  4367. */
  4368. public override void ReadFromFile(BinaryReader objFileReader, TextWriter asmFileWriter)
  4369. {
  4370. instSizes.ReadFromFile(objFileReader);
  4371. numVirtFuncs = objFileReader.ReadInt32();
  4372. extendsStr = objFileReader.ReadString();
  4373. arrayOfRank = objFileReader.ReadInt32();
  4374. if(arrayOfRank > 0)
  4375. arrayOfTypeStr = objFileReader.ReadString();
  4376. if(asmFileWriter != null)
  4377. {
  4378. instSizes.WriteAsmFile(asmFileWriter, extendsStr + "." + shortName.val + ".numInst");
  4379. }
  4380. stackedMethods = new List<StackedMethod>();
  4381. int vTableIndex;
  4382. while((vTableIndex = objFileReader.ReadInt32()) >= 0)
  4383. {
  4384. StackedMethod sm;
  4385. sm.methVTI = vTableIndex;
  4386. sm.methName = objFileReader.ReadString();
  4387. sm.methSig = objFileReader.ReadString();
  4388. stackedMethods.Add(sm);
  4389. }
  4390. int numIFaces = objFileReader.ReadInt32();
  4391. if(numIFaces > 0)
  4392. {
  4393. iDynMeths = new DynamicMethod[numIFaces][];
  4394. iMethTypes = new Type[numIFaces][];
  4395. stackedIFaces = new List<StackedIFace>();
  4396. for(int i = 0; i < numIFaces; i++)
  4397. {
  4398. string iFaceName = objFileReader.ReadString();
  4399. intfIndices[iFaceName] = i;
  4400. int numMeths = objFileReader.ReadInt32();
  4401. iDynMeths[i] = new DynamicMethod[numMeths];
  4402. iMethTypes[i] = new Type[numMeths];
  4403. for(int j = 0; j < numMeths; j++)
  4404. {
  4405. StackedIFace si;
  4406. si.iFaceIndex = i;
  4407. si.methIndex = j;
  4408. si.vTableIndex = objFileReader.ReadInt32();
  4409. si.methName = objFileReader.ReadString();
  4410. si.methSig = objFileReader.ReadString();
  4411. stackedIFaces.Add(si);
  4412. }
  4413. }
  4414. }
  4415. }
  4416. private struct StackedMethod
  4417. {
  4418. public int methVTI;
  4419. public string methName;
  4420. public string methSig;
  4421. }
  4422. private struct StackedIFace
  4423. {
  4424. public int iFaceIndex; // which implemented interface
  4425. public int methIndex; // which method of that interface
  4426. public int vTableIndex; // <0: implemented by non-virtual; else: implemented by virtual
  4427. public string methName; // object code name of implementing method (GetObjCodeName)
  4428. public string methSig; // method signature incl return type (GetWholeSig)
  4429. }
  4430. /**
  4431. * @brief Called after all dynamic method code has been generated to fill in vDynMeths and vMethTypes
  4432. * Also fills in iDynMeths, iMethTypes.
  4433. */
  4434. public void FillVTables(ScriptObjCode scriptObjCode)
  4435. {
  4436. if(extendsStr != null)
  4437. {
  4438. if(extendsStr != "")
  4439. {
  4440. extends = (TokenDeclSDTypeClass)scriptObjCode.sdObjTypesName[extendsStr];
  4441. extends.FillVTables(scriptObjCode);
  4442. }
  4443. extendsStr = null;
  4444. }
  4445. if(arrayOfTypeStr != null)
  4446. {
  4447. arrayOfType = MakeTypeToken(arrayOfTypeStr);
  4448. arrayOfTypeStr = null;
  4449. }
  4450. if((numVirtFuncs > 0) && (stackedMethods != null))
  4451. {
  4452. // Allocate arrays big enough for mine plus type we are extending.
  4453. vDynMeths = new DynamicMethod[numVirtFuncs];
  4454. vMethTypes = new Type[numVirtFuncs];
  4455. // Fill in low parts from type we are extending.
  4456. if(extends != null)
  4457. {
  4458. int n = extends.numVirtFuncs;
  4459. for(int i = 0; i < n; i++)
  4460. {
  4461. vDynMeths[i] = extends.vDynMeths[i];
  4462. vMethTypes[i] = extends.vMethTypes[i];
  4463. }
  4464. }
  4465. // Fill in high parts with my own methods.
  4466. // Might also overwrite lower ones with 'override' methods.
  4467. foreach(StackedMethod sm in stackedMethods)
  4468. {
  4469. int i = sm.methVTI;
  4470. string methName = sm.methName;
  4471. DynamicMethod dm;
  4472. if(scriptObjCode.dynamicMethods.TryGetValue(methName, out dm))
  4473. {
  4474. // method is not abstract
  4475. vDynMeths[i] = dm;
  4476. vMethTypes[i] = GetDynamicMethodDelegateType(dm, sm.methSig);
  4477. }
  4478. }
  4479. stackedMethods = null;
  4480. }
  4481. if(stackedIFaces != null)
  4482. {
  4483. foreach(StackedIFace si in stackedIFaces)
  4484. {
  4485. int i = si.iFaceIndex;
  4486. int j = si.methIndex;
  4487. int vti = si.vTableIndex;
  4488. string methName = si.methName;
  4489. DynamicMethod dm = scriptObjCode.dynamicMethods[methName];
  4490. iDynMeths[i][j] = (vti < 0) ? dm : vDynMeths[vti];
  4491. iMethTypes[i][j] = GetDynamicMethodDelegateType(dm, si.methSig);
  4492. }
  4493. stackedIFaces = null;
  4494. }
  4495. }
  4496. private Type GetDynamicMethodDelegateType(DynamicMethod dm, string methSig)
  4497. {
  4498. Type retType = dm.ReturnType;
  4499. ParameterInfo[] pi = dm.GetParameters();
  4500. Type[] argTypes = new Type[pi.Length];
  4501. for(int j = 0; j < pi.Length; j++)
  4502. {
  4503. argTypes[j] = pi[j].ParameterType;
  4504. }
  4505. return DelegateCommon.GetType(retType, argTypes, methSig);
  4506. }
  4507. public override void DebString(StringBuilder sb)
  4508. {
  4509. // Don't output if array of some type.
  4510. // They will be re-instantiated as referenced by rest of script.
  4511. if(arrayOfType != null)
  4512. return;
  4513. // This class name and extended/implemented type declaration.
  4514. sb.Append("class ");
  4515. sb.Append(shortName.val);
  4516. bool first = true;
  4517. if(extends != null)
  4518. {
  4519. sb.Append(" : ");
  4520. sb.Append(extends.longName);
  4521. first = false;
  4522. }
  4523. foreach(TokenDeclSDType impld in implements)
  4524. {
  4525. sb.Append(first ? " : " : ", ");
  4526. sb.Append(impld.longName);
  4527. first = false;
  4528. }
  4529. sb.Append(" {");
  4530. // Inner type definitions.
  4531. foreach(TokenDeclSDType subs in innerSDTypes.Values)
  4532. {
  4533. subs.DebString(sb);
  4534. }
  4535. // Members (fields, methods, properties).
  4536. foreach(TokenDeclVar memb in members)
  4537. {
  4538. if((memb == instFieldInit) || (memb == staticFieldInit))
  4539. {
  4540. memb.DebStringInitFields(sb);
  4541. }
  4542. else if(memb.retType != null)
  4543. {
  4544. memb.DebString(sb);
  4545. }
  4546. }
  4547. sb.Append('}');
  4548. }
  4549. }
  4550. public class TokenDeclSDTypeDelegate: TokenDeclSDType
  4551. {
  4552. private TokenType retType;
  4553. private TokenType[] argTypes;
  4554. private string argSig;
  4555. private string wholeSig;
  4556. private Type sysType;
  4557. private Type retSysType;
  4558. private Type[] argSysTypes;
  4559. private string retStr;
  4560. private string[] argStrs;
  4561. private static Dictionary<string, TokenDeclSDTypeDelegate> inlines = new Dictionary<string, TokenDeclSDTypeDelegate>();
  4562. private static Dictionary<Type, string> inlrevs = new Dictionary<Type, string>();
  4563. public TokenDeclSDTypeDelegate(TokenName shortName) : base(shortName)
  4564. {
  4565. this.shortName = shortName;
  4566. }
  4567. public void SetRetArgTypes(TokenType retType, TokenType[] argTypes)
  4568. {
  4569. this.retType = retType;
  4570. this.argTypes = argTypes;
  4571. }
  4572. protected override TokenDeclSDType MakeBlank(TokenName shortName)
  4573. {
  4574. return new TokenDeclSDTypeDelegate(shortName);
  4575. }
  4576. public override TokenType MakeRefToken(Token t)
  4577. {
  4578. return new TokenTypeSDTypeDelegate(t, this);
  4579. }
  4580. /**
  4581. * @brief Get system type for the whole delegate.
  4582. */
  4583. public override Type GetSysType()
  4584. {
  4585. if(sysType == null)
  4586. FillInStuff();
  4587. return sysType;
  4588. }
  4589. /**
  4590. * @brief Get the function's return value type (TokenTypeVoid if void, never null)
  4591. */
  4592. public TokenType GetRetType()
  4593. {
  4594. if(retType == null)
  4595. FillInStuff();
  4596. return retType;
  4597. }
  4598. /**
  4599. * @brief Get the function's argument types
  4600. */
  4601. public TokenType[] GetArgTypes()
  4602. {
  4603. if(argTypes == null)
  4604. FillInStuff();
  4605. return argTypes;
  4606. }
  4607. /**
  4608. * @brief Get signature for the whole delegate, eg, "void(integer,list)"
  4609. */
  4610. public string GetWholeSig()
  4611. {
  4612. if(wholeSig == null)
  4613. FillInStuff();
  4614. return wholeSig;
  4615. }
  4616. /**
  4617. * @brief Get signature for the arguments, eg, "(integer,list)"
  4618. */
  4619. public string GetArgSig()
  4620. {
  4621. if(argSig == null)
  4622. FillInStuff();
  4623. return argSig;
  4624. }
  4625. /**
  4626. * @brief Find out how to create one of these delegates.
  4627. */
  4628. public ConstructorInfo GetConstructorInfo()
  4629. {
  4630. if(sysType == null)
  4631. FillInStuff();
  4632. return sysType.GetConstructor(DelegateCommon.constructorArgTypes);
  4633. }
  4634. /**
  4635. * @brief Find out how to call what one of these delegates points to.
  4636. */
  4637. public MethodInfo GetInvokerInfo()
  4638. {
  4639. if(sysType == null)
  4640. FillInStuff();
  4641. return sysType.GetMethod("Invoke", argSysTypes);
  4642. }
  4643. /**
  4644. * @brief Write enough out to a file so delegate can be reconstructed in ReadFromFile().
  4645. */
  4646. public override void WriteToFile(BinaryWriter objFileWriter)
  4647. {
  4648. objFileWriter.Write(this.file);
  4649. objFileWriter.Write(this.line);
  4650. objFileWriter.Write(this.posn);
  4651. objFileWriter.Write((byte)DELEGATE);
  4652. objFileWriter.Write(this.sdTypeIndex);
  4653. objFileWriter.Write(retType.ToString());
  4654. int nArgs = argTypes.Length;
  4655. objFileWriter.Write(nArgs);
  4656. for(int i = 0; i < nArgs; i++)
  4657. {
  4658. objFileWriter.Write(argTypes[i].ToString());
  4659. }
  4660. }
  4661. /**
  4662. * @brief Read that data from file so we can reconstruct.
  4663. * Don't actually reconstruct yet in case any forward-referenced types are undefined.
  4664. */
  4665. public override void ReadFromFile(BinaryReader objFileReader, TextWriter asmFileWriter)
  4666. {
  4667. retStr = objFileReader.ReadString();
  4668. int nArgs = objFileReader.ReadInt32();
  4669. if(asmFileWriter != null)
  4670. {
  4671. asmFileWriter.Write(" delegate " + retStr + " " + longName.val + "(");
  4672. }
  4673. argStrs = new string[nArgs];
  4674. for(int i = 0; i < nArgs; i++)
  4675. {
  4676. argStrs[i] = objFileReader.ReadString();
  4677. if(asmFileWriter != null)
  4678. {
  4679. if(i > 0)
  4680. asmFileWriter.Write(",");
  4681. asmFileWriter.Write(argStrs[i]);
  4682. }
  4683. }
  4684. if(asmFileWriter != null)
  4685. {
  4686. asmFileWriter.WriteLine(");");
  4687. }
  4688. }
  4689. /**
  4690. * @brief Fill in missing internal data.
  4691. */
  4692. private void FillInStuff()
  4693. {
  4694. int nArgs;
  4695. // This happens when the node was restored via ReadFromFile().
  4696. // It leaves the types in retStr/argStrs for resolution after
  4697. // all definitions have been read from the object file in case
  4698. // there are forward references.
  4699. if(retType == null)
  4700. {
  4701. retType = MakeTypeToken(retStr);
  4702. }
  4703. if(argTypes == null)
  4704. {
  4705. nArgs = argStrs.Length;
  4706. argTypes = new TokenType[nArgs];
  4707. for(int i = 0; i < nArgs; i++)
  4708. {
  4709. argTypes[i] = MakeTypeToken(argStrs[i]);
  4710. }
  4711. }
  4712. // Fill in system types from token types.
  4713. // Might as well build the signature strings too from token types.
  4714. retSysType = retType.ToSysType();
  4715. nArgs = argTypes.Length;
  4716. StringBuilder sb = new StringBuilder();
  4717. argSysTypes = new Type[nArgs];
  4718. sb.Append('(');
  4719. for(int i = 0; i < nArgs; i++)
  4720. {
  4721. if(i > 0)
  4722. sb.Append(',');
  4723. sb.Append(argTypes[i].ToString());
  4724. argSysTypes[i] = argTypes[i].ToSysType();
  4725. }
  4726. sb.Append(')');
  4727. argSig = sb.ToString();
  4728. wholeSig = retType.ToString() + argSig;
  4729. // Now we can create a system delegate type from the given
  4730. // return and argument types. Give it an unique name using
  4731. // the whole signature string.
  4732. sysType = DelegateCommon.GetType(retSysType, argSysTypes, wholeSig);
  4733. }
  4734. /**
  4735. * @brief create delegate reference token for inline functions.
  4736. * there is just one instance of these per inline function
  4737. * shared by all scripts, and it is just used when the
  4738. * script engine is loaded.
  4739. */
  4740. public static TokenDeclSDTypeDelegate CreateInline(TokenType retType, TokenType[] argTypes)
  4741. {
  4742. TokenDeclSDTypeDelegate decldel;
  4743. // Name it after the whole signature string.
  4744. StringBuilder sb = new StringBuilder("$inline");
  4745. sb.Append(retType.ToString());
  4746. sb.Append("(");
  4747. bool first = true;
  4748. foreach(TokenType at in argTypes)
  4749. {
  4750. if(!first)
  4751. sb.Append(",");
  4752. sb.Append(at.ToString());
  4753. first = false;
  4754. }
  4755. sb.Append(")");
  4756. string inlname = sb.ToString();
  4757. if(!inlines.TryGetValue(inlname, out decldel))
  4758. {
  4759. // Create the corresponding declaration and link to it
  4760. TokenName name = new TokenName(null, inlname);
  4761. decldel = new TokenDeclSDTypeDelegate(name);
  4762. decldel.retType = retType;
  4763. decldel.argTypes = argTypes;
  4764. inlines.Add(inlname, decldel);
  4765. inlrevs.Add(decldel.GetSysType(), inlname);
  4766. }
  4767. return decldel;
  4768. }
  4769. public static string TryGetInlineName(Type sysType)
  4770. {
  4771. string name;
  4772. if(!inlrevs.TryGetValue(sysType, out name))
  4773. return null;
  4774. return name;
  4775. }
  4776. public static Type TryGetInlineSysType(string name)
  4777. {
  4778. TokenDeclSDTypeDelegate decl;
  4779. if(!inlines.TryGetValue(name, out decl))
  4780. return null;
  4781. return decl.GetSysType();
  4782. }
  4783. }
  4784. public class TokenDeclSDTypeInterface: TokenDeclSDType
  4785. {
  4786. public VarDict methsNProps = new VarDict(false);
  4787. // any class that implements this interface
  4788. // must implement all of these methods & properties
  4789. public List<TokenDeclSDTypeInterface> implements = new List<TokenDeclSDTypeInterface>();
  4790. // any class that implements this interface
  4791. // must also implement all of the methods & properties
  4792. // of all of these interfaces
  4793. public TokenDeclSDTypeInterface(TokenName shortName) : base(shortName)
  4794. {
  4795. this.shortName = shortName;
  4796. }
  4797. protected override TokenDeclSDType MakeBlank(TokenName shortName)
  4798. {
  4799. return new TokenDeclSDTypeInterface(shortName);
  4800. }
  4801. public override TokenType MakeRefToken(Token t)
  4802. {
  4803. return new TokenTypeSDTypeInterface(t, this);
  4804. }
  4805. public override Type GetSysType()
  4806. {
  4807. // interfaces are implemented as arrays of delegates
  4808. // they are taken from iDynMeths[interfaceIndex] of a script-defined class object
  4809. return typeof(Delegate[]);
  4810. }
  4811. public override void WriteToFile(BinaryWriter objFileWriter)
  4812. {
  4813. objFileWriter.Write(this.file);
  4814. objFileWriter.Write(this.line);
  4815. objFileWriter.Write(this.posn);
  4816. objFileWriter.Write((byte)INTERFACE);
  4817. objFileWriter.Write(this.sdTypeIndex);
  4818. }
  4819. public override void ReadFromFile(BinaryReader objFileReader, TextWriter asmFileWriter)
  4820. {
  4821. }
  4822. /**
  4823. * @brief Add this interface to the list of interfaces implemented by a class if not already.
  4824. * And also add this interface's implemented interfaces to the class for those not already there,
  4825. * just as if the class itself had declared to implement those interfaces.
  4826. */
  4827. public void AddToClassDecl(TokenDeclSDTypeClass tokdeclcl)
  4828. {
  4829. if(!tokdeclcl.implements.Contains(this))
  4830. {
  4831. tokdeclcl.implements.Add(this);
  4832. foreach(TokenDeclSDTypeInterface subimpl in this.implements)
  4833. {
  4834. subimpl.AddToClassDecl(tokdeclcl);
  4835. }
  4836. }
  4837. }
  4838. /**
  4839. * @brief See if the 'this' interface implements the new interface.
  4840. * Do a recursive (deep) check.
  4841. */
  4842. public bool Implements(TokenDeclSDTypeInterface newDecl)
  4843. {
  4844. foreach(TokenDeclSDTypeInterface ii in this.implements)
  4845. {
  4846. if(ii == newDecl)
  4847. return true;
  4848. if(ii.Implements(newDecl))
  4849. return true;
  4850. }
  4851. return false;
  4852. }
  4853. /**
  4854. * @brief Scan an interface and all its implemented interfaces for a method or property
  4855. * @param scg = script code generator (ie, which script is being compiled)
  4856. * @param fieldName = name of the member being looked for
  4857. * @param argsig = the method's argument signature
  4858. * @returns null: no such member; intf = undefined
  4859. * else: member; intf = which interface actually found in
  4860. */
  4861. public TokenDeclVar FindIFaceMember(ScriptCodeGen scg, TokenName fieldName, TokenType[] argsig, out TokenDeclSDTypeInterface intf)
  4862. {
  4863. intf = this;
  4864. TokenDeclVar var = scg.FindSingleMember(this.methsNProps, fieldName, argsig);
  4865. if(var == null)
  4866. {
  4867. foreach(TokenDeclSDTypeInterface ii in this.implements)
  4868. {
  4869. var = ii.FindIFaceMember(scg, fieldName, argsig, out intf);
  4870. if(var != null)
  4871. break;
  4872. }
  4873. }
  4874. return var;
  4875. }
  4876. }
  4877. public class TokenDeclSDTypeTypedef: TokenDeclSDType
  4878. {
  4879. public TokenDeclSDTypeTypedef(TokenName shortName) : base(shortName)
  4880. {
  4881. this.shortName = shortName;
  4882. }
  4883. protected override TokenDeclSDType MakeBlank(TokenName shortName)
  4884. {
  4885. return new TokenDeclSDTypeTypedef(shortName);
  4886. }
  4887. public override TokenType MakeRefToken(Token t)
  4888. {
  4889. // if our body is a single type token, that is what we return
  4890. // otherwise return null saying maybe our body needs some substitutions
  4891. if(!(this.nextToken is TokenType))
  4892. return null;
  4893. if(this.nextToken.nextToken != this.endToken)
  4894. {
  4895. this.nextToken.nextToken.ErrorMsg("extra tokens for typedef");
  4896. return null;
  4897. }
  4898. return (TokenType)this.nextToken.CopyToken(t);
  4899. }
  4900. public override Type GetSysType()
  4901. {
  4902. // we are just a macro
  4903. // we are asked for system type because we are cataloged
  4904. // but we don't really have one so return null
  4905. return null;
  4906. }
  4907. public override void WriteToFile(BinaryWriter objFileWriter)
  4908. {
  4909. objFileWriter.Write(this.file);
  4910. objFileWriter.Write(this.line);
  4911. objFileWriter.Write(this.posn);
  4912. objFileWriter.Write((byte)TYPEDEF);
  4913. objFileWriter.Write(this.sdTypeIndex);
  4914. }
  4915. public override void ReadFromFile(BinaryReader objFileReader, TextWriter asmFileWriter)
  4916. {
  4917. }
  4918. }
  4919. /**
  4920. * @brief Script-defined type references.
  4921. * These occur in the source code wherever it specifies (eg, variable declaration) a script-defined type.
  4922. * These must be copyable via CopyToken().
  4923. */
  4924. public abstract class TokenTypeSDType: TokenType
  4925. {
  4926. public TokenTypeSDType(TokenErrorMessage emsg, string file, int line, int posn) : base(emsg, file, line, posn) { }
  4927. public TokenTypeSDType(Token t) : base(t) { }
  4928. public abstract TokenDeclSDType GetDecl();
  4929. public abstract void SetDecl(TokenDeclSDType decl);
  4930. }
  4931. public class TokenTypeSDTypeClass: TokenTypeSDType
  4932. {
  4933. private static readonly FieldInfo iarSDTClObjsFieldInfo = typeof(XMRInstArrays).GetField("iarSDTClObjs");
  4934. public TokenDeclSDTypeClass decl;
  4935. public TokenTypeSDTypeClass(Token t, TokenDeclSDTypeClass decl) : base(t)
  4936. {
  4937. this.decl = decl;
  4938. }
  4939. public override TokenDeclSDType GetDecl()
  4940. {
  4941. return decl;
  4942. }
  4943. public override void SetDecl(TokenDeclSDType decl)
  4944. {
  4945. this.decl = (TokenDeclSDTypeClass)decl;
  4946. }
  4947. public override string ToString()
  4948. {
  4949. return decl.longName.val;
  4950. }
  4951. public override Type ToSysType()
  4952. {
  4953. return typeof(XMRSDTypeClObj);
  4954. }
  4955. public override void AssignVarSlot(TokenDeclVar declVar, XMRInstArSizes ias)
  4956. {
  4957. declVar.vTableArray = iarSDTClObjsFieldInfo;
  4958. declVar.vTableIndex = ias.iasSDTClObjs++;
  4959. }
  4960. // debugging
  4961. public override void DebString(StringBuilder sb)
  4962. {
  4963. sb.Append(decl.longName);
  4964. }
  4965. }
  4966. public class TokenTypeSDTypeDelegate: TokenTypeSDType
  4967. {
  4968. private static readonly FieldInfo iarObjectsFieldInfo = typeof(XMRInstArrays).GetField("iarObjects");
  4969. public TokenDeclSDTypeDelegate decl;
  4970. /**
  4971. * @brief create a reference to an explicitly declared delegate
  4972. * @param t = where the reference is being made in the source file
  4973. * @param decl = the explicit delegate declaration
  4974. */
  4975. public TokenTypeSDTypeDelegate(Token t, TokenDeclSDTypeDelegate decl) : base(t)
  4976. {
  4977. this.decl = decl;
  4978. }
  4979. public override TokenDeclSDType GetDecl()
  4980. {
  4981. return decl;
  4982. }
  4983. public override void SetDecl(TokenDeclSDType decl)
  4984. {
  4985. this.decl = (TokenDeclSDTypeDelegate)decl;
  4986. }
  4987. /**
  4988. * @brief create a reference to a possibly anonymous delegate
  4989. * @param t = where the reference is being made in the source file
  4990. * @param retType = return type (TokenTypeVoid if void, never null)
  4991. * @param argTypes = script-visible argument types
  4992. * @param tokenScript = what script this is part of
  4993. */
  4994. public TokenTypeSDTypeDelegate(Token t, TokenType retType, TokenType[] argTypes, TokenScript tokenScript) : base(t)
  4995. {
  4996. TokenDeclSDTypeDelegate decldel;
  4997. // See if we already have a matching declared one cataloged.
  4998. int nArgs = argTypes.Length;
  4999. foreach(TokenDeclSDType decl in tokenScript.sdSrcTypesValues)
  5000. {
  5001. if(decl is TokenDeclSDTypeDelegate)
  5002. {
  5003. decldel = (TokenDeclSDTypeDelegate)decl;
  5004. TokenType rt = decldel.GetRetType();
  5005. TokenType[] ats = decldel.GetArgTypes();
  5006. if((rt.ToString() == retType.ToString()) && (ats.Length == nArgs))
  5007. {
  5008. for(int i = 0; i < nArgs; i++)
  5009. {
  5010. if(ats[i].ToString() != argTypes[i].ToString())
  5011. goto nomatch;
  5012. }
  5013. this.decl = decldel;
  5014. return;
  5015. }
  5016. }
  5017. nomatch:
  5018. ;
  5019. }
  5020. // No such luck, create a new anonymous declaration.
  5021. StringBuilder sb = new StringBuilder("$anondel$");
  5022. sb.Append(retType.ToString());
  5023. sb.Append("(");
  5024. bool first = true;
  5025. foreach(TokenType at in argTypes)
  5026. {
  5027. if(!first)
  5028. sb.Append(",");
  5029. sb.Append(at.ToString());
  5030. first = false;
  5031. }
  5032. sb.Append(")");
  5033. TokenName name = new TokenName(t, sb.ToString());
  5034. decldel = new TokenDeclSDTypeDelegate(name);
  5035. decldel.SetRetArgTypes(retType, argTypes);
  5036. tokenScript.sdSrcTypesAdd(name.val, decldel);
  5037. this.decl = decldel;
  5038. }
  5039. public override Type ToSysType()
  5040. {
  5041. return decl.GetSysType();
  5042. }
  5043. public override string ToString()
  5044. {
  5045. return decl.longName.val;
  5046. }
  5047. /**
  5048. * @brief Assign slots in the gblObjects[] array because we have to typecast out in any case.
  5049. * Likewise with the sdtcObjects[] array.
  5050. */
  5051. public override void AssignVarSlot(TokenDeclVar declVar, XMRInstArSizes ias)
  5052. {
  5053. declVar.vTableArray = iarObjectsFieldInfo;
  5054. declVar.vTableIndex = ias.iasObjects++;
  5055. }
  5056. /**
  5057. * @brief create delegate reference token for inline functions.
  5058. */
  5059. public TokenTypeSDTypeDelegate(TokenType retType, TokenType[] argTypes) : base(null)
  5060. {
  5061. this.decl = TokenDeclSDTypeDelegate.CreateInline(retType, argTypes);
  5062. }
  5063. // debugging
  5064. public override void DebString(StringBuilder sb)
  5065. {
  5066. sb.Append(decl.longName);
  5067. }
  5068. }
  5069. public class TokenTypeSDTypeInterface: TokenTypeSDType
  5070. {
  5071. private static readonly FieldInfo iarSDTIntfObjsFieldInfo = typeof(XMRInstArrays).GetField("iarSDTIntfObjs");
  5072. public TokenDeclSDTypeInterface decl;
  5073. public TokenTypeSDTypeInterface(Token t, TokenDeclSDTypeInterface decl) : base(t)
  5074. {
  5075. this.decl = decl;
  5076. }
  5077. public override TokenDeclSDType GetDecl()
  5078. {
  5079. return decl;
  5080. }
  5081. public override void SetDecl(TokenDeclSDType decl)
  5082. {
  5083. this.decl = (TokenDeclSDTypeInterface)decl;
  5084. }
  5085. public override string ToString()
  5086. {
  5087. return decl.longName.val;
  5088. }
  5089. public override Type ToSysType()
  5090. {
  5091. return typeof(Delegate[]);
  5092. }
  5093. /**
  5094. * @brief Assign slots in the gblSDTIntfObjs[] array
  5095. * Likewise with the sdtcSDTIntfObjs[] array.
  5096. */
  5097. public override void AssignVarSlot(TokenDeclVar declVar, XMRInstArSizes ias)
  5098. {
  5099. declVar.vTableArray = iarSDTIntfObjsFieldInfo;
  5100. declVar.vTableIndex = ias.iasSDTIntfObjs++;
  5101. }
  5102. // debugging
  5103. public override void DebString(StringBuilder sb)
  5104. {
  5105. sb.Append(decl.longName);
  5106. }
  5107. }
  5108. /**
  5109. * @brief function argument list declaration
  5110. */
  5111. public class TokenArgDecl: Token
  5112. {
  5113. public VarDict varDict = new VarDict(false);
  5114. public TokenArgDecl(Token original) : base(original) { }
  5115. public bool AddArg(TokenType type, TokenName name)
  5116. {
  5117. TokenDeclVar var = new TokenDeclVar(name, null, null);
  5118. var.name = name;
  5119. var.type = type;
  5120. var.vTableIndex = varDict.Count;
  5121. return varDict.AddEntry(var);
  5122. }
  5123. /**
  5124. * @brief Get an array of the argument types.
  5125. */
  5126. private TokenType[] _types;
  5127. public TokenType[] types
  5128. {
  5129. get
  5130. {
  5131. if(_types == null)
  5132. {
  5133. _types = new TokenType[varDict.Count];
  5134. foreach(TokenDeclVar var in varDict)
  5135. {
  5136. _types[var.vTableIndex] = var.type;
  5137. }
  5138. }
  5139. return _types;
  5140. }
  5141. }
  5142. /**
  5143. * @brief Access the arguments as an array of variables.
  5144. */
  5145. private TokenDeclVar[] _vars;
  5146. public TokenDeclVar[] vars
  5147. {
  5148. get
  5149. {
  5150. if(_vars == null)
  5151. {
  5152. _vars = new TokenDeclVar[varDict.Count];
  5153. foreach(TokenDeclVar var in varDict)
  5154. {
  5155. _vars[var.vTableIndex] = var;
  5156. }
  5157. }
  5158. return _vars;
  5159. }
  5160. }
  5161. /**
  5162. * @brief Get argument signature string, eg, "(list,vector,integer)"
  5163. */
  5164. private string argSig = null;
  5165. public string GetArgSig()
  5166. {
  5167. if(argSig == null)
  5168. {
  5169. argSig = ScriptCodeGen.ArgSigString(types);
  5170. }
  5171. return argSig;
  5172. }
  5173. }
  5174. /**
  5175. * @brief encapsulate a state declaration in a single token
  5176. */
  5177. public class TokenDeclState: Token
  5178. {
  5179. public TokenName name; // null for default state
  5180. public TokenStateBody body;
  5181. public TokenDeclState(Token original) : base(original) { }
  5182. public override void DebString(StringBuilder sb)
  5183. {
  5184. if(name == null)
  5185. {
  5186. sb.Append("default");
  5187. }
  5188. else
  5189. {
  5190. sb.Append("state ");
  5191. sb.Append(name);
  5192. }
  5193. body.DebString(sb);
  5194. }
  5195. }
  5196. /**
  5197. * @brief encapsulate the declaration of a field/function/method/property/variable.
  5198. */
  5199. public enum Triviality
  5200. { // function triviality: has no loops and doesn't call anything that has loops
  5201. // such a function does not need all the CheckRun() and stack serialization stuff
  5202. unknown, // function's Triviality unknown as of yet
  5203. // - it does not have any loops or backward gotos
  5204. // - nothing it calls is known to be complex
  5205. trivial, // function known to be trivial
  5206. // - it does not have any loops or backward gotos
  5207. // - everything it calls is known to be trivial
  5208. complex, // function known to be complex
  5209. // - it has loops or backward gotos
  5210. // - something it calls is known to be complex
  5211. analyzing // triviality is being analyzed (used to detect recursive loops)
  5212. };
  5213. public class TokenDeclVar: TokenStmt
  5214. {
  5215. public TokenName name; // vars: name; funcs: bare name, ie, no signature
  5216. public TokenRVal init; // vars: null if none; funcs: null
  5217. public bool constant; // vars: 'constant'; funcs: false
  5218. public uint sdtFlags; // SDT_<*> flags
  5219. public CompValu location; // used by codegen to keep track of location
  5220. public FieldInfo vTableArray;
  5221. public int vTableIndex = -1; // local vars: not used (-1)
  5222. // arg vars: index in the arg list
  5223. // global vars: which slot in gbl<Type>s[] array it is stored
  5224. // instance vars: which slot in inst<Types>s[] array it is stored
  5225. // static vars: which slot in gbl<Type>s[] array it is stored
  5226. // global funcs: not used (-1)
  5227. // virt funcs: which slot in vTable[] array it is stored
  5228. // instance func: not used (-1)
  5229. public TokenDeclVar getProp; // if property, function that reads value
  5230. public TokenDeclVar setProp; // if property, function that writes value
  5231. public TokenScript tokenScript; // what script this function is part of
  5232. public TokenDeclSDType sdtClass; // null: script global member
  5233. // else: member is part of this script-defined type
  5234. // function-only data:
  5235. public TokenType retType; // vars: null; funcs: TokenTypeVoid if void
  5236. public TokenArgDecl argDecl; // vars: null; funcs: argument list prototypes
  5237. public TokenStmtBlock body; // vars: null; funcs: statements (null iff abstract)
  5238. public Dictionary<string, TokenStmtLabel> labels = new Dictionary<string, TokenStmtLabel>();
  5239. // all labels defined in the function
  5240. public LinkedList<TokenDeclVar> localVars = new LinkedList<TokenDeclVar>();
  5241. // all local variables declared by this function
  5242. // - doesn't include argument variables
  5243. public TokenIntfImpl implements; // if script-defined type method, what interface method(s) this func implements
  5244. public TokenRValCall baseCtorCall; // if script-defined type constructor, call to base constructor, if any
  5245. public Triviality triviality = Triviality.unknown;
  5246. // vars: unknown (not used for any thing); funcs: unknown/trivial/complex
  5247. public LinkedList<TokenRValCall> unknownTrivialityCalls = new LinkedList<TokenRValCall>();
  5248. // reduction puts all calls here
  5249. // compilation sorts it all out
  5250. public ScriptObjWriter ilGen; // codegen stores emitted code here
  5251. /**
  5252. * @brief Set up a variable declaration token.
  5253. * @param original = original source token that triggered definition
  5254. * (for error messages)
  5255. * @param func = null: global variable
  5256. * else: local to the given function
  5257. */
  5258. public TokenDeclVar(Token original, TokenDeclVar func, TokenScript ts) : base(original)
  5259. {
  5260. if(func != null)
  5261. {
  5262. func.localVars.AddLast(this);
  5263. }
  5264. tokenScript = ts;
  5265. }
  5266. /**
  5267. * @brief Get/Set overall type
  5268. * For vars, this is the type of the location
  5269. * For funcs, this is the delegate type
  5270. */
  5271. private TokenType _type;
  5272. public TokenType type
  5273. {
  5274. get
  5275. {
  5276. if(_type == null)
  5277. {
  5278. GetDelType();
  5279. }
  5280. return _type;
  5281. }
  5282. set
  5283. {
  5284. _type = value;
  5285. }
  5286. }
  5287. /**
  5288. * @brief Full name: <fulltype>.<name>(<argsig>)
  5289. * (<argsig>) missing for fields/variables
  5290. * <fulltype>. missing for top-level functions/variables
  5291. */
  5292. public string fullName
  5293. {
  5294. get
  5295. {
  5296. if(sdtClass == null)
  5297. {
  5298. if(retType == null)
  5299. return name.val;
  5300. return funcNameSig.val;
  5301. }
  5302. string ln = sdtClass.longName.val;
  5303. if(retType == null)
  5304. return ln + "." + name.val;
  5305. return ln + "." + funcNameSig.val;
  5306. }
  5307. }
  5308. /**
  5309. * @brief See if reading or writing the variable is trivial.
  5310. * Note that for functions, this is reading the function itself,
  5311. * as in 'someDelegate = SomeFunction;', not calling it as such.
  5312. * The triviality of actually calling the function is IsFuncTrivial().
  5313. */
  5314. public bool IsVarTrivial(ScriptCodeGen scg)
  5315. {
  5316. // reading or writing a property involves a function call however
  5317. // so we need to check the triviality of the property functions
  5318. if((getProp != null) && !getProp.IsFuncTrivial(scg))
  5319. return false;
  5320. if((setProp != null) && !setProp.IsFuncTrivial(scg))
  5321. return false;
  5322. // otherwise for variables it is a trivial access
  5323. // and likewise for getting a delegate that points to a function
  5324. return true;
  5325. }
  5326. /***************************\
  5327. * FUNCTION-only methods *
  5328. \***************************/
  5329. private TokenName _funcNameSig; // vars: null; funcs: function name including argumet signature, eg, "PrintStuff(list,string)"
  5330. public TokenName funcNameSig
  5331. {
  5332. get
  5333. {
  5334. if(_funcNameSig == null)
  5335. {
  5336. if(argDecl == null)
  5337. return null;
  5338. _funcNameSig = new TokenName(name, name.val + argDecl.GetArgSig());
  5339. }
  5340. return _funcNameSig;
  5341. }
  5342. }
  5343. /**
  5344. * @brief The bare function name, ie, without any signature info
  5345. */
  5346. public string GetSimpleName()
  5347. {
  5348. return name.val;
  5349. }
  5350. /**
  5351. * @brief The function name as it appears in the object code,
  5352. * ie, script-defined type name if any,
  5353. * bare function name and argument signature,
  5354. * eg, "MyClass.PrintStuff(string)"
  5355. */
  5356. public string GetObjCodeName()
  5357. {
  5358. string objCodeName = "";
  5359. if(sdtClass != null)
  5360. {
  5361. objCodeName += sdtClass.longName.val + ".";
  5362. }
  5363. objCodeName += funcNameSig.val;
  5364. return objCodeName;
  5365. }
  5366. /**
  5367. * @brief Get delegate type.
  5368. * This is the function's script-visible type,
  5369. * It includes return type and all script-visible argument types.
  5370. * @returns null for vars; else delegate type for funcs
  5371. */
  5372. public TokenTypeSDTypeDelegate GetDelType()
  5373. {
  5374. if(argDecl == null)
  5375. return null;
  5376. if(_type == null)
  5377. {
  5378. if(tokenScript == null)
  5379. {
  5380. // used during startup to define inline function delegate types
  5381. _type = new TokenTypeSDTypeDelegate(retType, argDecl.types);
  5382. }
  5383. else
  5384. {
  5385. // used for normal script processing
  5386. _type = new TokenTypeSDTypeDelegate(this, retType, argDecl.types, tokenScript);
  5387. }
  5388. }
  5389. if(!(_type is TokenTypeSDTypeDelegate))
  5390. return null;
  5391. return (TokenTypeSDTypeDelegate)_type;
  5392. }
  5393. /**
  5394. * @brief See if the function's code itself is trivial or not.
  5395. * If it contains any loops (calls to CheckRun()), it is not trivial.
  5396. * If it calls anything that is not trivial, it is not trivial.
  5397. * Otherwise it is trivial.
  5398. */
  5399. public bool IsFuncTrivial(ScriptCodeGen scg)
  5400. {
  5401. // If not really a function, assume it's a delegate.
  5402. // And since we don't really know what functions it can point to,
  5403. // assume it can point to a non-trivial one.
  5404. if(retType == null)
  5405. return false;
  5406. // All virtual functions are non-trivial because although a particular
  5407. // one might be trivial, it might be overidden with a non-trivial one.
  5408. if((sdtFlags & (ScriptReduce.SDT_ABSTRACT | ScriptReduce.SDT_OVERRIDE |
  5409. ScriptReduce.SDT_VIRTUAL)) != 0)
  5410. {
  5411. return false;
  5412. }
  5413. // Check the triviality status of the function.
  5414. switch(triviality)
  5415. {
  5416. // Don't yet know if it is trivial.
  5417. // We know at this point it doesn't have any direct looping.
  5418. // But if it calls something that has loops, it isn't trivial.
  5419. // Otherwise it is trivial.
  5420. case Triviality.unknown:
  5421. {
  5422. // Mark that we are analyzing this function now. So if there are
  5423. // any recursive call loops, that will show that the function is
  5424. // non-trivial and the analysis will terminate at that point.
  5425. triviality = Triviality.analyzing;
  5426. // Check out everything else this function calls. If any say they
  5427. // aren't trivial, then we say this function isn't trivial.
  5428. foreach(TokenRValCall call in unknownTrivialityCalls)
  5429. {
  5430. if(!call.IsRValTrivial(scg, null))
  5431. {
  5432. triviality = Triviality.complex;
  5433. return false;
  5434. }
  5435. }
  5436. // All functions called by this function are trivial, and this
  5437. // function's code doesn't have any loops, so we can mark this
  5438. // function as being trivial.
  5439. triviality = Triviality.trivial;
  5440. return true;
  5441. }
  5442. // We already know that it is trivial.
  5443. case Triviality.trivial:
  5444. {
  5445. return true;
  5446. }
  5447. // We either know it is complex or are trying to analyze it already.
  5448. // If we are already analyzing it, it means it has a recursive loop
  5449. // and we assume those are non-trivial.
  5450. default:
  5451. return false;
  5452. }
  5453. }
  5454. // debugging
  5455. public override void DebString(StringBuilder sb)
  5456. {
  5457. DebStringSDTFlags(sb);
  5458. if(retType == null)
  5459. {
  5460. sb.Append(constant ? "constant" : type.ToString());
  5461. sb.Append(' ');
  5462. sb.Append(name.val);
  5463. if(init != null)
  5464. {
  5465. sb.Append(" = ");
  5466. init.DebString(sb);
  5467. }
  5468. sb.Append(';');
  5469. }
  5470. else
  5471. {
  5472. if(!(retType is TokenTypeVoid))
  5473. {
  5474. sb.Append(retType.ToString());
  5475. sb.Append(' ');
  5476. }
  5477. string namestr = name.val;
  5478. if(namestr == "$ctor")
  5479. namestr = "constructor";
  5480. sb.Append(namestr);
  5481. sb.Append(" (");
  5482. for(int i = 0; i < argDecl.vars.Length; i++)
  5483. {
  5484. if(i > 0)
  5485. sb.Append(", ");
  5486. sb.Append(argDecl.vars[i].type.ToString());
  5487. sb.Append(' ');
  5488. sb.Append(argDecl.vars[i].name.val);
  5489. }
  5490. sb.Append(')');
  5491. if(body == null)
  5492. sb.Append(';');
  5493. else
  5494. {
  5495. sb.Append(' ');
  5496. body.DebString(sb);
  5497. }
  5498. }
  5499. }
  5500. // debugging
  5501. // - used to output contents of a $globalvarinit(), $instfieldinit() or $statisfieldinit() function
  5502. // as a series of variable declaration statements with initial value assignments
  5503. // so we get the initial value assignments done in same order as specified in script
  5504. public void DebStringInitFields(StringBuilder sb)
  5505. {
  5506. if((retType == null) || !(retType is TokenTypeVoid))
  5507. throw new Exception("bad return type " + retType.GetType().Name);
  5508. if(argDecl.vars.Length != 0)
  5509. throw new Exception("has " + argDecl.vars.Length + " arg(s)");
  5510. for(Token stmt = body.statements; stmt != null; stmt = stmt.nextToken)
  5511. {
  5512. // Body of the function should all be arithmetic statements (not eg for loops, if statements etc).
  5513. TokenRVal rval = ((TokenStmtRVal)stmt).rVal;
  5514. // And the opcode should be a simple assignment operator.
  5515. TokenRValOpBin rvob = (TokenRValOpBin)rval;
  5516. if(!(rvob.opcode is TokenKwAssign))
  5517. throw new Exception("bad op type " + rvob.opcode.GetType().Name);
  5518. // Get field or variable being assigned to.
  5519. TokenDeclVar var = null;
  5520. TokenRVal left = rvob.rValLeft;
  5521. if(left is TokenLValIField)
  5522. {
  5523. TokenLValIField ifield = (TokenLValIField)left;
  5524. TokenRValThis zhis = (TokenRValThis)ifield.baseRVal;
  5525. TokenDeclSDTypeClass sdt = zhis.sdtClass;
  5526. var = sdt.members.FindExact(ifield.fieldName.val, null);
  5527. }
  5528. if(left is TokenLValName)
  5529. {
  5530. TokenLValName global = (TokenLValName)left;
  5531. var = global.stack.FindExact(global.name.val, null);
  5532. }
  5533. if(left is TokenLValSField)
  5534. {
  5535. TokenLValSField sfield = (TokenLValSField)left;
  5536. TokenTypeSDTypeClass sdtc = (TokenTypeSDTypeClass)sfield.baseType;
  5537. TokenDeclSDTypeClass decl = sdtc.decl;
  5538. var = decl.members.FindExact(sfield.fieldName.val, null);
  5539. }
  5540. if(var == null)
  5541. throw new Exception("unknown var type " + left.GetType().Name);
  5542. // Output flags, type name and bare variable name.
  5543. // This should look like a declaration in the 'sb'
  5544. // as it is not enclosed in a function.
  5545. var.DebStringSDTFlags(sb);
  5546. var.type.DebString(sb);
  5547. sb.Append(' ');
  5548. sb.Append(var.name.val);
  5549. // Maybe it has a non-default initialization value.
  5550. if((var.init != null) && !(var.init is TokenRValInitDef))
  5551. {
  5552. sb.Append(" = ");
  5553. var.init.DebString(sb);
  5554. }
  5555. // End of declaration statement.
  5556. sb.Append(';');
  5557. }
  5558. }
  5559. private void DebStringSDTFlags(StringBuilder sb)
  5560. {
  5561. if((sdtFlags & ScriptReduce.SDT_PRIVATE) != 0)
  5562. sb.Append("private ");
  5563. if((sdtFlags & ScriptReduce.SDT_PROTECTED) != 0)
  5564. sb.Append("protected ");
  5565. if((sdtFlags & ScriptReduce.SDT_PUBLIC) != 0)
  5566. sb.Append("public ");
  5567. if((sdtFlags & ScriptReduce.SDT_ABSTRACT) != 0)
  5568. sb.Append("abstract ");
  5569. if((sdtFlags & ScriptReduce.SDT_FINAL) != 0)
  5570. sb.Append("final ");
  5571. if((sdtFlags & ScriptReduce.SDT_NEW) != 0)
  5572. sb.Append("new ");
  5573. if((sdtFlags & ScriptReduce.SDT_OVERRIDE) != 0)
  5574. sb.Append("override ");
  5575. if((sdtFlags & ScriptReduce.SDT_STATIC) != 0)
  5576. sb.Append("static ");
  5577. if((sdtFlags & ScriptReduce.SDT_VIRTUAL) != 0)
  5578. sb.Append("virtual ");
  5579. }
  5580. }
  5581. /**
  5582. * @brief Indicates an interface type.method that is implemented by the function
  5583. */
  5584. public class TokenIntfImpl: Token
  5585. {
  5586. public TokenTypeSDTypeInterface intfType;
  5587. public TokenName methName; // simple name, no arg signature
  5588. public TokenIntfImpl(TokenTypeSDTypeInterface intfType, TokenName methName) : base(intfType)
  5589. {
  5590. this.intfType = intfType;
  5591. this.methName = methName;
  5592. }
  5593. }
  5594. /**
  5595. * @brief any expression that can go on left side of an "="
  5596. */
  5597. public abstract class TokenLVal: TokenRVal
  5598. {
  5599. public TokenLVal(Token original) : base(original) { }
  5600. public abstract override TokenType GetRValType(ScriptCodeGen scg, TokenType[] argsig);
  5601. public abstract override bool IsRValTrivial(ScriptCodeGen scg, TokenType[] argsig);
  5602. }
  5603. /**
  5604. * @brief an element of an array is an L-value
  5605. */
  5606. public class TokenLValArEle: TokenLVal
  5607. {
  5608. public TokenRVal baseRVal;
  5609. public TokenRVal subRVal;
  5610. public TokenLValArEle(Token original) : base(original) { }
  5611. public override TokenType GetRValType(ScriptCodeGen scg, TokenType[] argsig)
  5612. {
  5613. TokenType baseType = baseRVal.GetRValType(scg, null);
  5614. // Maybe referencing element of a fixed-dimension array.
  5615. if((baseType is TokenTypeSDTypeClass) && (((TokenTypeSDTypeClass)baseType).decl.arrayOfType != null))
  5616. {
  5617. return ((TokenTypeSDTypeClass)baseType).decl.arrayOfType;
  5618. }
  5619. // Maybe referencing $idxprop property of script-defined class or interface.
  5620. if(baseType is TokenTypeSDTypeClass)
  5621. {
  5622. TokenDeclSDTypeClass sdtDecl = ((TokenTypeSDTypeClass)baseType).decl;
  5623. TokenDeclVar idxProp = scg.FindSingleMember(sdtDecl.members, new TokenName(this, "$idxprop"), null);
  5624. if(idxProp != null)
  5625. return idxProp.type;
  5626. }
  5627. if(baseType is TokenTypeSDTypeInterface)
  5628. {
  5629. TokenDeclSDTypeInterface sdtDecl = ((TokenTypeSDTypeInterface)baseType).decl;
  5630. TokenDeclVar idxProp = sdtDecl.FindIFaceMember(scg, new TokenName(this, "$idxprop"), null, out sdtDecl);
  5631. if(idxProp != null)
  5632. return idxProp.type;
  5633. }
  5634. // Maybe referencing single character of a string.
  5635. if((baseType is TokenTypeKey) || (baseType is TokenTypeStr))
  5636. {
  5637. return new TokenTypeChar(this);
  5638. }
  5639. // Assume XMR_Array element or extracting element from list.
  5640. if((baseType is TokenTypeArray) || (baseType is TokenTypeList))
  5641. {
  5642. return new TokenTypeObject(this);
  5643. }
  5644. scg.ErrorMsg(this, "unknown array reference");
  5645. return new TokenTypeVoid(this);
  5646. }
  5647. public override bool IsRValTrivial(ScriptCodeGen scg, TokenType[] argsig)
  5648. {
  5649. return baseRVal.IsRValTrivial(scg, null) && subRVal.IsRValTrivial(scg, null);
  5650. }
  5651. public override void DebString(StringBuilder sb)
  5652. {
  5653. baseRVal.DebString(sb);
  5654. sb.Append('[');
  5655. subRVal.DebString(sb);
  5656. sb.Append(']');
  5657. }
  5658. }
  5659. /**
  5660. * @brief 'base.' being used to reference a field/method of the extended class.
  5661. */
  5662. public class TokenLValBaseField: TokenLVal
  5663. {
  5664. public TokenName fieldName;
  5665. private TokenDeclSDTypeClass thisClass;
  5666. public TokenLValBaseField(Token original, TokenName fieldName, TokenDeclSDTypeClass thisClass) : base(original)
  5667. {
  5668. this.fieldName = fieldName;
  5669. this.thisClass = thisClass;
  5670. }
  5671. public override TokenType GetRValType(ScriptCodeGen scg, TokenType[] argsig)
  5672. {
  5673. TokenDeclVar var = scg.FindThisMember(thisClass.extends, fieldName, argsig);
  5674. if(var != null)
  5675. return var.type;
  5676. scg.ErrorMsg(fieldName, "unknown member of " + thisClass.extends.ToString());
  5677. return new TokenTypeVoid(fieldName);
  5678. }
  5679. public override bool IsRValTrivial(ScriptCodeGen scg, TokenType[] argsig)
  5680. {
  5681. TokenDeclVar var = scg.FindThisMember(thisClass.extends, fieldName, argsig);
  5682. return (var != null) && var.IsVarTrivial(scg);
  5683. }
  5684. public override bool IsCallTrivial(ScriptCodeGen scg, TokenType[] argsig)
  5685. {
  5686. TokenDeclVar var = scg.FindThisMember(thisClass.extends, fieldName, argsig);
  5687. return (var != null) && var.IsFuncTrivial(scg);
  5688. }
  5689. }
  5690. /**
  5691. * @brief a field within an struct is an L-value
  5692. */
  5693. public class TokenLValIField: TokenLVal
  5694. {
  5695. public TokenRVal baseRVal;
  5696. public TokenName fieldName;
  5697. public TokenLValIField(Token original) : base(original) { }
  5698. public override TokenType GetRValType(ScriptCodeGen scg, TokenType[] argsig)
  5699. {
  5700. TokenType baseType = baseRVal.GetRValType(scg, null);
  5701. if(baseType is TokenTypeSDTypeClass)
  5702. {
  5703. TokenDeclVar var = scg.FindThisMember((TokenTypeSDTypeClass)baseType, fieldName, argsig);
  5704. if(var != null)
  5705. return var.type;
  5706. }
  5707. if(baseType is TokenTypeSDTypeInterface)
  5708. {
  5709. TokenDeclSDTypeInterface baseIntfDecl = ((TokenTypeSDTypeInterface)baseType).decl;
  5710. TokenDeclVar var = baseIntfDecl.FindIFaceMember(scg, fieldName, argsig, out baseIntfDecl);
  5711. if(var != null)
  5712. return var.type;
  5713. }
  5714. if(baseType is TokenTypeArray)
  5715. {
  5716. return XMR_Array.GetRValType(fieldName);
  5717. }
  5718. if((baseType is TokenTypeRot) || (baseType is TokenTypeVec))
  5719. {
  5720. return new TokenTypeFloat(fieldName);
  5721. }
  5722. scg.ErrorMsg(fieldName, "unknown member of " + baseType.ToString());
  5723. return new TokenTypeVoid(fieldName);
  5724. }
  5725. public override bool IsRValTrivial(ScriptCodeGen scg, TokenType[] argsig)
  5726. {
  5727. // If getting pointer to instance isn't trivial, then accessing the member isn't trivial either.
  5728. if(!baseRVal.IsRValTrivial(scg, null))
  5729. return false;
  5730. // Accessing a member of a class depends on the member.
  5731. // In the case of a method, this is accessing it as a delegate, not calling it, and
  5732. // argsig simply serves as selecting which of possibly overloaded methods to select.
  5733. // The case of accessing a property, however, depends on the property implementation,
  5734. // as there could be looping inside the property code.
  5735. TokenType baseType = baseRVal.GetRValType(scg, null);
  5736. if(baseType is TokenTypeSDTypeClass)
  5737. {
  5738. TokenDeclVar var = scg.FindThisMember((TokenTypeSDTypeClass)baseType, fieldName, argsig);
  5739. return (var != null) && var.IsVarTrivial(scg);
  5740. }
  5741. // Accessing the members of anything else (arrays, rotations, vectors) is always trivial.
  5742. return true;
  5743. }
  5744. /**
  5745. * @brief Check to see if the case of calling an instance method of some object is trivial.
  5746. * @param scg = script making the call
  5747. * @param argsig = argument types of the call (used to select among overloads)
  5748. * @returns true iff we can tell at compile time that the call will always call a trivial method
  5749. */
  5750. public override bool IsCallTrivial(ScriptCodeGen scg, TokenType[] argsig)
  5751. {
  5752. // If getting pointer to instance isn't trivial, then calling the method isn't trivial either.
  5753. if(!baseRVal.IsRValTrivial(scg, null))
  5754. return false;
  5755. // Calling a method of a class depends on the method.
  5756. TokenType baseType = baseRVal.GetRValType(scg, null);
  5757. if(baseType is TokenTypeSDTypeClass)
  5758. {
  5759. TokenDeclVar var = scg.FindThisMember((TokenTypeSDTypeClass)baseType, fieldName, argsig);
  5760. return (var != null) && var.IsFuncTrivial(scg);
  5761. }
  5762. // Calling via a pointer to an interface instance is never trivial.
  5763. // (It is really a pointer to an array of delegates).
  5764. // We can't tell for this call site whether the actual method being called is trivial or not,
  5765. // so we have to assume it isn't.
  5766. // ??? We could theoretically check to see if *all* implementations of this method of
  5767. // this interface are trivial, then we could conclude that this call is trivial.
  5768. if(baseType is TokenTypeSDTypeInterface)
  5769. return false;
  5770. // Calling a method of anything else (arrays, rotations, vectors) is always trivial.
  5771. // Even methods of delegates, such as ".GetArgTypes()" that we may someday do is trivial.
  5772. return true;
  5773. }
  5774. // debugging
  5775. public override void DebString(StringBuilder sb)
  5776. {
  5777. baseRVal.DebString(sb);
  5778. sb.Append('.');
  5779. sb.Append(fieldName.val);
  5780. }
  5781. }
  5782. /**
  5783. * @brief a name is being used as an L-value
  5784. */
  5785. public class TokenLValName: TokenLVal
  5786. {
  5787. public TokenName name;
  5788. public VarDict stack;
  5789. public TokenLValName(TokenName name, VarDict stack) : base(name)
  5790. {
  5791. // Save name of variable/method/function/field.
  5792. this.name = name;
  5793. // Save where in the stack it can be looked up.
  5794. // If the current stack is for locals, do not allow forward references.
  5795. // this allows idiocy like:
  5796. // list buttons = [ 1, 2, 3 ];
  5797. // x () {
  5798. // list buttons = llList2List (buttons, 0, 1);
  5799. // llOwnerSay (llList2CSV (buttons));
  5800. // }
  5801. // If it is not locals, allow forward references.
  5802. // this allows function X() to call Y() and Y() to call X().
  5803. this.stack = stack.FreezeLocals();
  5804. }
  5805. public override TokenType GetRValType(ScriptCodeGen scg, TokenType[] argsig)
  5806. {
  5807. TokenDeclVar var = scg.FindNamedVar(this, argsig);
  5808. if(var != null)
  5809. return var.type;
  5810. scg.ErrorMsg(name, "undefined name " + name.val + ScriptCodeGen.ArgSigString(argsig));
  5811. return new TokenTypeVoid(name);
  5812. }
  5813. public override bool IsRValTrivial(ScriptCodeGen scg, TokenType[] argsig)
  5814. {
  5815. TokenDeclVar var = scg.FindNamedVar(this, argsig);
  5816. return (var != null) && var.IsVarTrivial(scg);
  5817. }
  5818. /**
  5819. * @brief Check to see if the case of calling a global method is trivial.
  5820. * @param scg = script making the call
  5821. * @param argsig = argument types of the call (used to select among overloads)
  5822. * @returns true iff we can tell at compile time that the call will always call a trivial method
  5823. */
  5824. public override bool IsCallTrivial(ScriptCodeGen scg, TokenType[] argsig)
  5825. {
  5826. TokenDeclVar var = scg.FindNamedVar(this, argsig);
  5827. return (var != null) && var.IsFuncTrivial(scg);
  5828. }
  5829. // debugging
  5830. public override void DebString(StringBuilder sb)
  5831. {
  5832. sb.Append(name.val);
  5833. }
  5834. }
  5835. /**
  5836. * @brief a static field within a struct is an L-value
  5837. */
  5838. public class TokenLValSField: TokenLVal
  5839. {
  5840. public TokenType baseType;
  5841. public TokenName fieldName;
  5842. public TokenLValSField(Token original) : base(original) { }
  5843. public override TokenType GetRValType(ScriptCodeGen scg, TokenType[] argsig)
  5844. {
  5845. if(baseType is TokenTypeSDTypeClass)
  5846. {
  5847. TokenDeclVar var = scg.FindThisMember((TokenTypeSDTypeClass)baseType, fieldName, argsig);
  5848. if(var != null)
  5849. return var.type;
  5850. }
  5851. scg.ErrorMsg(fieldName, "unknown member of " + baseType.ToString());
  5852. return new TokenTypeVoid(fieldName);
  5853. }
  5854. public override bool IsRValTrivial(ScriptCodeGen scg, TokenType[] argsig)
  5855. {
  5856. // Accessing a member of a class depends on the member.
  5857. // In the case of a method, this is accessing it as a delegate, not calling it, and
  5858. // argsig simply serves as selecting which of possibly overloaded methods to select.
  5859. // The case of accessing a property, however, depends on the property implementation,
  5860. // as there could be looping inside the property code.
  5861. if(baseType is TokenTypeSDTypeClass)
  5862. {
  5863. TokenDeclVar var = scg.FindThisMember((TokenTypeSDTypeClass)baseType, fieldName, argsig);
  5864. return (var != null) && var.IsVarTrivial(scg);
  5865. }
  5866. // Accessing the fields/methods/properties of anything else (arrays, rotations, vectors) is always trivial.
  5867. return true;
  5868. }
  5869. /**
  5870. * @brief Check to see if the case of calling a class' static method is trivial.
  5871. * @param scg = script making the call
  5872. * @param argsig = argument types of the call (used to select among overloads)
  5873. * @returns true iff we can tell at compile time that the call will always call a trivial method
  5874. */
  5875. public override bool IsCallTrivial(ScriptCodeGen scg, TokenType[] argsig)
  5876. {
  5877. // Calling a static method of a class depends on the method.
  5878. if(baseType is TokenTypeSDTypeClass)
  5879. {
  5880. TokenDeclVar var = scg.FindThisMember((TokenTypeSDTypeClass)baseType, fieldName, argsig);
  5881. return (var != null) && var.IsFuncTrivial(scg);
  5882. }
  5883. // Calling a static method of anything else (arrays, rotations, vectors) is always trivial.
  5884. return true;
  5885. }
  5886. public override void DebString(StringBuilder sb)
  5887. {
  5888. if(fieldName.val == "$new")
  5889. {
  5890. sb.Append("new ");
  5891. baseType.DebString(sb);
  5892. }
  5893. else
  5894. {
  5895. baseType.DebString(sb);
  5896. sb.Append('.');
  5897. fieldName.DebString(sb);
  5898. }
  5899. }
  5900. }
  5901. /**
  5902. * @brief any expression that can go on right side of "="
  5903. */
  5904. public delegate TokenRVal TCCLookup(TokenRVal rVal, ref bool didOne);
  5905. public abstract class TokenRVal: Token
  5906. {
  5907. public TokenRVal(Token original) : base(original) { }
  5908. /**
  5909. * @brief Tell us the type of the expression.
  5910. */
  5911. public abstract TokenType GetRValType(ScriptCodeGen scg, TokenType[] argsig);
  5912. /**
  5913. * @brief Tell us if reading and writing the value is trivial.
  5914. *
  5915. * @param scg = script code generator of script making the access
  5916. * @param argsig = argument types of the call (used to select among overloads)
  5917. * @returns true: we can tell at compile time that reading/writing this location
  5918. * will always be trivial (no looping or CheckRun() calls possible).
  5919. * false: otherwise
  5920. */
  5921. public abstract bool IsRValTrivial(ScriptCodeGen scg, TokenType[] argsig);
  5922. /**
  5923. * @brief Tell us if calling the method is trivial.
  5924. *
  5925. * This is the default implementation that returns false.
  5926. * It is only used if the location is holding a delegate
  5927. * and the method that the delegate is pointing to is being
  5928. * called. Since we can't tell if the actual runtime method
  5929. * is trivial or not, we assume it isn't.
  5930. *
  5931. * For the more usual ways of calling functions, see the
  5932. * various overrides of IsCallTrivial().
  5933. *
  5934. * @param scg = script code generator of script making the call
  5935. * @param argsig = argument types of the call (used to select among overloads)
  5936. * @returns true: we can tell at compile time that this call will always
  5937. * be to a trivial function/method (no looping or CheckRun()
  5938. * calls possible).
  5939. * false: otherwise
  5940. */
  5941. public virtual bool IsCallTrivial(ScriptCodeGen scg, TokenType[] argsig)
  5942. {
  5943. return false;
  5944. }
  5945. /**
  5946. * @brief If the result of the expression is a constant,
  5947. * create a TokenRValConst equivalent, set didOne, and return that.
  5948. * Otherwise, just return the original without changing didOne.
  5949. */
  5950. public virtual TokenRVal TryComputeConstant(TCCLookup lookup, ref bool didOne)
  5951. {
  5952. return lookup(this, ref didOne);
  5953. }
  5954. }
  5955. /**
  5956. * @brief a postfix operator and corresponding L-value
  5957. */
  5958. public class TokenRValAsnPost: TokenRVal
  5959. {
  5960. public TokenLVal lVal;
  5961. public Token postfix;
  5962. public TokenRValAsnPost(Token original) : base(original) { }
  5963. public override TokenType GetRValType(ScriptCodeGen scg, TokenType[] argsig)
  5964. {
  5965. return lVal.GetRValType(scg, argsig);
  5966. }
  5967. public override bool IsRValTrivial(ScriptCodeGen scg, TokenType[] argsig)
  5968. {
  5969. return lVal.IsRValTrivial(scg, null);
  5970. }
  5971. public override void DebString(StringBuilder sb)
  5972. {
  5973. lVal.DebString(sb);
  5974. sb.Append(' ');
  5975. postfix.DebString(sb);
  5976. }
  5977. }
  5978. /**
  5979. * @brief a prefix operator and corresponding L-value
  5980. */
  5981. public class TokenRValAsnPre: TokenRVal
  5982. {
  5983. public Token prefix;
  5984. public TokenLVal lVal;
  5985. public TokenRValAsnPre(Token original) : base(original) { }
  5986. public override TokenType GetRValType(ScriptCodeGen scg, TokenType[] argsig)
  5987. {
  5988. return lVal.GetRValType(scg, argsig);
  5989. }
  5990. public override bool IsRValTrivial(ScriptCodeGen scg, TokenType[] argsig)
  5991. {
  5992. return lVal.IsRValTrivial(scg, null);
  5993. }
  5994. public override void DebString(StringBuilder sb)
  5995. {
  5996. prefix.DebString(sb);
  5997. sb.Append(' ');
  5998. lVal.DebString(sb);
  5999. }
  6000. }
  6001. /**
  6002. * @brief calling a function or method, ie, may have side-effects
  6003. */
  6004. public class TokenRValCall: TokenRVal
  6005. {
  6006. public TokenRVal meth; // points to the function to be called
  6007. // - might be a reference to a global function (TokenLValName)
  6008. // - or an instance method of a class (TokenLValIField)
  6009. // - or a static method of a class (TokenLValSField)
  6010. // - or a delegate stored in a variable (assumption for anything else)
  6011. public TokenRVal args; // null-terminated TokenRVal list
  6012. public int nArgs; // number of elements in args
  6013. public TokenRValCall(Token original) : base(original) { }
  6014. private TokenType[] myArgSig;
  6015. /**
  6016. * @brief The type of a call is the type of the return value.
  6017. */
  6018. public override TokenType GetRValType(ScriptCodeGen scg, TokenType[] argsig)
  6019. {
  6020. // Build type signature so we select correct overloaded function.
  6021. if(myArgSig == null)
  6022. {
  6023. myArgSig = new TokenType[nArgs];
  6024. int i = 0;
  6025. for(Token t = args; t != null; t = t.nextToken)
  6026. {
  6027. myArgSig[i++] = ((TokenRVal)t).GetRValType(scg, null);
  6028. }
  6029. }
  6030. // Get the type of the method itself. This should get us a delegate type.
  6031. TokenType delType = meth.GetRValType(scg, myArgSig);
  6032. if(!(delType is TokenTypeSDTypeDelegate))
  6033. {
  6034. scg.ErrorMsg(meth, "must be function or method");
  6035. return new TokenTypeVoid(meth);
  6036. }
  6037. // Get the return type from the delegate type.
  6038. return ((TokenTypeSDTypeDelegate)delType).decl.GetRetType();
  6039. }
  6040. /**
  6041. * @brief See if the call to the function/method is trivial.
  6042. * It is trivial if all the argument computations are trivial and
  6043. * the function is not being called via virtual table or delegate
  6044. * and the function body is trivial.
  6045. */
  6046. public override bool IsRValTrivial(ScriptCodeGen scg, TokenType[] argsig)
  6047. {
  6048. // Build type signature so we select correct overloaded function.
  6049. if(myArgSig == null)
  6050. {
  6051. myArgSig = new TokenType[nArgs];
  6052. int i = 0;
  6053. for(Token t = args; t != null; t = t.nextToken)
  6054. {
  6055. myArgSig[i++] = ((TokenRVal)t).GetRValType(scg, null);
  6056. }
  6057. }
  6058. // Make sure all arguments can be computed trivially.
  6059. for(Token t = args; t != null; t = t.nextToken)
  6060. {
  6061. if(!((TokenRVal)t).IsRValTrivial(scg, null))
  6062. return false;
  6063. }
  6064. // See if the function call itself and the function body are trivial.
  6065. return meth.IsCallTrivial(scg, myArgSig);
  6066. }
  6067. // debugging
  6068. public override void DebString(StringBuilder sb)
  6069. {
  6070. meth.DebString(sb);
  6071. sb.Append(" (");
  6072. bool first = true;
  6073. for(Token t = args; t != null; t = t.nextToken)
  6074. {
  6075. if(!first)
  6076. sb.Append(", ");
  6077. t.DebString(sb);
  6078. first = false;
  6079. }
  6080. sb.Append(")");
  6081. }
  6082. }
  6083. /**
  6084. * @brief encapsulates a typecast, ie, (type)
  6085. */
  6086. public class TokenRValCast: TokenRVal
  6087. {
  6088. public TokenType castTo;
  6089. public TokenRVal rVal;
  6090. public TokenRValCast(TokenType type, TokenRVal value) : base(type)
  6091. {
  6092. castTo = type;
  6093. rVal = value;
  6094. }
  6095. public override TokenType GetRValType(ScriptCodeGen scg, TokenType[] argsig)
  6096. {
  6097. return castTo;
  6098. }
  6099. public override bool IsRValTrivial(ScriptCodeGen scg, TokenType[] argsig)
  6100. {
  6101. argsig = null;
  6102. if(castTo is TokenTypeSDTypeDelegate)
  6103. {
  6104. argsig = ((TokenTypeSDTypeDelegate)castTo).decl.GetArgTypes();
  6105. }
  6106. return rVal.IsRValTrivial(scg, argsig);
  6107. }
  6108. /**
  6109. * @brief If operand is constant, maybe we can say the whole thing is a constant.
  6110. */
  6111. public override TokenRVal TryComputeConstant(TCCLookup lookup, ref bool didOne)
  6112. {
  6113. rVal = rVal.TryComputeConstant(lookup, ref didOne);
  6114. if(rVal is TokenRValConst)
  6115. {
  6116. try
  6117. {
  6118. object val = ((TokenRValConst)rVal).val;
  6119. object nval = null;
  6120. if(castTo is TokenTypeChar)
  6121. {
  6122. if(val is char)
  6123. return rVal;
  6124. if(val is int)
  6125. nval = (char)(int)val;
  6126. }
  6127. if(castTo is TokenTypeFloat)
  6128. {
  6129. if(val is double)
  6130. return rVal;
  6131. if(val is int)
  6132. nval = (double)(int)val;
  6133. if(val is string)
  6134. nval = new LSL_Float((string)val).value;
  6135. }
  6136. if(castTo is TokenTypeInt)
  6137. {
  6138. if(val is int)
  6139. return rVal;
  6140. if(val is char)
  6141. nval = (int)(char)val;
  6142. if(val is double)
  6143. nval = (int)(double)val;
  6144. if(val is string)
  6145. nval = new LSL_Integer((string)val).value;
  6146. }
  6147. if(castTo is TokenTypeRot)
  6148. {
  6149. if(val is LSL_Rotation)
  6150. return rVal;
  6151. if(val is string)
  6152. nval = new LSL_Rotation((string)val);
  6153. }
  6154. if((castTo is TokenTypeKey) || (castTo is TokenTypeStr))
  6155. {
  6156. if(val is string)
  6157. nval = val; // in case of key/string conversion
  6158. if(val is char)
  6159. nval = TypeCast.CharToString((char)val);
  6160. if(val is double)
  6161. nval = TypeCast.FloatToString((double)val);
  6162. if(val is int)
  6163. nval = TypeCast.IntegerToString((int)val);
  6164. if(val is LSL_Rotation)
  6165. nval = TypeCast.RotationToString((LSL_Rotation)val);
  6166. if(val is LSL_Vector)
  6167. nval = TypeCast.VectorToString((LSL_Vector)val);
  6168. }
  6169. if(castTo is TokenTypeVec)
  6170. {
  6171. if(val is LSL_Vector)
  6172. return rVal;
  6173. if(val is string)
  6174. nval = new LSL_Vector((string)val);
  6175. }
  6176. if(nval != null)
  6177. {
  6178. TokenRVal rValConst = new TokenRValConst(castTo, nval);
  6179. didOne = true;
  6180. return rValConst;
  6181. }
  6182. }
  6183. catch
  6184. {
  6185. }
  6186. }
  6187. return this;
  6188. }
  6189. public override void DebString(StringBuilder sb)
  6190. {
  6191. sb.Append('(');
  6192. castTo.DebString(sb);
  6193. sb.Append(')');
  6194. rVal.DebString(sb);
  6195. }
  6196. }
  6197. /**
  6198. * @brief Encapsulate a conditional expression:
  6199. * <condExpr> ? <trueExpr> : <falseExpr>
  6200. */
  6201. public class TokenRValCondExpr: TokenRVal
  6202. {
  6203. public TokenRVal condExpr;
  6204. public TokenRVal trueExpr;
  6205. public TokenRVal falseExpr;
  6206. public TokenRValCondExpr(Token original) : base(original)
  6207. {
  6208. }
  6209. public override TokenType GetRValType(ScriptCodeGen scg, TokenType[] argsig)
  6210. {
  6211. TokenType trueType = trueExpr.GetRValType(scg, argsig);
  6212. TokenType falseType = falseExpr.GetRValType(scg, argsig);
  6213. if(trueType.ToString() != falseType.ToString())
  6214. {
  6215. scg.ErrorMsg(condExpr, "true & false expr types don't match");
  6216. }
  6217. return trueType;
  6218. }
  6219. public override bool IsRValTrivial(ScriptCodeGen scg, TokenType[] argsig)
  6220. {
  6221. return condExpr.IsRValTrivial(scg, null) &&
  6222. trueExpr.IsRValTrivial(scg, argsig) &&
  6223. falseExpr.IsRValTrivial(scg, argsig);
  6224. }
  6225. /**
  6226. * @brief If condition is constant, then the whole expression is constant
  6227. * iff the corresponding trueExpr or falseExpr is constant.
  6228. */
  6229. public override TokenRVal TryComputeConstant(TCCLookup lookup, ref bool didOne)
  6230. {
  6231. TokenRVal rValCond = condExpr.TryComputeConstant(lookup, ref didOne);
  6232. if(rValCond is TokenRValConst)
  6233. {
  6234. didOne = true;
  6235. bool isTrue = ((TokenRValConst)rValCond).IsConstBoolTrue();
  6236. return (isTrue ? trueExpr : falseExpr).TryComputeConstant(lookup, ref didOne);
  6237. }
  6238. return this;
  6239. }
  6240. // debugging
  6241. public override void DebString(StringBuilder sb)
  6242. {
  6243. condExpr.DebString(sb);
  6244. sb.Append(" ? ");
  6245. trueExpr.DebString(sb);
  6246. sb.Append(" : ");
  6247. falseExpr.DebString(sb);
  6248. }
  6249. }
  6250. /**
  6251. * @brief all constants supposed to end up here
  6252. */
  6253. public enum TokenRValConstType: byte { CHAR = 0, FLOAT = 1, INT = 2, KEY = 3, STRING = 4 };
  6254. public class TokenRValConst: TokenRVal
  6255. {
  6256. public object val; // always a system type (char, int, double, string), never LSL-wrapped
  6257. public TokenRValConstType type;
  6258. public TokenType tokType;
  6259. public TokenRValConst(Token original, object value) : base(original)
  6260. {
  6261. val = value;
  6262. TokenType tt = null;
  6263. if(val is char)
  6264. {
  6265. type = TokenRValConstType.CHAR;
  6266. tt = new TokenTypeChar(this);
  6267. }
  6268. else if(val is int)
  6269. {
  6270. type = TokenRValConstType.INT;
  6271. tt = new TokenTypeInt(this);
  6272. }
  6273. else if(val is double)
  6274. {
  6275. type = TokenRValConstType.FLOAT;
  6276. tt = new TokenTypeFloat(this);
  6277. }
  6278. else if(val is string)
  6279. {
  6280. type = TokenRValConstType.STRING;
  6281. tt = new TokenTypeStr(this);
  6282. }
  6283. else
  6284. {
  6285. throw new Exception("invalid constant type " + val.GetType());
  6286. }
  6287. tokType = (original is TokenType) ? (TokenType)original : tt;
  6288. if(tokType is TokenTypeKey)
  6289. {
  6290. type = TokenRValConstType.KEY;
  6291. }
  6292. }
  6293. public override TokenType GetRValType(ScriptCodeGen scg, TokenType[] argsig)
  6294. {
  6295. return tokType;
  6296. }
  6297. public override bool IsRValTrivial(ScriptCodeGen scg, TokenType[] argsig)
  6298. {
  6299. return true;
  6300. }
  6301. public CompValu GetCompValu()
  6302. {
  6303. switch(type)
  6304. {
  6305. case TokenRValConstType.CHAR:
  6306. {
  6307. return new CompValuChar(tokType, (char)val);
  6308. }
  6309. case TokenRValConstType.FLOAT:
  6310. {
  6311. return new CompValuFloat(tokType, (double)val);
  6312. }
  6313. case TokenRValConstType.INT:
  6314. {
  6315. return new CompValuInteger(tokType, (int)val);
  6316. }
  6317. case TokenRValConstType.KEY:
  6318. case TokenRValConstType.STRING:
  6319. {
  6320. return new CompValuString(tokType, (string)val);
  6321. }
  6322. default:
  6323. throw new Exception("unknown type");
  6324. }
  6325. }
  6326. public override TokenRVal TryComputeConstant(TCCLookup lookup, ref bool didOne)
  6327. {
  6328. // gotta end somewhere
  6329. return this;
  6330. }
  6331. public bool IsConstBoolTrue()
  6332. {
  6333. switch(type)
  6334. {
  6335. case TokenRValConstType.CHAR:
  6336. {
  6337. return (char)val != 0;
  6338. }
  6339. case TokenRValConstType.FLOAT:
  6340. {
  6341. return (double)val != 0;
  6342. }
  6343. case TokenRValConstType.INT:
  6344. {
  6345. return (int)val != 0;
  6346. }
  6347. case TokenRValConstType.KEY:
  6348. {
  6349. return (string)val != "" && (string)val != ScriptBaseClass.NULL_KEY;
  6350. }
  6351. case TokenRValConstType.STRING:
  6352. {
  6353. return (string)val != "";
  6354. }
  6355. default:
  6356. throw new Exception("unknown type");
  6357. }
  6358. }
  6359. public override void DebString(StringBuilder sb)
  6360. {
  6361. if(val is char)
  6362. {
  6363. sb.Append('\'');
  6364. EscapeQuotes(sb, new string(new char[] { (char)val }));
  6365. sb.Append('\'');
  6366. }
  6367. else if(val is int)
  6368. {
  6369. sb.Append((int)val);
  6370. }
  6371. else if(val is double)
  6372. {
  6373. string str = ((double)val).ToString();
  6374. sb.Append(str);
  6375. if((str.IndexOf('.') < 0) &&
  6376. (str.IndexOf('E') < 0) &&
  6377. (str.IndexOf('e') < 0))
  6378. {
  6379. sb.Append(".0");
  6380. }
  6381. }
  6382. else if(val is string)
  6383. {
  6384. sb.Append('"');
  6385. EscapeQuotes(sb, (string)val);
  6386. sb.Append('"');
  6387. }
  6388. else
  6389. {
  6390. throw new Exception("invalid constant type " + val.GetType());
  6391. }
  6392. }
  6393. private static void EscapeQuotes(StringBuilder sb, string s)
  6394. {
  6395. foreach(char c in s)
  6396. {
  6397. switch(c)
  6398. {
  6399. case '\n':
  6400. {
  6401. sb.Append("\\n");
  6402. break;
  6403. }
  6404. case '\t':
  6405. {
  6406. sb.Append("\\t");
  6407. break;
  6408. }
  6409. case '\\':
  6410. {
  6411. sb.Append("\\\\");
  6412. break;
  6413. }
  6414. case '\'':
  6415. {
  6416. sb.Append("\\'");
  6417. break;
  6418. }
  6419. case '\"':
  6420. {
  6421. sb.Append("\\\"");
  6422. break;
  6423. }
  6424. default:
  6425. {
  6426. sb.Append(c);
  6427. break;
  6428. }
  6429. }
  6430. }
  6431. }
  6432. }
  6433. /**
  6434. * @brief Default initialization value for the corresponding variable.
  6435. */
  6436. public class TokenRValInitDef: TokenRVal
  6437. {
  6438. public TokenType type;
  6439. public static TokenRValInitDef Construct(TokenDeclVar tokenDeclVar)
  6440. {
  6441. TokenRValInitDef zhis = new TokenRValInitDef(tokenDeclVar);
  6442. zhis.type = tokenDeclVar.type;
  6443. return zhis;
  6444. }
  6445. private TokenRValInitDef(Token original) : base(original) { }
  6446. public override TokenType GetRValType(ScriptCodeGen scg, TokenType[] argsig)
  6447. {
  6448. return type;
  6449. }
  6450. public override bool IsRValTrivial(ScriptCodeGen scg, TokenType[] argsig)
  6451. {
  6452. // it's always just a constant so it's always very trivial
  6453. return true;
  6454. }
  6455. public override void DebString(StringBuilder sb)
  6456. {
  6457. sb.Append("<default ");
  6458. sb.Append(type.ToString());
  6459. sb.Append('>');
  6460. }
  6461. }
  6462. /**
  6463. * @brief encapsulation of <rval> is <typeexp>
  6464. */
  6465. public class TokenRValIsType: TokenRVal
  6466. {
  6467. public TokenRVal rValExp;
  6468. public TokenTypeExp typeExp;
  6469. public TokenRValIsType(Token original) : base(original) { }
  6470. public override TokenType GetRValType(ScriptCodeGen scg, TokenType[] argsig)
  6471. {
  6472. return new TokenTypeBool(rValExp);
  6473. }
  6474. public override bool IsRValTrivial(ScriptCodeGen scg, TokenType[] argsig)
  6475. {
  6476. return rValExp.IsRValTrivial(scg, argsig);
  6477. }
  6478. }
  6479. /**
  6480. * @brief an R-value enclosed in brackets is an LSLList
  6481. */
  6482. public class TokenRValList: TokenRVal
  6483. {
  6484. public TokenRVal rVal; // null-terminated list of TokenRVal objects
  6485. public int nItems;
  6486. public TokenRValList(Token original) : base(original) { }
  6487. public override TokenType GetRValType(ScriptCodeGen scg, TokenType[] argsig)
  6488. {
  6489. return new TokenTypeList(rVal);
  6490. }
  6491. public override bool IsRValTrivial(ScriptCodeGen scg, TokenType[] argsig)
  6492. {
  6493. for(Token t = rVal; t != null; t = t.nextToken)
  6494. {
  6495. if(!((TokenRVal)t).IsRValTrivial(scg, null))
  6496. return false;
  6497. }
  6498. return true;
  6499. }
  6500. public override void DebString(StringBuilder sb)
  6501. {
  6502. bool first = true;
  6503. sb.Append('[');
  6504. for(Token t = rVal; t != null; t = t.nextToken)
  6505. {
  6506. if(!first)
  6507. sb.Append(',');
  6508. sb.Append(' ');
  6509. t.DebString(sb);
  6510. first = false;
  6511. }
  6512. sb.Append(" ]");
  6513. }
  6514. }
  6515. /**
  6516. * @brief encapsulates '$new' arraytype '{' ... '}'
  6517. */
  6518. public class TokenRValNewArIni: TokenRVal
  6519. {
  6520. public TokenType arrayType;
  6521. public TokenList valueList; // TokenList : a sub-list
  6522. // TokenKwComma : a default value
  6523. // TokenRVal : init expression
  6524. public TokenRValNewArIni(Token original) : base(original)
  6525. {
  6526. valueList = new TokenList(original);
  6527. }
  6528. // type of the expression = the array type allocated by $new()
  6529. public override TokenType GetRValType(ScriptCodeGen scg, TokenType[] argsig)
  6530. {
  6531. return arrayType;
  6532. }
  6533. // The expression is trivial if all the initializers are trivial.
  6534. // An array's constructor is always trivial (no CheckRun() calls).
  6535. public override bool IsRValTrivial(ScriptCodeGen scg, TokenType[] argsig)
  6536. {
  6537. return ListIsTrivial(scg, valueList);
  6538. }
  6539. private bool ListIsTrivial(ScriptCodeGen scg, TokenList valList)
  6540. {
  6541. foreach(Token val in valList.tl)
  6542. {
  6543. if(val is TokenRVal)
  6544. {
  6545. if(!((TokenRVal)val).IsRValTrivial(scg, null))
  6546. return false;
  6547. }
  6548. if(val is TokenList)
  6549. {
  6550. if(!ListIsTrivial(scg, (TokenList)val))
  6551. return false;
  6552. }
  6553. }
  6554. return true;
  6555. }
  6556. public override void DebString(StringBuilder sb)
  6557. {
  6558. sb.Append("new ");
  6559. arrayType.DebString(sb);
  6560. sb.Append(' ');
  6561. valueList.DebString(sb);
  6562. }
  6563. }
  6564. public class TokenList: Token
  6565. {
  6566. public List<Token> tl = new List<Token>();
  6567. public TokenList(Token original) : base(original) { }
  6568. public override void DebString(StringBuilder sb)
  6569. {
  6570. sb.Append('{');
  6571. bool first = true;
  6572. foreach(Token t in tl)
  6573. {
  6574. if(!first)
  6575. sb.Append(", ");
  6576. t.DebString(sb);
  6577. first = false;
  6578. }
  6579. sb.Append('}');
  6580. }
  6581. }
  6582. /**
  6583. * @brief a binary operator and its two operands
  6584. */
  6585. public class TokenRValOpBin: TokenRVal
  6586. {
  6587. public TokenRVal rValLeft;
  6588. public TokenKw opcode;
  6589. public TokenRVal rValRight;
  6590. public TokenRValOpBin(TokenRVal left, TokenKw op, TokenRVal right) : base(op)
  6591. {
  6592. rValLeft = left;
  6593. opcode = op;
  6594. rValRight = right;
  6595. }
  6596. public override TokenType GetRValType(ScriptCodeGen scg, TokenType[] argsig)
  6597. {
  6598. // Comparisons and the like always return bool.
  6599. string opstr = opcode.ToString();
  6600. if((opstr == "==") || (opstr == "!=") || (opstr == ">=") || (opstr == ">") ||
  6601. (opstr == "&&") || (opstr == "||") || (opstr == "<=") || (opstr == "<") ||
  6602. (opstr == "&&&") || (opstr == "|||"))
  6603. {
  6604. return new TokenTypeBool(opcode);
  6605. }
  6606. // Comma is always type of right-hand operand.
  6607. if(opstr == ",")
  6608. return rValRight.GetRValType(scg, argsig);
  6609. // Assignments are always the type of the left-hand operand,
  6610. // including stuff like "+=".
  6611. if(opstr.EndsWith("="))
  6612. {
  6613. return rValLeft.GetRValType(scg, argsig);
  6614. }
  6615. // string+something or something+string is always string.
  6616. // except list+something or something+list is always a list.
  6617. string lType = rValLeft.GetRValType(scg, argsig).ToString();
  6618. string rType = rValRight.GetRValType(scg, argsig).ToString();
  6619. if((opstr == "+") && ((lType == "list") || (rType == "list")))
  6620. {
  6621. return new TokenTypeList(opcode);
  6622. }
  6623. if((opstr == "+") && ((lType == "key") || (lType == "string") ||
  6624. (rType == "key") || (rType == "string")))
  6625. {
  6626. return new TokenTypeStr(opcode);
  6627. }
  6628. // Everything else depends on both operands.
  6629. string key = lType + opstr + rType;
  6630. BinOpStr binOpStr;
  6631. if(BinOpStr.defined.TryGetValue(key, out binOpStr))
  6632. {
  6633. return TokenType.FromSysType(opcode, binOpStr.outtype);
  6634. }
  6635. scg.ErrorMsg(opcode, "undefined operation " + key);
  6636. return new TokenTypeVoid(opcode);
  6637. }
  6638. public override bool IsRValTrivial(ScriptCodeGen scg, TokenType[] argsig)
  6639. {
  6640. return rValLeft.IsRValTrivial(scg, null) && rValRight.IsRValTrivial(scg, null);
  6641. }
  6642. /**
  6643. * @brief If both operands are constants, maybe we can say the whole thing is a constant.
  6644. */
  6645. public override TokenRVal TryComputeConstant(TCCLookup lookup, ref bool didOne)
  6646. {
  6647. rValLeft = rValLeft.TryComputeConstant(lookup, ref didOne);
  6648. rValRight = rValRight.TryComputeConstant(lookup, ref didOne);
  6649. if((rValLeft is TokenRValConst) && (rValRight is TokenRValConst))
  6650. {
  6651. try
  6652. {
  6653. object val = opcode.binOpConst(((TokenRValConst)rValLeft).val,
  6654. ((TokenRValConst)rValRight).val);
  6655. TokenRVal rValConst = new TokenRValConst(opcode, val);
  6656. didOne = true;
  6657. return rValConst;
  6658. }
  6659. catch
  6660. {
  6661. }
  6662. }
  6663. return this;
  6664. }
  6665. // debugging
  6666. public override void DebString(StringBuilder sb)
  6667. {
  6668. rValLeft.DebString(sb);
  6669. sb.Append(' ');
  6670. sb.Append(opcode.ToString());
  6671. sb.Append(' ');
  6672. rValRight.DebString(sb);
  6673. }
  6674. }
  6675. /**
  6676. * @brief an unary operator and its one operand
  6677. */
  6678. public class TokenRValOpUn: TokenRVal
  6679. {
  6680. public TokenKw opcode;
  6681. public TokenRVal rVal;
  6682. public TokenRValOpUn(TokenKw op, TokenRVal right) : base(op)
  6683. {
  6684. opcode = op;
  6685. rVal = right;
  6686. }
  6687. public override TokenType GetRValType(ScriptCodeGen scg, TokenType[] argsig)
  6688. {
  6689. if(opcode is TokenKwExclam)
  6690. return new TokenTypeInt(opcode);
  6691. return rVal.GetRValType(scg, null);
  6692. }
  6693. public override bool IsRValTrivial(ScriptCodeGen scg, TokenType[] argsig)
  6694. {
  6695. return rVal.IsRValTrivial(scg, null);
  6696. }
  6697. /**
  6698. * @brief If operand is constant, maybe we can say the whole thing is a constant.
  6699. */
  6700. public override TokenRVal TryComputeConstant(TCCLookup lookup, ref bool didOne)
  6701. {
  6702. rVal = rVal.TryComputeConstant(lookup, ref didOne);
  6703. if(rVal is TokenRValConst)
  6704. {
  6705. try
  6706. {
  6707. object val = opcode.unOpConst(((TokenRValConst)rVal).val);
  6708. TokenRVal rValConst = new TokenRValConst(opcode, val);
  6709. didOne = true;
  6710. return rValConst;
  6711. }
  6712. catch
  6713. {
  6714. }
  6715. }
  6716. return this;
  6717. }
  6718. /**
  6719. * @brief Serialization/Deserialization.
  6720. */
  6721. public TokenRValOpUn(Token original) : base(original) { }
  6722. // debugging
  6723. public override void DebString(StringBuilder sb)
  6724. {
  6725. sb.Append(opcode.ToString());
  6726. rVal.DebString(sb);
  6727. }
  6728. }
  6729. /**
  6730. * @brief an R-value enclosed in parentheses
  6731. */
  6732. public class TokenRValParen: TokenRVal
  6733. {
  6734. public TokenRVal rVal;
  6735. public TokenRValParen(Token original) : base(original) { }
  6736. public override TokenType GetRValType(ScriptCodeGen scg, TokenType[] argsig)
  6737. {
  6738. // pass argsig through in this simple case, ie, let
  6739. // them do something like (llOwnerSay)("blabla...");
  6740. return rVal.GetRValType(scg, argsig);
  6741. }
  6742. public override bool IsRValTrivial(ScriptCodeGen scg, TokenType[] argsig)
  6743. {
  6744. // pass argsig through in this simple case, ie, let
  6745. // them do something like (llOwnerSay)("blabla...");
  6746. return rVal.IsRValTrivial(scg, argsig);
  6747. }
  6748. /**
  6749. * @brief If operand is constant, we can say the whole thing is a constant.
  6750. */
  6751. public override TokenRVal TryComputeConstant(TCCLookup lookup, ref bool didOne)
  6752. {
  6753. rVal = rVal.TryComputeConstant(lookup, ref didOne);
  6754. if(rVal is TokenRValConst)
  6755. {
  6756. didOne = true;
  6757. return rVal;
  6758. }
  6759. return this;
  6760. }
  6761. public override void DebString(StringBuilder sb)
  6762. {
  6763. sb.Append('(');
  6764. rVal.DebString(sb);
  6765. sb.Append(')');
  6766. }
  6767. }
  6768. public class TokenRValRot: TokenRVal
  6769. {
  6770. public TokenRVal xRVal;
  6771. public TokenRVal yRVal;
  6772. public TokenRVal zRVal;
  6773. public TokenRVal wRVal;
  6774. public TokenRValRot(Token original) : base(original) { }
  6775. public override TokenType GetRValType(ScriptCodeGen scg, TokenType[] argsig)
  6776. {
  6777. return new TokenTypeRot(xRVal);
  6778. }
  6779. public override bool IsRValTrivial(ScriptCodeGen scg, TokenType[] argsig)
  6780. {
  6781. return xRVal.IsRValTrivial(scg, null) &&
  6782. yRVal.IsRValTrivial(scg, null) &&
  6783. zRVal.IsRValTrivial(scg, null) &&
  6784. wRVal.IsRValTrivial(scg, null);
  6785. }
  6786. public override void DebString(StringBuilder sb)
  6787. {
  6788. sb.Append('<');
  6789. xRVal.DebString(sb);
  6790. sb.Append(',');
  6791. yRVal.DebString(sb);
  6792. sb.Append(',');
  6793. zRVal.DebString(sb);
  6794. sb.Append(',');
  6795. wRVal.DebString(sb);
  6796. sb.Append('>');
  6797. }
  6798. }
  6799. /**
  6800. * @brief 'this' is being used as an rval inside an instance method.
  6801. */
  6802. public class TokenRValThis: TokenRVal
  6803. {
  6804. public Token original;
  6805. public TokenDeclSDTypeClass sdtClass;
  6806. public TokenRValThis(Token original, TokenDeclSDTypeClass sdtClass) : base(original)
  6807. {
  6808. this.original = original;
  6809. this.sdtClass = sdtClass;
  6810. }
  6811. public override TokenType GetRValType(ScriptCodeGen scg, TokenType[] argsig)
  6812. {
  6813. return sdtClass.MakeRefToken(original);
  6814. }
  6815. public override bool IsRValTrivial(ScriptCodeGen scg, TokenType[] argsig)
  6816. {
  6817. return true; // ldarg.0/starg.0 can't possibly loop
  6818. }
  6819. // debugging
  6820. public override void DebString(StringBuilder sb)
  6821. {
  6822. sb.Append("this");
  6823. }
  6824. }
  6825. /**
  6826. * @brief the 'undef' keyword is being used as a value in an expression.
  6827. * It is the null object pointer and has type TokenTypeUndef.
  6828. */
  6829. public class TokenRValUndef: TokenRVal
  6830. {
  6831. Token original;
  6832. public TokenRValUndef(Token original) : base(original)
  6833. {
  6834. this.original = original;
  6835. }
  6836. public override TokenType GetRValType(ScriptCodeGen scg, TokenType[] argsig)
  6837. {
  6838. return new TokenTypeUndef(original);
  6839. }
  6840. public override bool IsRValTrivial(ScriptCodeGen scg, TokenType[] argsig)
  6841. {
  6842. return true;
  6843. }
  6844. public override void DebString(StringBuilder sb)
  6845. {
  6846. sb.Append("undef");
  6847. }
  6848. }
  6849. /**
  6850. * @brief put 3 RVals together as a Vector value.
  6851. */
  6852. public class TokenRValVec: TokenRVal
  6853. {
  6854. public TokenRVal xRVal;
  6855. public TokenRVal yRVal;
  6856. public TokenRVal zRVal;
  6857. public TokenRValVec(Token original) : base(original) { }
  6858. public override TokenType GetRValType(ScriptCodeGen scg, TokenType[] argsig)
  6859. {
  6860. return new TokenTypeVec(xRVal);
  6861. }
  6862. public override bool IsRValTrivial(ScriptCodeGen scg, TokenType[] argsig)
  6863. {
  6864. return xRVal.IsRValTrivial(scg, null) &&
  6865. yRVal.IsRValTrivial(scg, null) &&
  6866. zRVal.IsRValTrivial(scg, null);
  6867. }
  6868. public override void DebString(StringBuilder sb)
  6869. {
  6870. sb.Append('<');
  6871. xRVal.DebString(sb);
  6872. sb.Append(',');
  6873. yRVal.DebString(sb);
  6874. sb.Append(',');
  6875. zRVal.DebString(sb);
  6876. sb.Append('>');
  6877. }
  6878. }
  6879. /**
  6880. * @brief encapsulates the whole script in a single token
  6881. */
  6882. public class TokenScript: Token
  6883. {
  6884. public int expiryDays = Int32.MaxValue;
  6885. public TokenDeclState defaultState;
  6886. public Dictionary<string, TokenDeclState> states = new Dictionary<string, TokenDeclState>();
  6887. public VarDict variablesStack = new VarDict(false); // initial one is used for global functions and variables
  6888. public TokenDeclVar globalVarInit; // $globalvarinit function
  6889. // - performs explicit global var and static field inits
  6890. private Dictionary<string, TokenDeclSDType> sdSrcTypes = new Dictionary<string, TokenDeclSDType>();
  6891. private bool sdSrcTypesSealed = false;
  6892. public TokenScript(Token original) : base(original) { }
  6893. /*
  6894. * Handle variable definition stack.
  6895. * Generally a '{' pushes a new frame and a '}' pops the frame.
  6896. * Function parameters are pushed in an additional frame (just outside the body's { ... } block)
  6897. */
  6898. public void PushVarFrame(bool locals)
  6899. {
  6900. PushVarFrame(new VarDict(locals));
  6901. }
  6902. public void PushVarFrame(VarDict newFrame)
  6903. {
  6904. newFrame.outerVarDict = variablesStack;
  6905. variablesStack = newFrame;
  6906. }
  6907. public void PopVarFrame()
  6908. {
  6909. variablesStack = variablesStack.outerVarDict;
  6910. }
  6911. public bool AddVarEntry(TokenDeclVar var)
  6912. {
  6913. return variablesStack.AddEntry(var);
  6914. }
  6915. /*
  6916. * Handle list of script-defined types.
  6917. */
  6918. public void sdSrcTypesSeal()
  6919. {
  6920. sdSrcTypesSealed = true;
  6921. }
  6922. public bool sdSrcTypesContainsKey(string key)
  6923. {
  6924. return sdSrcTypes.ContainsKey(key);
  6925. }
  6926. public bool sdSrcTypesTryGetValue(string key, out TokenDeclSDType value)
  6927. {
  6928. return sdSrcTypes.TryGetValue(key, out value);
  6929. }
  6930. public void sdSrcTypesAdd(string key, TokenDeclSDType value)
  6931. {
  6932. if(sdSrcTypesSealed)
  6933. throw new Exception("sdSrcTypes is sealed");
  6934. value.sdTypeIndex = sdSrcTypes.Count;
  6935. sdSrcTypes.Add(key, value);
  6936. }
  6937. public void sdSrcTypesRep(string key, TokenDeclSDType value)
  6938. {
  6939. if(sdSrcTypesSealed)
  6940. throw new Exception("sdSrcTypes is sealed");
  6941. value.sdTypeIndex = sdSrcTypes[key].sdTypeIndex;
  6942. sdSrcTypes[key] = value;
  6943. }
  6944. public void sdSrcTypesReplace(string key, TokenDeclSDType value)
  6945. {
  6946. if(sdSrcTypesSealed)
  6947. throw new Exception("sdSrcTypes is sealed");
  6948. sdSrcTypes[key] = value;
  6949. }
  6950. public Dictionary<string, TokenDeclSDType>.ValueCollection sdSrcTypesValues
  6951. {
  6952. get
  6953. {
  6954. return sdSrcTypes.Values;
  6955. }
  6956. }
  6957. public int sdSrcTypesCount
  6958. {
  6959. get
  6960. {
  6961. return sdSrcTypes.Count;
  6962. }
  6963. }
  6964. /**
  6965. * @brief Debug output.
  6966. */
  6967. public override void DebString(StringBuilder sb)
  6968. {
  6969. /*
  6970. * Script-defined types.
  6971. */
  6972. foreach(TokenDeclSDType srcType in sdSrcTypes.Values)
  6973. {
  6974. srcType.DebString(sb);
  6975. }
  6976. /*
  6977. * Global constants.
  6978. * Variables are handled by outputting the $globalvarinit function.
  6979. */
  6980. foreach(TokenDeclVar var in variablesStack)
  6981. {
  6982. if(var.constant)
  6983. {
  6984. var.DebString(sb);
  6985. }
  6986. }
  6987. /*
  6988. * Global functions.
  6989. */
  6990. foreach(TokenDeclVar var in variablesStack)
  6991. {
  6992. if(var == globalVarInit)
  6993. {
  6994. var.DebStringInitFields(sb);
  6995. }
  6996. else if(var.retType != null)
  6997. {
  6998. var.DebString(sb);
  6999. }
  7000. }
  7001. /*
  7002. * States and their event handler functions.
  7003. */
  7004. defaultState.DebString(sb);
  7005. foreach(TokenDeclState st in states.Values)
  7006. {
  7007. st.DebString(sb);
  7008. }
  7009. }
  7010. }
  7011. /**
  7012. * @brief state body declaration
  7013. */
  7014. public class TokenStateBody: Token
  7015. {
  7016. public TokenDeclVar eventFuncs;
  7017. public int index = -1; // (codegen) row in ScriptHandlerEventTable (0=default)
  7018. public TokenStateBody(Token original) : base(original) { }
  7019. public override void DebString(StringBuilder sb)
  7020. {
  7021. sb.Append(" { ");
  7022. for(Token t = eventFuncs; t != null; t = t.nextToken)
  7023. {
  7024. t.DebString(sb);
  7025. }
  7026. sb.Append(" } ");
  7027. }
  7028. }
  7029. /**
  7030. * @brief a single statement, such as ending on a semicolon or enclosed in braces
  7031. * TokenStmt includes the terminating semicolon or the enclosing braces
  7032. * Also includes @label; for jump targets.
  7033. * Also includes stray ; null statements.
  7034. * Also includes local variable declarations with or without initialization value.
  7035. */
  7036. public class TokenStmt: Token
  7037. {
  7038. public TokenStmt(Token original) : base(original) { }
  7039. }
  7040. /**
  7041. * @brief a group of statements enclosed in braces
  7042. */
  7043. public class TokenStmtBlock: TokenStmt
  7044. {
  7045. public Token statements; // null-terminated list of statements, can also have TokenDeclVar's in here
  7046. public TokenStmtBlock outerStmtBlock; // next outer stmtBlock or null if top-level, ie, function definition
  7047. public TokenDeclVar function; // function it is part of
  7048. public bool isTry; // true iff it's a try statement block
  7049. public bool isCatch; // true iff it's a catch statement block
  7050. public bool isFinally; // true iff it's a finally statement block
  7051. public TokenStmtTry tryStmt; // set iff isTry|isCatch|isFinally is set
  7052. public TokenStmtBlock(Token original) : base(original) { }
  7053. // debugging
  7054. public override void DebString(StringBuilder sb)
  7055. {
  7056. sb.Append("{ ");
  7057. for(Token stmt = statements; stmt != null; stmt = stmt.nextToken)
  7058. {
  7059. stmt.DebString(sb);
  7060. }
  7061. sb.Append("} ");
  7062. }
  7063. }
  7064. /**
  7065. * @brief definition of branch target name
  7066. */
  7067. public class TokenStmtLabel: TokenStmt
  7068. {
  7069. public TokenName name; // the label's name
  7070. public TokenStmtBlock block; // which block it is defined in
  7071. public bool hasBkwdRefs = false;
  7072. public bool labelTagged; // code gen: location of label
  7073. public ScriptMyLabel labelStruct;
  7074. public TokenStmtLabel(Token original) : base(original) { }
  7075. public override void DebString(StringBuilder sb)
  7076. {
  7077. sb.Append('@');
  7078. name.DebString(sb);
  7079. sb.Append(';');
  7080. }
  7081. }
  7082. /**
  7083. * @brief those types of RVals with a semi-colon on the end
  7084. * that are allowed to stand alone as statements
  7085. */
  7086. public class TokenStmtRVal: TokenStmt
  7087. {
  7088. public TokenRVal rVal;
  7089. public TokenStmtRVal(Token original) : base(original) { }
  7090. // debugging
  7091. public override void DebString(StringBuilder sb)
  7092. {
  7093. rVal.DebString(sb);
  7094. sb.Append("; ");
  7095. }
  7096. }
  7097. public class TokenStmtBreak: TokenStmt
  7098. {
  7099. public TokenStmtBreak(Token original) : base(original) { }
  7100. public override void DebString(StringBuilder sb)
  7101. {
  7102. sb.Append("break;");
  7103. }
  7104. }
  7105. public class TokenStmtCont: TokenStmt
  7106. {
  7107. public TokenStmtCont(Token original) : base(original) { }
  7108. public override void DebString(StringBuilder sb)
  7109. {
  7110. sb.Append("continue;");
  7111. }
  7112. }
  7113. /**
  7114. * @brief "do" statement
  7115. */
  7116. public class TokenStmtDo: TokenStmt
  7117. {
  7118. public TokenStmt bodyStmt;
  7119. public TokenRValParen testRVal;
  7120. public TokenStmtDo(Token original) : base(original) { }
  7121. public override void DebString(StringBuilder sb)
  7122. {
  7123. sb.Append("do ");
  7124. bodyStmt.DebString(sb);
  7125. sb.Append(" while ");
  7126. testRVal.DebString(sb);
  7127. sb.Append(';');
  7128. }
  7129. }
  7130. /**
  7131. * @brief "for" statement
  7132. */
  7133. public class TokenStmtFor: TokenStmt
  7134. {
  7135. public TokenStmt initStmt; // there is always an init statement, though it may be a null statement
  7136. public TokenRVal testRVal; // there may or may not be a test (null if not)
  7137. public TokenRVal incrRVal; // there may or may not be an increment (null if not)
  7138. public TokenStmt bodyStmt; // there is always a body statement, though it may be a null statement
  7139. public TokenStmtFor(Token original) : base(original) { }
  7140. public override void DebString(StringBuilder sb)
  7141. {
  7142. sb.Append("for (");
  7143. if(initStmt != null)
  7144. initStmt.DebString(sb);
  7145. else
  7146. sb.Append(';');
  7147. if(testRVal != null)
  7148. testRVal.DebString(sb);
  7149. sb.Append(';');
  7150. if(incrRVal != null)
  7151. incrRVal.DebString(sb);
  7152. sb.Append(") ");
  7153. bodyStmt.DebString(sb);
  7154. }
  7155. }
  7156. /**
  7157. * @brief "foreach" statement
  7158. */
  7159. public class TokenStmtForEach: TokenStmt
  7160. {
  7161. public TokenLVal keyLVal;
  7162. public TokenLVal valLVal;
  7163. public TokenRVal arrayRVal;
  7164. public TokenStmt bodyStmt; // there is always a body statement, though it may be a null statement
  7165. public TokenStmtForEach(Token original) : base(original) { }
  7166. public override void DebString(StringBuilder sb)
  7167. {
  7168. sb.Append("foreach (");
  7169. if(keyLVal != null)
  7170. keyLVal.DebString(sb);
  7171. sb.Append(',');
  7172. if(valLVal != null)
  7173. valLVal.DebString(sb);
  7174. sb.Append(" in ");
  7175. arrayRVal.DebString(sb);
  7176. sb.Append(')');
  7177. bodyStmt.DebString(sb);
  7178. }
  7179. }
  7180. public class TokenStmtIf: TokenStmt
  7181. {
  7182. public TokenRValParen testRVal;
  7183. public TokenStmt trueStmt;
  7184. public TokenStmt elseStmt;
  7185. public TokenStmtIf(Token original) : base(original) { }
  7186. public override void DebString(StringBuilder sb)
  7187. {
  7188. sb.Append("if ");
  7189. testRVal.DebString(sb);
  7190. sb.Append(" ");
  7191. trueStmt.DebString(sb);
  7192. if(elseStmt != null)
  7193. {
  7194. sb.Append(" else ");
  7195. elseStmt.DebString(sb);
  7196. }
  7197. }
  7198. }
  7199. public class TokenStmtJump: TokenStmt
  7200. {
  7201. public TokenName label;
  7202. public TokenStmtJump(Token original) : base(original) { }
  7203. public override void DebString(StringBuilder sb)
  7204. {
  7205. sb.Append("jump ");
  7206. label.DebString(sb);
  7207. sb.Append(';');
  7208. }
  7209. }
  7210. public class TokenStmtNull: TokenStmt
  7211. {
  7212. public TokenStmtNull(Token original) : base(original) { }
  7213. public override void DebString(StringBuilder sb)
  7214. {
  7215. sb.Append(';');
  7216. }
  7217. }
  7218. public class TokenStmtRet: TokenStmt
  7219. {
  7220. public TokenRVal rVal; // null if void
  7221. public TokenStmtRet(Token original) : base(original) { }
  7222. public override void DebString(StringBuilder sb)
  7223. {
  7224. sb.Append("return");
  7225. if(rVal != null)
  7226. {
  7227. sb.Append(' ');
  7228. rVal.DebString(sb);
  7229. }
  7230. sb.Append(';');
  7231. }
  7232. }
  7233. /**
  7234. * @brief statement that changes the current state.
  7235. */
  7236. public class TokenStmtState: TokenStmt
  7237. {
  7238. public TokenName state; // null for default
  7239. public TokenStmtState(Token original) : base(original) { }
  7240. public override void DebString(StringBuilder sb)
  7241. {
  7242. sb.Append("state ");
  7243. sb.Append((state == null) ? "default" : state.val);
  7244. sb.Append(';');
  7245. }
  7246. }
  7247. /**
  7248. * @brief Encapsulates a whole switch statement including the body and all cases.
  7249. */
  7250. public class TokenStmtSwitch: TokenStmt
  7251. {
  7252. public TokenRValParen testRVal; // the integer index expression
  7253. public TokenSwitchCase cases = null; // list of all cases, linked by .nextCase
  7254. public TokenSwitchCase lastCase = null; // used during reduce to point to last in 'cases' list
  7255. public TokenStmtSwitch(Token original) : base(original) { }
  7256. public override void DebString(StringBuilder sb)
  7257. {
  7258. sb.Append("switch ");
  7259. testRVal.DebString(sb);
  7260. sb.Append('{');
  7261. for(TokenSwitchCase kase = cases; kase != null; kase = kase.nextCase)
  7262. {
  7263. kase.DebString(sb);
  7264. }
  7265. sb.Append('}');
  7266. }
  7267. }
  7268. /**
  7269. * @brief Encapsulates a case/default clause from a switch statement including the
  7270. * two values and the corresponding body statements.
  7271. */
  7272. public class TokenSwitchCase: Token
  7273. {
  7274. public TokenSwitchCase nextCase; // next case in source-code order
  7275. public TokenRVal rVal1; // null means 'default', else 'case'
  7276. public TokenRVal rVal2; // null means 'case expr:', else 'case expr ... expr:'
  7277. public TokenStmt stmts; // statements associated with the case
  7278. public TokenStmt lastStmt; // used during reduce for building statement list
  7279. public int val1; // codegen: value of rVal1 here
  7280. public int val2; // codegen: value of rVal2 here
  7281. public ScriptMyLabel label; // codegen: target label here
  7282. public TokenSwitchCase nextSortedCase; // codegen: next case in ascending val order
  7283. public string str1;
  7284. public string str2;
  7285. public TokenSwitchCase lowerCase;
  7286. public TokenSwitchCase higherCase;
  7287. public TokenSwitchCase(Token original) : base(original) { }
  7288. public override void DebString(StringBuilder sb)
  7289. {
  7290. if(rVal1 == null)
  7291. {
  7292. sb.Append("default: ");
  7293. }
  7294. else
  7295. {
  7296. sb.Append("case ");
  7297. rVal1.DebString(sb);
  7298. if(rVal2 != null)
  7299. {
  7300. sb.Append(" ... ");
  7301. rVal2.DebString(sb);
  7302. }
  7303. sb.Append(": ");
  7304. }
  7305. for(Token t = stmts; t != null; t = t.nextToken)
  7306. {
  7307. t.DebString(sb);
  7308. }
  7309. }
  7310. }
  7311. public class TokenStmtThrow: TokenStmt
  7312. {
  7313. public TokenRVal rVal; // null if rethrow style
  7314. public TokenStmtThrow(Token original) : base(original) { }
  7315. public override void DebString(StringBuilder sb)
  7316. {
  7317. sb.Append("throw ");
  7318. rVal.DebString(sb);
  7319. sb.Append(';');
  7320. }
  7321. }
  7322. /**
  7323. * @brief Encapsulates related try, catch and finally statements.
  7324. */
  7325. public class TokenStmtTry: TokenStmt
  7326. {
  7327. public TokenStmtBlock tryStmt;
  7328. public TokenDeclVar catchVar; // null iff catchStmt is null
  7329. public TokenStmtBlock catchStmt; // can be null
  7330. public TokenStmtBlock finallyStmt; // can be null
  7331. public Dictionary<string, IntermediateLeave> iLeaves = new Dictionary<string, IntermediateLeave>();
  7332. public TokenStmtTry(Token original) : base(original) { }
  7333. public override void DebString(StringBuilder sb)
  7334. {
  7335. sb.Append("try ");
  7336. tryStmt.DebString(sb);
  7337. if(catchStmt != null)
  7338. {
  7339. sb.Append("catch (");
  7340. sb.Append(catchVar.type.ToString());
  7341. sb.Append(' ');
  7342. sb.Append(catchVar.name.val);
  7343. sb.Append(") ");
  7344. catchStmt.DebString(sb);
  7345. }
  7346. if(finallyStmt != null)
  7347. {
  7348. sb.Append("finally ");
  7349. finallyStmt.DebString(sb);
  7350. }
  7351. }
  7352. }
  7353. public class IntermediateLeave
  7354. {
  7355. public ScriptMyLabel jumpIntoLabel;
  7356. public ScriptMyLabel jumpAwayLabel;
  7357. }
  7358. public class TokenStmtVarIniDef: TokenStmt
  7359. {
  7360. public TokenLVal var;
  7361. public TokenStmtVarIniDef(Token original) : base(original) { }
  7362. }
  7363. public class TokenStmtWhile: TokenStmt
  7364. {
  7365. public TokenRValParen testRVal;
  7366. public TokenStmt bodyStmt;
  7367. public TokenStmtWhile(Token original) : base(original) { }
  7368. public override void DebString(StringBuilder sb)
  7369. {
  7370. sb.Append("while ");
  7371. testRVal.DebString(sb);
  7372. sb.Append(' ');
  7373. bodyStmt.DebString(sb);
  7374. }
  7375. }
  7376. /**
  7377. * @brief type expressions (right-hand of 'is' keyword).
  7378. */
  7379. public class TokenTypeExp: Token
  7380. {
  7381. public TokenTypeExp(Token original) : base(original) { }
  7382. }
  7383. public class TokenTypeExpBinOp: TokenTypeExp
  7384. {
  7385. public TokenTypeExp leftOp;
  7386. public Token binOp;
  7387. public TokenTypeExp rightOp;
  7388. public TokenTypeExpBinOp(Token original) : base(original) { }
  7389. }
  7390. public class TokenTypeExpNot: TokenTypeExp
  7391. {
  7392. public TokenTypeExp typeExp;
  7393. public TokenTypeExpNot(Token original) : base(original) { }
  7394. }
  7395. public class TokenTypeExpPar: TokenTypeExp
  7396. {
  7397. public TokenTypeExp typeExp;
  7398. public TokenTypeExpPar(Token original) : base(original) { }
  7399. }
  7400. public class TokenTypeExpType: TokenTypeExp
  7401. {
  7402. public TokenType typeToken;
  7403. public TokenTypeExpType(Token original) : base(original) { }
  7404. }
  7405. public class TokenTypeExpUndef: TokenTypeExp
  7406. {
  7407. public TokenTypeExpUndef(Token original) : base(original) { }
  7408. }
  7409. }