1
0

MMRScriptReduce.cs 308 KB

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