1
0

MMRScriptReduce.cs 308 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180
  1. /*
  2. * Copyright (c) Contributors, http://opensimulator.org/
  3. * See CONTRIBUTORS.TXT for a full list of copyright holders.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. * * Redistributions of source code must retain the above copyright
  8. * notice, this list of conditions and the following disclaimer.
  9. * * Redistributions in binary form must reproduce the above copyright
  10. * notice, this list of conditions and the following disclaimer in the
  11. * documentation and/or other materials provided with the distribution.
  12. * * Neither the name of the OpenSimulator Project nor the
  13. * names of its contributors may be used to endorse or promote products
  14. * derived from this software without specific prior written permission.
  15. *
  16. * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
  17. * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  18. * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  19. * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
  20. * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  21. * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  22. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  23. * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  24. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  25. * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  26. */
  27. /**
  28. * @brief Reduce parser tokens to abstract syntax tree tokens.
  29. *
  30. * Usage:
  31. *
  32. * tokenBegin = returned by TokenBegin.Analyze ()
  33. * representing the whole script source
  34. * as a flat list of tokens
  35. *
  36. * TokenScript tokenScript = Reduce.Analyze (TokenBegin tokenBegin);
  37. *
  38. * tokenScript = represents the whole script source
  39. * as a tree of tokens
  40. */
  41. using OpenSim.Region.ScriptEngine.Shared.ScriptBase;
  42. using System;
  43. using System.Collections.Generic;
  44. using System.IO;
  45. using System.Reflection;
  46. using System.Reflection.Emit;
  47. using System.Text;
  48. using LSL_Float = OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLFloat;
  49. using LSL_Integer = OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLInteger;
  50. using LSL_Key = OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLString;
  51. using LSL_List = OpenSim.Region.ScriptEngine.Shared.LSL_Types.list;
  52. using LSL_Rotation = OpenSim.Region.ScriptEngine.Shared.LSL_Types.Quaternion;
  53. using LSL_String = OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLString;
  54. using LSL_Vector = OpenSim.Region.ScriptEngine.Shared.LSL_Types.Vector3;
  55. namespace OpenSim.Region.ScriptEngine.Yengine
  56. {
  57. public class ScriptReduce
  58. {
  59. public const uint SDT_PRIVATE = 1;
  60. public const uint SDT_PROTECTED = 2;
  61. public const uint SDT_PUBLIC = 4;
  62. public const uint SDT_ABSTRACT = 8;
  63. public const uint SDT_FINAL = 16;
  64. public const uint SDT_NEW = 32;
  65. public const uint SDT_OVERRIDE = 64;
  66. public const uint SDT_STATIC = 128;
  67. public const uint SDT_VIRTUAL = 256;
  68. private const int ASNPR = 50;
  69. private 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 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 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 case or default label");
  2928. token = SkipPastSemi(token);
  2929. haveComplained = true;
  2930. }
  2931. }
  2932. token = token.nextToken;
  2933. return tokenStmtSwitch;
  2934. }
  2935. private TokenStmtState ParseStmtState(ref Token token)
  2936. {
  2937. TokenStmtState tokenStmtState = new(token);
  2938. token = token.nextToken;
  2939. if((token is not TokenName && token is not TokenKwDefault) || token.nextToken is not TokenKwSemi)
  2940. {
  2941. ErrorMsg(token, "expecting state;");
  2942. token = SkipPastSemi(token);
  2943. return null;
  2944. }
  2945. if(token is TokenName tname)
  2946. {
  2947. tokenStmtState.state = tname;
  2948. }
  2949. token = token.nextToken.nextToken;
  2950. return tokenStmtState;
  2951. }
  2952. private TokenStmtThrow ParseStmtThrow(ref Token token)
  2953. {
  2954. TokenStmtThrow tokenStmtThrow = new(token);
  2955. token = token.nextToken;
  2956. if(token is TokenKwSemi)
  2957. {
  2958. token = token.nextToken;
  2959. }
  2960. else
  2961. {
  2962. tokenStmtThrow.rVal = ParseRVal(ref token, semiOnly);
  2963. if(tokenStmtThrow.rVal == null)
  2964. return null;
  2965. }
  2966. return tokenStmtThrow;
  2967. }
  2968. /**
  2969. * @brief Parse a try { ... } catch { ... } finally { ... } statement block
  2970. * @param token = point to 'try' keyword on entry
  2971. * points past last '}' processed on return
  2972. * @returns encapsulated try/catch/finally or null if parsing error
  2973. */
  2974. private TokenStmtTry ParseStmtTry(ref Token token)
  2975. {
  2976. // Parse out the 'try { ... }' part
  2977. Token tryKw = token;
  2978. token = token.nextToken;
  2979. TokenStmt body = ParseStmtBlock(ref token);
  2980. while(true)
  2981. {
  2982. TokenStmtTry tokenStmtTry;
  2983. if(token is TokenKwCatch)
  2984. {
  2985. if(token.nextToken is not TokenKwParOpen ||
  2986. token.nextToken.nextToken is not TokenType ||
  2987. token.nextToken.nextToken.nextToken is not TokenName ||
  2988. token.nextToken.nextToken.nextToken.nextToken is not TokenKwParClose)
  2989. {
  2990. ErrorMsg(token, "catch must be followed by ( <type> <varname> ) { <statement>... }");
  2991. return null;
  2992. }
  2993. token = token.nextToken.nextToken; // skip over 'catch' '('
  2994. TokenDeclVar tag = new(token.nextToken, currentDeclFunc, tokenScript) { type = (TokenType)token };
  2995. token = token.nextToken; // skip over <type>
  2996. tag.name = (TokenName)token;
  2997. token = token.nextToken.nextToken; // skip over <varname> ')'
  2998. if((tag.type is not TokenTypeExc) && (tag.type is not TokenTypeStr))
  2999. {
  3000. ErrorMsg(tag.type, "must be type 'exception' or 'string'");
  3001. }
  3002. tokenStmtTry = new TokenStmtTry(tryKw)
  3003. {
  3004. tryStmt = WrapTryCatFinInBlock(body),
  3005. catchVar = tag
  3006. };
  3007. tokenScript.PushVarFrame(false);
  3008. tokenScript.AddVarEntry(tag);
  3009. tokenStmtTry.catchStmt = ParseStmtBlock(ref token);
  3010. tokenScript.PopVarFrame();
  3011. if(tokenStmtTry.catchStmt == null)
  3012. return null;
  3013. tokenStmtTry.tryStmt.isTry = true;
  3014. tokenStmtTry.tryStmt.tryStmt = tokenStmtTry;
  3015. tokenStmtTry.catchStmt.isCatch = true;
  3016. tokenStmtTry.catchStmt.tryStmt = tokenStmtTry;
  3017. }
  3018. else if(token is TokenKwFinally)
  3019. {
  3020. token = token.nextToken;
  3021. tokenStmtTry = new TokenStmtTry(tryKw)
  3022. {
  3023. tryStmt = WrapTryCatFinInBlock(body),
  3024. finallyStmt = ParseStmtBlock(ref token)
  3025. };
  3026. if (tokenStmtTry.finallyStmt == null)
  3027. return null;
  3028. tokenStmtTry.tryStmt.isTry = true;
  3029. tokenStmtTry.tryStmt.tryStmt = tokenStmtTry;
  3030. tokenStmtTry.finallyStmt.isFinally = true;
  3031. tokenStmtTry.finallyStmt.tryStmt = tokenStmtTry;
  3032. }
  3033. else
  3034. break;
  3035. body = tokenStmtTry;
  3036. }
  3037. if(!(body is TokenStmtTry))
  3038. {
  3039. ErrorMsg(body, "try must have a matching catch and/or finally");
  3040. return null;
  3041. }
  3042. return (TokenStmtTry)body;
  3043. }
  3044. /**
  3045. * @brief Wrap a possible try/catch/finally statement block in a block statement.
  3046. *
  3047. * Given body = try { } catch (string s) { }
  3048. *
  3049. * we return { try { } catch (string s) { } }
  3050. *
  3051. * @param body = a TokenStmtTry or a TokenStmtBlock
  3052. * @returns a TokenStmtBlock
  3053. */
  3054. private TokenStmtBlock WrapTryCatFinInBlock(TokenStmt body)
  3055. {
  3056. if(body is TokenStmtBlock tb)
  3057. return tb;
  3058. TokenStmtTry innerTry = (TokenStmtTry)body;
  3059. TokenStmtBlock wrapper = new(body)
  3060. {
  3061. statements = innerTry,
  3062. outerStmtBlock = currentStmtBlock,
  3063. function = currentDeclFunc
  3064. };
  3065. innerTry.tryStmt.outerStmtBlock = wrapper;
  3066. if(innerTry.catchStmt != null)
  3067. innerTry.catchStmt.outerStmtBlock = wrapper;
  3068. if(innerTry.finallyStmt != null)
  3069. innerTry.finallyStmt.outerStmtBlock = wrapper;
  3070. return wrapper;
  3071. }
  3072. private TokenStmtWhile ParseStmtWhile(ref Token token)
  3073. {
  3074. currentDeclFunc.triviality = Triviality.complex;
  3075. TokenStmtWhile tokenStmtWhile = new(token);
  3076. token = token.nextToken;
  3077. tokenStmtWhile.testRVal = ParseRValParen(ref token);
  3078. if(tokenStmtWhile.testRVal == null)
  3079. return null;
  3080. tokenStmtWhile.bodyStmt = ParseStmt(ref token);
  3081. if(tokenStmtWhile.bodyStmt == null)
  3082. return null;
  3083. return tokenStmtWhile;
  3084. }
  3085. /**
  3086. * @brief parse a variable declaration statement, including init value if any.
  3087. * @param token = points to type or 'constant' token
  3088. * @param initFunc = null: parsing a local var declaration
  3089. * put initialization code in .init
  3090. * else: parsing a global var or field var declaration
  3091. * put initialization code in initFunc.body
  3092. * @returns null: parsing error
  3093. * else: variable declaration encapulating token
  3094. * token = advanced just past semi-colon
  3095. * variables = modified to include the new variable
  3096. */
  3097. private TokenDeclVar ParseDeclVar(ref Token token, TokenDeclVar initFunc)
  3098. {
  3099. TokenDeclVar tokenDeclVar = new(token.nextToken, currentDeclFunc, tokenScript);
  3100. // Handle constant declaration.
  3101. // It ends up in the declared variables list for the statement block just like
  3102. // any other variable, except it has .constant = true.
  3103. // The code generator will test that the initialization expression is constant.
  3104. //
  3105. // constant <name> = <value> ;
  3106. if(token is TokenKwConst)
  3107. {
  3108. token = token.nextToken;
  3109. if(token is not TokenName)
  3110. {
  3111. ErrorMsg(token, "expecting constant name");
  3112. token = SkipPastSemi(token);
  3113. return null;
  3114. }
  3115. tokenDeclVar.name = (TokenName)token;
  3116. token = token.nextToken;
  3117. if(token is not TokenKwAssign)
  3118. {
  3119. ErrorMsg(token, "expecting =");
  3120. token = SkipPastSemi(token);
  3121. return null;
  3122. }
  3123. token = token.nextToken;
  3124. TokenRVal rVal = ParseRVal(ref token, semiOnly);
  3125. if(rVal == null)
  3126. return null;
  3127. tokenDeclVar.init = rVal;
  3128. tokenDeclVar.constant = true;
  3129. }
  3130. // Otherwise, normal variable declaration with optional initialization value.
  3131. else
  3132. {
  3133. // Build basic encapsulating token with type and name.
  3134. tokenDeclVar.type = (TokenType)token;
  3135. token = token.nextToken;
  3136. if(!(token is TokenName))
  3137. {
  3138. ErrorMsg(token, "expecting variable name");
  3139. token = SkipPastSemi(token);
  3140. return null;
  3141. }
  3142. tokenDeclVar.name = (TokenName)token;
  3143. token = token.nextToken;
  3144. // If just a ;, there is no explicit initialization value.
  3145. // Otherwise, look for an =RVal; expression that has init value.
  3146. if(token is TokenKwSemi)
  3147. {
  3148. token = token.nextToken;
  3149. if(initFunc != null)
  3150. {
  3151. tokenDeclVar.init = TokenRValInitDef.Construct(tokenDeclVar);
  3152. }
  3153. }
  3154. else if(token is TokenKwAssign)
  3155. {
  3156. token = token.nextToken;
  3157. if(initFunc != null)
  3158. {
  3159. currentDeclFunc = initFunc;
  3160. tokenDeclVar.init = ParseRVal(ref token, semiOnly);
  3161. currentDeclFunc = null;
  3162. }
  3163. else
  3164. {
  3165. tokenDeclVar.init = ParseRVal(ref token, semiOnly);
  3166. }
  3167. if(tokenDeclVar.init == null)
  3168. return null;
  3169. }
  3170. else
  3171. {
  3172. ErrorMsg(token, "expecting = or ;");
  3173. token = SkipPastSemi(token);
  3174. return null;
  3175. }
  3176. }
  3177. // If doing local vars, each var goes in its own var frame,
  3178. // to make sure no code before this point can reference it.
  3179. if (currentStmtBlock != null)
  3180. {
  3181. tokenScript.PushVarFrame(true);
  3182. }
  3183. /*
  3184. ScriptConst scriptConst = ScriptConst.Lookup(tokenDeclVar.name.val);
  3185. if (scriptConst != null)
  3186. {
  3187. ErrorMsg(tokenDeclVar, "reserved constant name " + tokenDeclVar.name.val);
  3188. return null;
  3189. }
  3190. */
  3191. // Can't be same name already in block.
  3192. if (!tokenScript.AddVarEntry(tokenDeclVar))
  3193. {
  3194. ErrorMsg(tokenDeclVar, "duplicate variable " + tokenDeclVar.name.val);
  3195. return null;
  3196. }
  3197. /*
  3198. if (TokenDeclInline.inlineFunctions.HasAnyExact(tokenDeclVar.name.val))
  3199. {
  3200. ErrorMsg(tokenDeclVar, "reserved name " + tokenDeclVar.name.val);
  3201. return null;
  3202. }
  3203. */
  3204. return tokenDeclVar;
  3205. }
  3206. /**
  3207. * @brief Add variable initialization to $globalvarinit, $staticfieldinit or $instfieldinit function.
  3208. * @param initFunc = $globalvarinit, $staticfieldinit or $instfieldinit function
  3209. * @param left = variable being initialized
  3210. * @param init = null: initialize to default value
  3211. * else: initialize to this value
  3212. */
  3213. private void DoVarInit(TokenDeclVar initFunc, TokenLVal left, TokenRVal init)
  3214. {
  3215. // Make a statement that assigns the initialization value to the variable.
  3216. TokenStmt stmt;
  3217. if(init == null)
  3218. {
  3219. stmt = new TokenStmtVarIniDef(left) { var = left };
  3220. }
  3221. else
  3222. {
  3223. TokenKw op = new TokenKwAssign(left);
  3224. stmt = new TokenStmtRVal(init) { rVal = new TokenRValOpBin(left, op, init) };
  3225. }
  3226. // Add statement to end of initialization function.
  3227. // Be sure to execute them in same order as in source
  3228. // as some doofus scripts depend on it.
  3229. Token lastStmt = initFunc.body.statements;
  3230. if(lastStmt == null)
  3231. {
  3232. initFunc.body.statements = stmt;
  3233. }
  3234. else
  3235. {
  3236. Token nextStmt;
  3237. while((nextStmt = lastStmt.nextToken) != null)
  3238. {
  3239. lastStmt = nextStmt;
  3240. }
  3241. lastStmt.nextToken = stmt;
  3242. }
  3243. }
  3244. /**
  3245. * @brief parse function declaration argument list
  3246. * @param token = points to TokenKwParOpen
  3247. * @returns null: parse error
  3248. * else: points to token with types and names
  3249. * token = updated past the TokenKw{Brk,Par}Close
  3250. */
  3251. private TokenArgDecl ParseFuncArgs(ref Token token, Type end)
  3252. {
  3253. TokenArgDecl tokenArgDecl = new(token);
  3254. bool first = true;
  3255. do
  3256. {
  3257. token = token.nextToken;
  3258. if((token.GetType() == end) && first)
  3259. break;
  3260. if(!(token is TokenType type))
  3261. {
  3262. ErrorMsg(token, "expecting arg type");
  3263. token = SkipPastSemi(token);
  3264. return null;
  3265. }
  3266. token = token.nextToken;
  3267. if(token is not TokenName name)
  3268. {
  3269. ErrorMsg(token, "expecting arg name");
  3270. token = SkipPastSemi(token);
  3271. return null;
  3272. }
  3273. token = token.nextToken;
  3274. if(!tokenArgDecl.AddArg(type, name))
  3275. {
  3276. ErrorMsg(name, "duplicate arg name");
  3277. }
  3278. first = false;
  3279. } while(token is TokenKwComma);
  3280. if(token.GetType() != end)
  3281. {
  3282. ErrorMsg(token, "expecting comma or close bracket/paren");
  3283. token = SkipPastSemi(token);
  3284. return null;
  3285. }
  3286. token = token.nextToken;
  3287. return tokenArgDecl;
  3288. }
  3289. /**
  3290. * @brief parse right-hand value expression
  3291. * this is where arithmetic-like expressions are processed
  3292. * @param token = points to first token expression
  3293. * @param termTokenType = expression termination token type
  3294. * @returns null: not an RVal
  3295. * else: single token representing whole expression
  3296. * token = if termTokenType.Length == 1, points just past terminating token
  3297. * else, points right at terminating token
  3298. */
  3299. public TokenRVal ParseRVal(ref Token token, Type[] termTokenTypes)
  3300. {
  3301. // Start with pushing the first operand on operand stack.
  3302. BinOp binOps = null;
  3303. TokenRVal operands = GetOperand(ref token);
  3304. if(operands == null)
  3305. return null;
  3306. // Keep scanning until we hit the termination token.
  3307. while(true)
  3308. {
  3309. Type tokType = token.GetType();
  3310. for(int i = termTokenTypes.Length; --i >= 0;)
  3311. {
  3312. if(tokType == termTokenTypes[i])
  3313. goto done;
  3314. }
  3315. // Special form:
  3316. // <operand> is <typeexp>
  3317. if(token is TokenKwIs)
  3318. {
  3319. TokenRValIsType tokenRValIsType = new(token);
  3320. token = token.nextToken;
  3321. // Parse the <typeexp>.
  3322. tokenRValIsType.typeExp = ParseTypeExp(ref token);
  3323. if(tokenRValIsType.typeExp == null)
  3324. return null;
  3325. // Replace top operand with result of <operand> is <typeexp>
  3326. tokenRValIsType.rValExp = operands;
  3327. tokenRValIsType.nextToken = operands.nextToken;
  3328. operands = tokenRValIsType;
  3329. // token points just past <typeexp> so see if it is another operator.
  3330. continue;
  3331. }
  3332. // Peek at next operator.
  3333. BinOp binOp = GetOperator(ref token);
  3334. if(binOp == null)
  3335. return null;
  3336. // If there are stacked operators of higher or same precedence than new one,
  3337. // perform their computation then push result back on operand stack.
  3338. //
  3339. // higher or same = left-to-right application of operators
  3340. // eg, a - b - c becomes (a - b) - c
  3341. //
  3342. // higher precedence = right-to-left application of operators
  3343. // eg, a - b - c becomes a - (b - c)
  3344. //
  3345. // Now of course, there is some ugliness necessary:
  3346. // we want: a - b - c => (a - b) - c so we do 'higher or same'
  3347. // but we want: a += b = c => a += (b = c) so we do 'higher only'
  3348. //
  3349. // binOps is the first operator (or null if only one)
  3350. // binOp is the second operator (or first if only one)
  3351. while(binOps != null)
  3352. {
  3353. if(binOps.preced < binOp.preced)
  3354. break; // 1st operator lower than 2nd, so leave 1st on stack to do later
  3355. if(binOps.preced > binOp.preced)
  3356. goto do1st; // 1st op higher than 2nd, so we always do 1st op first
  3357. if(binOps.preced == ASNPR)
  3358. break; // equal preced, if assignment type, leave 1st on stack to do later
  3359. // if non-asn type, do 1st op first (ie left-to-right)
  3360. do1st:
  3361. TokenRVal result = PerformBinOp((TokenRVal)operands.prevToken, binOps, (TokenRVal)operands);
  3362. result.prevToken = operands.prevToken.prevToken;
  3363. operands = result;
  3364. binOps = binOps.pop;
  3365. }
  3366. // Handle conditional expression as a special form:
  3367. // <condexp> ? <trueexp> : <falseexp>
  3368. if(binOp.token is TokenKwQMark)
  3369. {
  3370. TokenRValCondExpr condExpr = new(binOp.token)
  3371. {
  3372. condExpr = operands,
  3373. trueExpr = ParseRVal(ref token, new Type[] { typeof(TokenKwColon) }),
  3374. falseExpr = ParseRVal(ref token, termTokenTypes),
  3375. prevToken = operands.prevToken
  3376. };
  3377. operands = condExpr;
  3378. termTokenTypes = Array.Empty<Type>();
  3379. goto done;
  3380. }
  3381. // Push new operator on its stack.
  3382. binOp.pop = binOps;
  3383. binOps = binOp;
  3384. // Push next operand on its stack.
  3385. TokenRVal operand = GetOperand(ref token);
  3386. if(operand == null)
  3387. return null;
  3388. operand.prevToken = operands;
  3389. operands = operand;
  3390. }
  3391. done:
  3392. // At end of expression, perform any stacked computations.
  3393. while(binOps != null)
  3394. {
  3395. TokenRVal result = PerformBinOp((TokenRVal)operands.prevToken, binOps, (TokenRVal)operands);
  3396. result.prevToken = operands.prevToken.prevToken;
  3397. operands = result;
  3398. binOps = binOps.pop;
  3399. }
  3400. // There should be exactly one remaining operand on the stack which is our final result.
  3401. if(operands.prevToken != null)
  3402. throw new Exception("too many operands");
  3403. // If only one terminator type possible, advance past the terminator.
  3404. if(termTokenTypes.Length == 1)
  3405. token = token.nextToken;
  3406. return operands;
  3407. }
  3408. private TokenTypeExp ParseTypeExp(ref Token token)
  3409. {
  3410. TokenTypeExp leftOperand = GetTypeExp(ref token);
  3411. if(leftOperand == null)
  3412. return null;
  3413. while((token is TokenKwAnd) || (token is TokenKwOr))
  3414. {
  3415. Token typeBinOp = token;
  3416. token = token.nextToken;
  3417. TokenTypeExp rightOperand = GetTypeExp(ref token);
  3418. if(rightOperand == null)
  3419. return null;
  3420. TokenTypeExpBinOp typeExpBinOp = new(typeBinOp)
  3421. {
  3422. leftOp = leftOperand,
  3423. binOp = typeBinOp,
  3424. rightOp = rightOperand
  3425. };
  3426. leftOperand = typeExpBinOp;
  3427. }
  3428. return leftOperand;
  3429. }
  3430. private TokenTypeExp GetTypeExp(ref Token token)
  3431. {
  3432. if(token is TokenKwTilde)
  3433. {
  3434. TokenTypeExpNot typeExpNot = new(token);
  3435. token = token.nextToken;
  3436. typeExpNot.typeExp = GetTypeExp(ref token);
  3437. if(typeExpNot.typeExp == null)
  3438. return null;
  3439. return typeExpNot;
  3440. }
  3441. if(token is TokenKwParOpen)
  3442. {
  3443. TokenTypeExpPar typeExpPar = new(token);
  3444. token = token.nextToken;
  3445. typeExpPar.typeExp = GetTypeExp(ref token);
  3446. if(typeExpPar.typeExp == null)
  3447. return null;
  3448. if(!(token is TokenKwParClose))
  3449. {
  3450. ErrorMsg(token, "expected close parenthesis");
  3451. token = SkipPastSemi(token);
  3452. return null;
  3453. }
  3454. return typeExpPar;
  3455. }
  3456. if(token is TokenKwUndef)
  3457. {
  3458. TokenTypeExpUndef typeExpUndef = new(token);
  3459. token = token.nextToken;
  3460. return typeExpUndef;
  3461. }
  3462. if(token is TokenType ttype)
  3463. {
  3464. TokenTypeExpType typeExpType = new(token) { typeToken = ttype };
  3465. token = token.nextToken;
  3466. return typeExpType;
  3467. }
  3468. ErrorMsg(token, "expected type");
  3469. token = SkipPastSemi(token);
  3470. return null;
  3471. }
  3472. /**
  3473. * @brief get a right-hand operand expression token
  3474. * @param token = first token of operand to parse
  3475. * @returns null: invalid operand
  3476. * else: token that bundles or wraps the operand
  3477. * token = points to token following last operand token
  3478. */
  3479. private TokenRVal GetOperand(ref Token token)
  3480. {
  3481. // Prefix unary operators (eg ++, --) requiring an L-value.
  3482. if((token is TokenKwIncr) || (token is TokenKwDecr))
  3483. {
  3484. TokenRValAsnPre asnPre = new(token) { prefix = token };
  3485. token = token.nextToken;
  3486. TokenRVal op = GetOperand(ref token);
  3487. if(op == null)
  3488. return null;
  3489. if(op is not TokenLVal)
  3490. {
  3491. ErrorMsg(op, "can pre{in,de}crement only an L-value");
  3492. return null;
  3493. }
  3494. asnPre.lVal = (TokenLVal)op;
  3495. return asnPre;
  3496. }
  3497. // Get the bulk of the operand, ie, without any of the below suffixes.
  3498. TokenRVal operand = GetOperandNoMods(ref token);
  3499. if(operand == null)
  3500. return null;
  3501. modifiers:
  3502. // If followed by '++' or '--', it is post-{in,de}cremented.
  3503. if((token is TokenKwIncr) || (token is TokenKwDecr))
  3504. {
  3505. TokenRValAsnPost asnPost = new(token) { postfix = token };
  3506. token = token.nextToken;
  3507. if(operand is not TokenLVal)
  3508. {
  3509. ErrorMsg(operand, "can post{in,de}crement only an L-value");
  3510. return null;
  3511. }
  3512. asnPost.lVal = (TokenLVal)operand;
  3513. return asnPost;
  3514. }
  3515. // If followed by a '.', it is an instance field or instance method reference.
  3516. if(token is TokenKwDot)
  3517. {
  3518. token = token.nextToken;
  3519. if(token is not TokenName)
  3520. {
  3521. ErrorMsg(token, ". must be followed by field/method name");
  3522. return null;
  3523. }
  3524. TokenLValIField field = new(token)
  3525. {
  3526. baseRVal = operand,
  3527. fieldName = (TokenName)token
  3528. };
  3529. operand = field;
  3530. token = token.nextToken;
  3531. goto modifiers;
  3532. }
  3533. // If followed by a '[', it is an array subscript.
  3534. if(token is TokenKwBrkOpen)
  3535. {
  3536. TokenLValArEle tokenLValArEle = new(token);
  3537. token = token.nextToken;
  3538. // Parse subscript(s) expression.
  3539. tokenLValArEle.subRVal = ParseRVal(ref token, brkCloseOnly);
  3540. if(tokenLValArEle.subRVal == null)
  3541. {
  3542. ErrorMsg(tokenLValArEle, "invalid subscript");
  3543. return null;
  3544. }
  3545. // See if comma-separated list of values.
  3546. int numSubscripts = SplitCommaRVals(tokenLValArEle.subRVal, out TokenRVal subscriptRVals);
  3547. if (numSubscripts > 1)
  3548. {
  3549. // If so, put the values in an LSL_List object.
  3550. TokenRValList rValList = new(tokenLValArEle)
  3551. {
  3552. rVal = subscriptRVals,
  3553. nItems = numSubscripts
  3554. };
  3555. tokenLValArEle.subRVal = rValList;
  3556. }
  3557. // Either way, save array variable name
  3558. // and substitute whole reference for L-value
  3559. tokenLValArEle.baseRVal = operand;
  3560. operand = tokenLValArEle;
  3561. goto modifiers;
  3562. }
  3563. // If followed by a '(', it is a function/method call.
  3564. if(token is TokenKwParOpen)
  3565. {
  3566. operand = ParseRValCall(ref token, operand);
  3567. goto modifiers;
  3568. }
  3569. // If 'new' arraytipe '{', it is an array initializer.
  3570. if((token is TokenKwBrcOpen) && (operand is TokenLValSField) &&
  3571. (((TokenLValSField)operand).fieldName.val == "$new") &&
  3572. ((TokenLValSField)operand).baseType.ToString().EndsWith("]"))
  3573. {
  3574. operand = ParseRValNewArIni(ref token, (TokenLValSField)operand);
  3575. if(operand != null)
  3576. goto modifiers;
  3577. }
  3578. return operand;
  3579. }
  3580. /**
  3581. * @brief same as GetOperand() except doesn't check for any modifiers
  3582. */
  3583. private TokenRVal GetOperandNoMods(ref Token token)
  3584. {
  3585. // Simple unary operators.
  3586. if((token is TokenKwSub) ||
  3587. (token is TokenKwTilde) ||
  3588. (token is TokenKwExclam))
  3589. {
  3590. Token uop = token;
  3591. token = token.nextToken;
  3592. TokenRVal rVal = GetOperand(ref token);
  3593. if(rVal == null)
  3594. return null;
  3595. return PerformUnOp(uop, rVal);
  3596. }
  3597. // Type casting.
  3598. if((token is TokenKwParOpen) &&
  3599. (token.nextToken is TokenType) &&
  3600. (token.nextToken.nextToken is TokenKwParClose))
  3601. {
  3602. TokenType type = (TokenType)token.nextToken;
  3603. token = token.nextToken.nextToken.nextToken;
  3604. TokenRVal rVal = GetOperand(ref token);
  3605. if(rVal == null)
  3606. return null;
  3607. return new TokenRValCast(type, rVal);
  3608. }
  3609. // Parenthesized expression.
  3610. if(token is TokenKwParOpen)
  3611. {
  3612. return ParseRValParen(ref token);
  3613. }
  3614. // Constants.
  3615. if(token is TokenChar tchar)
  3616. {
  3617. TokenRValConst rValConst = new(token, tchar.val);
  3618. token = token.nextToken;
  3619. return rValConst;
  3620. }
  3621. if(token is TokenFloat tfloat)
  3622. {
  3623. TokenRValConst rValConst = new(token, tfloat.val);
  3624. token = token.nextToken;
  3625. return rValConst;
  3626. }
  3627. if(token is TokenInt tint)
  3628. {
  3629. TokenRValConst rValConst = new(token, tint.val);
  3630. token = token.nextToken;
  3631. return rValConst;
  3632. }
  3633. if(token is TokenStr tstr)
  3634. {
  3635. TokenRValConst rValConst = new(token, tstr.val);
  3636. token = token.nextToken;
  3637. return rValConst;
  3638. }
  3639. if(token is TokenKwUndef tundef)
  3640. {
  3641. TokenRValUndef rValUndef = new(tundef);
  3642. token = token.nextToken;
  3643. return rValUndef;
  3644. }
  3645. // '<'value,...'>', ie, rotation or vector
  3646. if(token is TokenKwCmpLT)
  3647. {
  3648. Token openBkt = token;
  3649. token = token.nextToken;
  3650. TokenRVal rValAll = ParseRVal(ref token, cmpGTOnly);
  3651. if(rValAll == null)
  3652. return null;
  3653. int nVals = SplitCommaRVals(rValAll, out TokenRVal rVals);
  3654. switch (nVals)
  3655. {
  3656. case 3:
  3657. {
  3658. return new TokenRValVec(openBkt)
  3659. {
  3660. xRVal = rVals,
  3661. yRVal = (TokenRVal)rVals.nextToken,
  3662. zRVal = (TokenRVal)rVals.nextToken.nextToken
  3663. };
  3664. }
  3665. case 4:
  3666. {
  3667. return new TokenRValRot(openBkt)
  3668. {
  3669. xRVal = rVals,
  3670. yRVal = (TokenRVal)rVals.nextToken,
  3671. zRVal = (TokenRVal)rVals.nextToken.nextToken,
  3672. wRVal = (TokenRVal)rVals.nextToken.nextToken.nextToken
  3673. };
  3674. }
  3675. default:
  3676. {
  3677. ErrorMsg(openBkt, "bad rotation/vector");
  3678. token = SkipPastSemi(token);
  3679. return null;
  3680. }
  3681. }
  3682. }
  3683. // '['value,...']', ie, list
  3684. if(token is TokenKwBrkOpen)
  3685. {
  3686. TokenRValList rValList = new(token);
  3687. token = token.nextToken;
  3688. if(token is TokenKwBrkClose)
  3689. {
  3690. token = token.nextToken; // empty list
  3691. }
  3692. else
  3693. {
  3694. TokenRVal rValAll = ParseRVal(ref token, brkCloseOnly);
  3695. if(rValAll == null)
  3696. return null;
  3697. rValList.nItems = SplitCommaRVals(rValAll, out rValList.rVal);
  3698. }
  3699. return rValList;
  3700. }
  3701. // Maybe we have <type>.<name> referencing a static field or method of some type.
  3702. if((token is TokenType) && (token.nextToken is TokenKwDot) && (token.nextToken.nextToken is TokenName))
  3703. {
  3704. TokenLValSField field = new(token.nextToken.nextToken)
  3705. {
  3706. baseType = (TokenType)token,
  3707. fieldName = (TokenName)token.nextToken.nextToken
  3708. };
  3709. token = token.nextToken.nextToken.nextToken;
  3710. return field;
  3711. }
  3712. // Maybe we have 'this' referring to the object of the instance method.
  3713. if(token is TokenKwThis)
  3714. {
  3715. if((currentDeclSDType == null) || currentDeclSDType is not TokenDeclSDTypeClass)
  3716. {
  3717. ErrorMsg(token, "using 'this' outside class definition");
  3718. token = SkipPastSemi(token);
  3719. return null;
  3720. }
  3721. TokenRValThis zhis = new(token, (TokenDeclSDTypeClass)currentDeclSDType);
  3722. token = token.nextToken;
  3723. return zhis;
  3724. }
  3725. // Maybe we have 'base' referring to a field/method of the extended class.
  3726. if(token is TokenKwBase)
  3727. {
  3728. if((currentDeclFunc == null) || (currentDeclFunc.sdtClass == null) || !(currentDeclFunc.sdtClass is TokenDeclSDTypeClass))
  3729. {
  3730. ErrorMsg(token, "using 'base' outside method");
  3731. token = SkipPastSemi(token);
  3732. return null;
  3733. }
  3734. if(token.nextToken is not TokenKwDot || token.nextToken.nextToken is not TokenName nextnexttname)
  3735. {
  3736. ErrorMsg(token, "base must be followed by . then field or method name");
  3737. TokenRValThis zhis = new(token, (TokenDeclSDTypeClass)currentDeclFunc.sdtClass);
  3738. token = token.nextToken;
  3739. return zhis;
  3740. }
  3741. TokenLValBaseField baseField = new(token, nextnexttname, (TokenDeclSDTypeClass)currentDeclFunc.sdtClass);
  3742. token = token.nextToken.nextToken.nextToken;
  3743. return baseField;
  3744. }
  3745. // Maybe we have 'new <script-defined-type>' saying to create an object instance.
  3746. // This ends up generating a call to static function <script-defined-type>.$new(...)
  3747. // whose CIL code is generated by GenerateNewobjBody().
  3748. if(token is TokenKwNew)
  3749. {
  3750. if(token.nextToken is not TokenType)
  3751. {
  3752. ErrorMsg(token.nextToken, "new must be followed by type");
  3753. token = SkipPastSemi(token);
  3754. return null;
  3755. }
  3756. TokenLValSField field = new(token.nextToken.nextToken)
  3757. {
  3758. baseType = (TokenType)token.nextToken,
  3759. fieldName = new TokenName(token, "$new")
  3760. };
  3761. token = token.nextToken.nextToken;
  3762. return field;
  3763. }
  3764. // All we got left is <name>, eg, arg, function, global or local variable reference
  3765. if(token is TokenName)
  3766. {
  3767. TokenLValName name = new((TokenName)token, tokenScript.variablesStack);
  3768. token = token.nextToken;
  3769. return name;
  3770. }
  3771. // Who knows what it is supposed to be?
  3772. ErrorMsg(token, "invalid operand token");
  3773. token = SkipPastSemi(token);
  3774. return null;
  3775. }
  3776. /**
  3777. * @brief Parse a call expression
  3778. * @param token = points to arg list '('
  3779. * @param meth = points to method name being called
  3780. * @returns call expression value
  3781. * token = points just past arg list ')'
  3782. */
  3783. private TokenRValCall ParseRValCall(ref Token token, TokenRVal meth)
  3784. {
  3785. // Set up basic function call struct with function name.
  3786. TokenRValCall rValCall = new(token) { meth = meth };
  3787. // Parse the call parameters, if any.
  3788. token = token.nextToken;
  3789. if(token is TokenKwParClose)
  3790. {
  3791. token = token.nextToken;
  3792. }
  3793. else
  3794. {
  3795. rValCall.args = ParseRVal(ref token, parCloseOnly);
  3796. if(rValCall.args == null)
  3797. return null;
  3798. rValCall.nArgs = SplitCommaRVals(rValCall.args, out rValCall.args);
  3799. }
  3800. currentDeclFunc.unknownTrivialityCalls.AddLast(rValCall);
  3801. return rValCall;
  3802. }
  3803. /**
  3804. * @brief decode binary operator token
  3805. * @param token = points to token to decode
  3806. * @returns null: invalid operator token
  3807. * else: operator token and precedence
  3808. */
  3809. private BinOp GetOperator(ref Token token)
  3810. {
  3811. BinOp binOp = new();
  3812. if(precedence.TryGetValue(token.GetType(), out binOp.preced))
  3813. {
  3814. binOp.token = (TokenKw)token;
  3815. token = token.nextToken;
  3816. return binOp;
  3817. }
  3818. if((token is TokenKwSemi) || (token is TokenKwBrcOpen) || (token is TokenKwBrcClose))
  3819. {
  3820. ErrorMsg(token, "premature expression end");
  3821. }
  3822. else
  3823. {
  3824. ErrorMsg(token, "invalid operator");
  3825. }
  3826. token = SkipPastSemi(token);
  3827. return null;
  3828. }
  3829. private class BinOp
  3830. {
  3831. public BinOp pop;
  3832. public TokenKw token;
  3833. public int preced;
  3834. }
  3835. /**
  3836. * @brief Return an R-value expression token that will be used to
  3837. * generate code to perform the operation at runtime.
  3838. * @param left = left-hand operand
  3839. * @param binOp = operator
  3840. * @param right = right-hand operand
  3841. * @returns resultant expression
  3842. */
  3843. private static TokenRVal PerformBinOp(TokenRVal left, BinOp binOp, TokenRVal right)
  3844. {
  3845. return new TokenRValOpBin(left, binOp.token, right);
  3846. }
  3847. /**
  3848. * @brief Return an R-value expression token that will be used to
  3849. * generate code to perform the operation at runtime.
  3850. * @param unOp = operator
  3851. * @param right = right-hand operand
  3852. * @returns resultant constant or expression
  3853. */
  3854. private static TokenRVal PerformUnOp(Token unOp, TokenRVal right)
  3855. {
  3856. return new TokenRValOpUn((TokenKw)unOp, right);
  3857. }
  3858. /**
  3859. * @brief Parse an array initialization expression.
  3860. * @param token = points to '{' on entry
  3861. * @param newCall = encapsulates a '$new' call
  3862. * @return resultant operand encapsulating '$new' call and initializers
  3863. * token = points just past terminating '}'
  3864. * ...or null if parse error
  3865. */
  3866. private TokenRVal ParseRValNewArIni(ref Token token, TokenLValSField newCall)
  3867. {
  3868. Stack<TokenList> stack = new();
  3869. TokenRValNewArIni arini = new(token) { arrayType = newCall.baseType };
  3870. TokenList values = null;
  3871. while(true)
  3872. {
  3873. // open brace means start a (sub-)list
  3874. if(token is TokenKwBrcOpen)
  3875. {
  3876. stack.Push(values);
  3877. values = new TokenList(token);
  3878. token = token.nextToken;
  3879. continue;
  3880. }
  3881. // close brace means end of (sub-)list
  3882. // if final '}' all done parsing
  3883. if(token is TokenKwBrcClose)
  3884. {
  3885. token = token.nextToken; // skip over the '}'
  3886. TokenList innerds = values; // save the list just closed
  3887. arini.valueList = innerds; // it's the top list if it's the last closed
  3888. values = stack.Pop(); // pop to next outer list
  3889. if(values == null)
  3890. return arini; // final '}', we are done
  3891. values.tl.Add(innerds); // put the inner list on end of outer list
  3892. if(token is TokenKwComma)
  3893. { // should have a ',' or '}' next
  3894. token = token.nextToken; // skip over the ','
  3895. }
  3896. else if(!(token is TokenKwBrcClose))
  3897. {
  3898. ErrorMsg(token, "expecting , or } after sublist");
  3899. }
  3900. continue;
  3901. }
  3902. // this is a comma that doesn't have a value expression before it
  3903. // so we take it to mean skip initializing element (leave it zeroes/null etc)
  3904. if(token is TokenKwComma)
  3905. {
  3906. values.tl.Add(token);
  3907. token = token.nextToken;
  3908. continue;
  3909. }
  3910. // parse value expression and skip terminating ',' if any
  3911. TokenRVal append = ParseRVal(ref token, commaOrBrcClose);
  3912. if(append == null)
  3913. return null;
  3914. values.tl.Add(append);
  3915. if(token is TokenKwComma)
  3916. {
  3917. token = token.nextToken;
  3918. }
  3919. }
  3920. }
  3921. /**
  3922. * @brief parse out a parenthesized expression.
  3923. * @param token = points to open parenthesis
  3924. * @returns null: invalid expression
  3925. * else: parenthesized expression token or constant token
  3926. * token = points past the close parenthesis
  3927. */
  3928. private TokenRValParen ParseRValParen(ref Token token)
  3929. {
  3930. if(!(token is TokenKwParOpen))
  3931. {
  3932. ErrorMsg(token, "expecting (");
  3933. token = SkipPastSemi(token);
  3934. return null;
  3935. }
  3936. TokenRValParen tokenRValParen = new(token);
  3937. token = token.nextToken;
  3938. tokenRValParen.rVal = ParseRVal(ref token, parCloseOnly);
  3939. if(tokenRValParen.rVal == null)
  3940. return null;
  3941. return tokenRValParen;
  3942. }
  3943. /**
  3944. * @brief Split a comma'd RVal into separate expressions
  3945. * @param rValAll = expression containing commas
  3946. * @returns number of comma separated values
  3947. * rVals = values in a null-terminated list linked by rVals.nextToken
  3948. */
  3949. private int SplitCommaRVals(TokenRVal rValAll, out TokenRVal rVals)
  3950. {
  3951. if(rValAll is not TokenRValOpBin opBin || opBin.opcode is not TokenKwComma)
  3952. {
  3953. rVals = rValAll;
  3954. if(rVals.nextToken != null)
  3955. throw new Exception("expected null");
  3956. return 1;
  3957. }
  3958. int leftCount = SplitCommaRVals(opBin.rValLeft, out TokenRVal rValLeft);
  3959. int rightCount = SplitCommaRVals(opBin.rValRight, out TokenRVal rValRight);
  3960. rVals = rValLeft;
  3961. while(rValLeft.nextToken != null)
  3962. rValLeft = (TokenRVal)rValLeft.nextToken;
  3963. rValLeft.nextToken = rValRight;
  3964. return leftCount + rightCount;
  3965. }
  3966. /**
  3967. * @brief output error message and remember that there is an error.
  3968. * @param token = what token is associated with the error
  3969. * @param message = error message string
  3970. */
  3971. private void ErrorMsg(Token token, string message)
  3972. {
  3973. if(!errors || (token.file != lastErrorFile) || (token.line > lastErrorLine))
  3974. {
  3975. errors = true;
  3976. lastErrorFile = token.file;
  3977. lastErrorLine = token.line;
  3978. token.ErrorMsg(message);
  3979. }
  3980. }
  3981. /**
  3982. * @brief Skip past the next semicolon (or matched braces)
  3983. * @param token = points to token to skip over
  3984. * @returns token just after the semicolon or close brace
  3985. */
  3986. private Token SkipPastSemi(Token token)
  3987. {
  3988. int braceLevel = 0;
  3989. while(!(token is TokenEnd))
  3990. {
  3991. if((token is TokenKwSemi) && (braceLevel == 0))
  3992. {
  3993. return token.nextToken;
  3994. }
  3995. if(token is TokenKwBrcOpen)
  3996. {
  3997. braceLevel++;
  3998. }
  3999. if((token is TokenKwBrcClose) && (--braceLevel <= 0))
  4000. {
  4001. return token.nextToken;
  4002. }
  4003. token = token.nextToken;
  4004. }
  4005. return token;
  4006. }
  4007. }
  4008. /**
  4009. * @brief Script-defined type declarations
  4010. */
  4011. public abstract class TokenDeclSDType: Token
  4012. {
  4013. protected const byte CLASS = 0;
  4014. protected const byte DELEGATE = 1;
  4015. protected const byte INTERFACE = 2;
  4016. protected const byte TYPEDEF = 3;
  4017. // stuff that gets cloned/copied/transformed when instantiating a generic
  4018. // see InstantiateGeneric() below
  4019. public TokenDeclSDType outerSDType; // null if top-level
  4020. // else points to defining script-defined type
  4021. public Dictionary<string, TokenDeclSDType> innerSDTypes = new();
  4022. // indexed by shortName
  4023. public Token begToken; // token that begins the definition (might be this or something like 'public')
  4024. public Token endToken; // the '}' or ';' that ends the definition
  4025. // generic instantiation assumes none of the rest needs to be cloned (well except for the shortName)
  4026. public int sdTypeIndex = -1; // index in scriptObjCode.sdObjTypesIndx[] array
  4027. public TokenDeclSDTypeClass extends; // only non-null for TokenDeclSDTypeClass's
  4028. public uint accessLevel; // SDT_PRIVATE, SDT_PROTECTED or SDT_PUBLIC
  4029. // ... all top-level types are SDT_PUBLIC
  4030. public VarDict members = new (false); // declared fields, methods, properties if any
  4031. public Dictionary<string, int> genParams; // list of parameters for generic prototypes
  4032. // null for non-generic prototypes
  4033. // eg, for 'Dictionary<K,V>'
  4034. // ...genParams gives K->0; V->1
  4035. public bool isPartial; // was declared with 'partial' keyword
  4036. // classes only, all others always false
  4037. /*
  4038. * Name of the type.
  4039. * shortName = doesn't include outer class type names
  4040. * eg, 'Engine' for non-generic
  4041. * 'Dictionary<,>' for generic prototype
  4042. * 'Dictionary<string,integer>' for generic instantiation
  4043. * longName = includes all outer class type names if any
  4044. */
  4045. private TokenName _shortName;
  4046. private TokenName _longName;
  4047. public TokenName shortName
  4048. {
  4049. get
  4050. {
  4051. return _shortName;
  4052. }
  4053. set
  4054. {
  4055. _shortName = value;
  4056. _longName = null;
  4057. }
  4058. }
  4059. public TokenName longName
  4060. {
  4061. get
  4062. {
  4063. if(_longName == null)
  4064. {
  4065. _longName = _shortName;
  4066. if(outerSDType != null)
  4067. {
  4068. _longName = new TokenName(_shortName, outerSDType.longName.val + "." + _shortName.val);
  4069. }
  4070. }
  4071. return _longName;
  4072. }
  4073. }
  4074. /*
  4075. * Dictionary used when reading from object file that holds all script-defined types.
  4076. * Not complete though until all types have been read from the object file.
  4077. */
  4078. private Dictionary<string, TokenDeclSDType> sdTypes;
  4079. public TokenDeclSDType(Token t) : base(t) { }
  4080. protected abstract TokenDeclSDType MakeBlank(TokenName shortName);
  4081. public abstract TokenType MakeRefToken(Token t);
  4082. public abstract Type GetSysType();
  4083. public abstract void WriteToFile(BinaryWriter objFileWriter);
  4084. public abstract void ReadFromFile(BinaryReader objFileReader, TextWriter asmFileWriter);
  4085. /**
  4086. * @brief Given that this is a generic prototype, apply the supplied genArgs
  4087. * to create an equivalent instantiated non-generic. This basically
  4088. * makes a copy replacing all the parameter types with the actual
  4089. * argument types.
  4090. * @param this = the prototype to be instantiated, eg, 'Dictionary<string,integer>.Converter'
  4091. * @param name = short name with arguments, eg, 'Converter<float>'.
  4092. * @param genArgs = argument types of just this level, eg, 'float'.
  4093. * @returns clone of this but with arguments applied and spliced in source token stream
  4094. */
  4095. public TokenDeclSDType InstantiateGeneric(string name, TokenType[] genArgs, ScriptReduce reduce)
  4096. {
  4097. // Malloc the struct and give it a name.
  4098. TokenDeclSDType instdecl = this.MakeBlank(new TokenName(this, name));
  4099. // If the original had an outer type, then so does the new one.
  4100. // The outer type will never be a generic prototype, eg, if this
  4101. // is 'ValueList' it will always be inside 'Dictionary<string,integer>'
  4102. // not 'Dictionary' at this point.
  4103. if((this.outerSDType != null) && (this.outerSDType.genParams != null))
  4104. throw new Exception();
  4105. instdecl.outerSDType = this.outerSDType;
  4106. // The generic prototype may have stuff like 'public' just before it and we need to copy that too.
  4107. Token prefix = this;
  4108. while((prefix = prefix.prevToken) != null)
  4109. {
  4110. if(prefix is not TokenKwPublic && prefix is not TokenKwProtected && prefix is not TokenKwPrivate)
  4111. break;
  4112. }
  4113. this.begToken = prefix.nextToken;
  4114. // Splice in a copy of the prefix tokens, just before the beginning token of prototype (this.begToken).
  4115. while((prefix = prefix.nextToken) != this)
  4116. {
  4117. SpliceSourceToken(prefix.CopyToken(prefix));
  4118. }
  4119. // Splice instantiation (instdecl) in just before the beginning token of prototype (this.begToken).
  4120. SpliceSourceToken(instdecl);
  4121. // Now for the fun part... Copy the rest of the prototype body to the
  4122. // instantiated body, replacing all generic parameter type tokens with
  4123. // the corresponding generic argument types. Note that the parameters
  4124. // are numbered starting with the outermost so we need the full genArgs
  4125. // array. Eg if we are doing 'Converter<V=float>' from
  4126. // 'Dictionary<T=string,U=integer>.Converter<V=float>', any V's are
  4127. // numbered [2]. Any [0]s or [1]s should be gone by now but it doesn't
  4128. // matter.
  4129. Token it, pt;
  4130. TokenDeclSDType innerProto = this;
  4131. TokenDeclSDType innerInst = instdecl;
  4132. for(pt = this; (pt = pt.nextToken) != this.endToken;)
  4133. {
  4134. // Coming across a sub-type's declaration involves a deep copy of the
  4135. // declaration token. Fortunately we are early on in parsing, so there
  4136. // really isn't much to copy:
  4137. // 1) short name is the same, eg, doing List of Dictionary<string,integer>.List is same short name as Dictionary<T,U>.List
  4138. // if generic, eg doing Converter<W> of Dictionary<T,U>.Converter<W>, we have to manually copy the W as well.
  4139. // 2) outerSDType is transformed from Dictionary<T,U> to Dictionary<string,integer>.
  4140. // 3) innerSDTypes is rebuilt when/if we find classes that are inner to this one.
  4141. if(pt is TokenDeclSDType ptSDType)
  4142. {
  4143. // Make a new TokenDeclSDType{Class,Delegate,Interface}.
  4144. TokenDeclSDType itSDType = ptSDType.MakeBlank(new TokenName(ptSDType.shortName, ptSDType.shortName.val));
  4145. // Set up the transformed outerSDType.
  4146. // Eg, if we are creating Enumerator of Dictionary<string,integer>.Enumerator,
  4147. // innerProto = Dictionary<T,U> and innerInst = Dictionary<string,integer>.
  4148. itSDType.outerSDType = innerInst;
  4149. // This clone is an inner type of its next outer level.
  4150. reduce.CatalogSDTypeDecl(itSDType);
  4151. // We need to manually copy any generic parameters of the class declaration being cloned.
  4152. // eg, if we are cloning Converter<W>, this is where the W gets copied.
  4153. // Since it is an immutable array of strings, just copy the array pointer, if any.
  4154. itSDType.genParams = ptSDType.genParams;
  4155. // We are now processing tokens for this cloned type declaration.
  4156. innerProto = ptSDType;
  4157. innerInst = itSDType;
  4158. // Splice this clone token in.
  4159. it = itSDType;
  4160. }
  4161. // Check for an generic parameter to substitute out.
  4162. else if((pt is TokenName namept) && this.genParams.TryGetValue(namept.val, out int index))
  4163. {
  4164. it = genArgs[index].CopyToken(pt);
  4165. }
  4166. // Everything else is a simple copy.
  4167. else
  4168. it = pt.CopyToken(pt);
  4169. // Whatever we came up with, splice it into the source token stream.
  4170. SpliceSourceToken(it);
  4171. // Maybe we just finished copying an inner type definition.
  4172. // If so, remember where it ends and pop it from the stack.
  4173. if(innerProto.endToken == pt)
  4174. {
  4175. innerInst.endToken = it;
  4176. innerProto = innerProto.outerSDType;
  4177. innerInst = innerInst.outerSDType;
  4178. }
  4179. }
  4180. // Clone and insert the terminator, either '}' or ';'
  4181. it = pt.CopyToken(pt);
  4182. SpliceSourceToken(it);
  4183. instdecl.endToken = it;
  4184. return instdecl;
  4185. }
  4186. /**
  4187. * @brief Splice a source token in just before the type's beginning keyword.
  4188. */
  4189. private void SpliceSourceToken(Token it)
  4190. {
  4191. it.nextToken = this.begToken;
  4192. (it.prevToken = this.begToken.prevToken).nextToken = it;
  4193. this.begToken.prevToken = it;
  4194. }
  4195. /**
  4196. * @brief Read one of these in from the object file.
  4197. * @param sdTypes = dictionary of script-defined types, not yet complete
  4198. * @param name = script-visible name of this type
  4199. * @param objFileReader = reads from the object file
  4200. * @param asmFileWriter = writes to the disassembly file (might be null)
  4201. */
  4202. public static TokenDeclSDType ReadFromFile(Dictionary<string, TokenDeclSDType> sdTypes, string name,
  4203. BinaryReader objFileReader, TextWriter asmFileWriter)
  4204. {
  4205. string file = objFileReader.ReadString();
  4206. int line = objFileReader.ReadInt32();
  4207. int posn = objFileReader.ReadInt32();
  4208. byte code = objFileReader.ReadByte();
  4209. TokenName n = new(null, file, line, posn, name);
  4210. TokenDeclSDType sdt;
  4211. switch(code)
  4212. {
  4213. case CLASS:
  4214. {
  4215. sdt = new TokenDeclSDTypeClass(n, false);
  4216. break;
  4217. }
  4218. case DELEGATE:
  4219. {
  4220. sdt = new TokenDeclSDTypeDelegate(n);
  4221. break;
  4222. }
  4223. case INTERFACE:
  4224. {
  4225. sdt = new TokenDeclSDTypeInterface(n);
  4226. break;
  4227. }
  4228. case TYPEDEF:
  4229. {
  4230. sdt = new TokenDeclSDTypeTypedef(n);
  4231. break;
  4232. }
  4233. default:
  4234. throw new Exception();
  4235. }
  4236. sdt.sdTypes = sdTypes;
  4237. sdt.sdTypeIndex = objFileReader.ReadInt32();
  4238. sdt.ReadFromFile(objFileReader, asmFileWriter);
  4239. return sdt;
  4240. }
  4241. /**
  4242. * @brief Convert a typename string to a type token
  4243. * @param name = script-visible name of token to create,
  4244. * either a script-defined type or an LSL-defined type
  4245. * @returns type token
  4246. */
  4247. protected TokenType MakeTypeToken(string name)
  4248. {
  4249. if (sdTypes.TryGetValue(name, out TokenDeclSDType sdtdecl))
  4250. return sdtdecl.MakeRefToken(this);
  4251. return TokenType.FromLSLType(this, name);
  4252. }
  4253. // debugging - returns, eg, 'Dictionary<T,U>.Enumerator.Node'
  4254. public override void DebString(StringBuilder sb)
  4255. {
  4256. // get long name broken down into segments from outermost to this
  4257. Stack<TokenDeclSDType> declStack = new();
  4258. for(TokenDeclSDType decl = this; decl != null; decl = decl.outerSDType)
  4259. {
  4260. declStack.Push(decl);
  4261. }
  4262. // output each segment's name followed by our args for it
  4263. // starting with outermost and ending with this
  4264. while(declStack.Count > 0)
  4265. {
  4266. TokenDeclSDType decl = declStack.Pop();
  4267. sb.Append(decl.shortName.val);
  4268. if(decl.genParams != null)
  4269. {
  4270. sb.Append('<');
  4271. string[] parms = new string[decl.genParams.Count];
  4272. foreach(KeyValuePair<string, int> kvp in decl.genParams)
  4273. {
  4274. parms[kvp.Value] = kvp.Key;
  4275. }
  4276. for(int j = 0; j < parms.Length;)
  4277. {
  4278. sb.Append(parms[j]);
  4279. if(++j < parms.Length)
  4280. sb.Append(',');
  4281. }
  4282. sb.Append('>');
  4283. }
  4284. if(declStack.Count > 0)
  4285. sb.Append('.');
  4286. }
  4287. }
  4288. }
  4289. public class TokenDeclSDTypeClass: TokenDeclSDType
  4290. {
  4291. public List<TokenDeclSDTypeInterface> implements = new();
  4292. public TokenDeclVar instFieldInit; // $instfieldinit function to do instance field initializations
  4293. public TokenDeclVar staticFieldInit; // $staticfieldinit function to do static field initializations
  4294. public Dictionary<string, int> intfIndices = new(); // longname => this.iFaces index
  4295. public TokenDeclSDTypeInterface[] iFaces; // array of implemented interfaces
  4296. // low-end entries copied from rootward classes
  4297. public TokenDeclVar[][] iImplFunc; // iImplFunc[i][j]:
  4298. // low-end [i] entries copied from rootward classes
  4299. // i = interface number from this.intfIndices[name]
  4300. // j = method of interface from iface.methods[name].vTableIndex
  4301. public TokenType arrayOfType; // if array, it's an array of this type, else null
  4302. public int arrayOfRank; // if array, it has this number of dimensions, else zero
  4303. public bool slotsAssigned; // set true when slots have been assigned...
  4304. public XMRInstArSizes instSizes = new();
  4305. // number of instance fields of various types
  4306. public int numVirtFuncs; // number of virtual functions
  4307. public int numInterfaces; // number of implemented interfaces
  4308. private string extendsStr;
  4309. private string arrayOfTypeStr;
  4310. private List<StackedMethod> stackedMethods;
  4311. private List<StackedIFace> stackedIFaces;
  4312. public DynamicMethod[] vDynMeths; // virtual method entrypoints
  4313. public Type[] vMethTypes; // virtual method delegate types
  4314. public DynamicMethod[][] iDynMeths; // interface method entrypoints
  4315. public Type[][] iMethTypes; // interface method types
  4316. // low-end [i] entries copied from rootward classes
  4317. // i = interface number from this.intfIndices[name]
  4318. // j = method of interface from iface.methods[name].vTableIndex
  4319. public TokenDeclSDTypeClass(TokenName shortName, bool isPartial) : base(shortName)
  4320. {
  4321. this.shortName = shortName;
  4322. this.isPartial = isPartial;
  4323. }
  4324. protected override TokenDeclSDType MakeBlank(TokenName shortName)
  4325. {
  4326. return new TokenDeclSDTypeClass(shortName, false);
  4327. }
  4328. public override TokenType MakeRefToken(Token t)
  4329. {
  4330. return new TokenTypeSDTypeClass(t, this);
  4331. }
  4332. public override Type GetSysType()
  4333. {
  4334. return typeof(XMRSDTypeClObj);
  4335. }
  4336. /**
  4337. * @brief See if the class implements the interface.
  4338. * Do a recursive (deep) check in all rootward classes.
  4339. */
  4340. public bool CanCastToIntf(TokenDeclSDTypeInterface intf)
  4341. {
  4342. if(this.implements.Contains(intf))
  4343. return true;
  4344. if(this.extends == null)
  4345. return false;
  4346. return this.extends.CanCastToIntf(intf);
  4347. }
  4348. /**
  4349. * @brief Write enough out so we can reconstruct with ReadFromFile.
  4350. */
  4351. public override void WriteToFile(BinaryWriter objFileWriter)
  4352. {
  4353. objFileWriter.Write(this.file);
  4354. objFileWriter.Write(this.line);
  4355. objFileWriter.Write(this.posn);
  4356. objFileWriter.Write((byte)CLASS);
  4357. objFileWriter.Write(this.sdTypeIndex);
  4358. this.instSizes.WriteToFile(objFileWriter);
  4359. objFileWriter.Write(numVirtFuncs);
  4360. if(extends == null)
  4361. {
  4362. objFileWriter.Write("");
  4363. }
  4364. else
  4365. {
  4366. objFileWriter.Write(extends.longName.val);
  4367. }
  4368. objFileWriter.Write(arrayOfRank);
  4369. if(arrayOfRank > 0)
  4370. objFileWriter.Write(arrayOfType.ToString());
  4371. foreach(TokenDeclVar meth in members)
  4372. {
  4373. if((meth.retType != null) && (meth.vTableIndex >= 0))
  4374. {
  4375. objFileWriter.Write(meth.vTableIndex);
  4376. objFileWriter.Write(meth.GetObjCodeName());
  4377. objFileWriter.Write(meth.GetDelType().decl.GetWholeSig());
  4378. }
  4379. }
  4380. objFileWriter.Write(-1);
  4381. int numIFaces = iImplFunc.Length;
  4382. objFileWriter.Write(numIFaces);
  4383. for(int i = 0; i < numIFaces; i++)
  4384. {
  4385. objFileWriter.Write(iFaces[i].longName.val);
  4386. TokenDeclVar[] meths = iImplFunc[i];
  4387. int numMeths = 0;
  4388. if(meths != null)
  4389. numMeths = meths.Length;
  4390. objFileWriter.Write(numMeths);
  4391. for(int j = 0; j < numMeths; j++)
  4392. {
  4393. TokenDeclVar meth = meths[j];
  4394. objFileWriter.Write(meth.vTableIndex);
  4395. objFileWriter.Write(meth.GetObjCodeName());
  4396. objFileWriter.Write(meth.GetDelType().decl.GetWholeSig());
  4397. }
  4398. }
  4399. }
  4400. /**
  4401. * @brief Reconstruct from the file.
  4402. */
  4403. public override void ReadFromFile(BinaryReader objFileReader, TextWriter asmFileWriter)
  4404. {
  4405. instSizes.ReadFromFile(objFileReader);
  4406. numVirtFuncs = objFileReader.ReadInt32();
  4407. extendsStr = objFileReader.ReadString();
  4408. arrayOfRank = objFileReader.ReadInt32();
  4409. if(arrayOfRank > 0)
  4410. arrayOfTypeStr = objFileReader.ReadString();
  4411. if(asmFileWriter != null)
  4412. {
  4413. instSizes.WriteAsmFile(asmFileWriter, extendsStr + "." + shortName.val + ".numInst");
  4414. }
  4415. stackedMethods = new List<StackedMethod>();
  4416. int vTableIndex;
  4417. while((vTableIndex = objFileReader.ReadInt32()) >= 0)
  4418. {
  4419. StackedMethod sm;
  4420. sm.methVTI = vTableIndex;
  4421. sm.methName = objFileReader.ReadString();
  4422. sm.methSig = objFileReader.ReadString();
  4423. stackedMethods.Add(sm);
  4424. }
  4425. int numIFaces = objFileReader.ReadInt32();
  4426. if(numIFaces > 0)
  4427. {
  4428. iDynMeths = new DynamicMethod[numIFaces][];
  4429. iMethTypes = new Type[numIFaces][];
  4430. stackedIFaces = new List<StackedIFace>();
  4431. for(int i = 0; i < numIFaces; i++)
  4432. {
  4433. string iFaceName = objFileReader.ReadString();
  4434. intfIndices[iFaceName] = i;
  4435. int numMeths = objFileReader.ReadInt32();
  4436. iDynMeths[i] = new DynamicMethod[numMeths];
  4437. iMethTypes[i] = new Type[numMeths];
  4438. for(int j = 0; j < numMeths; j++)
  4439. {
  4440. StackedIFace si;
  4441. si.iFaceIndex = i;
  4442. si.methIndex = j;
  4443. si.vTableIndex = objFileReader.ReadInt32();
  4444. si.methName = objFileReader.ReadString();
  4445. si.methSig = objFileReader.ReadString();
  4446. stackedIFaces.Add(si);
  4447. }
  4448. }
  4449. }
  4450. }
  4451. private struct StackedMethod
  4452. {
  4453. public int methVTI;
  4454. public string methName;
  4455. public string methSig;
  4456. }
  4457. private struct StackedIFace
  4458. {
  4459. public int iFaceIndex; // which implemented interface
  4460. public int methIndex; // which method of that interface
  4461. public int vTableIndex; // <0: implemented by non-virtual; else: implemented by virtual
  4462. public string methName; // object code name of implementing method (GetObjCodeName)
  4463. public string methSig; // method signature incl return type (GetWholeSig)
  4464. }
  4465. /**
  4466. * @brief Called after all dynamic method code has been generated to fill in vDynMeths and vMethTypes
  4467. * Also fills in iDynMeths, iMethTypes.
  4468. */
  4469. public void FillVTables(ScriptObjCode scriptObjCode)
  4470. {
  4471. if(extendsStr != null)
  4472. {
  4473. if(extendsStr != "")
  4474. {
  4475. extends = (TokenDeclSDTypeClass)scriptObjCode.sdObjTypesName[extendsStr];
  4476. extends.FillVTables(scriptObjCode);
  4477. }
  4478. extendsStr = null;
  4479. }
  4480. if(arrayOfTypeStr != null)
  4481. {
  4482. arrayOfType = MakeTypeToken(arrayOfTypeStr);
  4483. arrayOfTypeStr = null;
  4484. }
  4485. if((numVirtFuncs > 0) && (stackedMethods != null))
  4486. {
  4487. // Allocate arrays big enough for mine plus type we are extending.
  4488. vDynMeths = new DynamicMethod[numVirtFuncs];
  4489. vMethTypes = new Type[numVirtFuncs];
  4490. // Fill in low parts from type we are extending.
  4491. if(extends != null)
  4492. {
  4493. int n = extends.numVirtFuncs;
  4494. for(int i = 0; i < n; i++)
  4495. {
  4496. vDynMeths[i] = extends.vDynMeths[i];
  4497. vMethTypes[i] = extends.vMethTypes[i];
  4498. }
  4499. }
  4500. // Fill in high parts with my own methods.
  4501. // Might also overwrite lower ones with 'override' methods.
  4502. foreach(StackedMethod sm in stackedMethods)
  4503. {
  4504. int i = sm.methVTI;
  4505. string methName = sm.methName;
  4506. if (scriptObjCode.dynamicMethods.TryGetValue(methName, out DynamicMethod dm))
  4507. {
  4508. // method is not abstract
  4509. vDynMeths[i] = dm;
  4510. vMethTypes[i] = GetDynamicMethodDelegateType(dm, sm.methSig);
  4511. }
  4512. }
  4513. stackedMethods = null;
  4514. }
  4515. if(stackedIFaces != null)
  4516. {
  4517. foreach(StackedIFace si in stackedIFaces)
  4518. {
  4519. int i = si.iFaceIndex;
  4520. int j = si.methIndex;
  4521. int vti = si.vTableIndex;
  4522. string methName = si.methName;
  4523. DynamicMethod dm = scriptObjCode.dynamicMethods[methName];
  4524. iDynMeths[i][j] = (vti < 0) ? dm : vDynMeths[vti];
  4525. iMethTypes[i][j] = GetDynamicMethodDelegateType(dm, si.methSig);
  4526. }
  4527. stackedIFaces = null;
  4528. }
  4529. }
  4530. private Type GetDynamicMethodDelegateType(DynamicMethod dm, string methSig)
  4531. {
  4532. Type retType = dm.ReturnType;
  4533. ParameterInfo[] pi = dm.GetParameters();
  4534. Type[] argTypes = new Type[pi.Length];
  4535. for(int j = 0; j < pi.Length; j++)
  4536. {
  4537. argTypes[j] = pi[j].ParameterType;
  4538. }
  4539. return DelegateCommon.GetType(retType, argTypes, methSig);
  4540. }
  4541. public override void DebString(StringBuilder sb)
  4542. {
  4543. // Don't output if array of some type.
  4544. // They will be re-instantiated as referenced by rest of script.
  4545. if(arrayOfType != null)
  4546. return;
  4547. // This class name and extended/implemented type declaration.
  4548. sb.Append("class ");
  4549. sb.Append(shortName.val);
  4550. bool first = true;
  4551. if(extends != null)
  4552. {
  4553. sb.Append(" : ");
  4554. sb.Append(extends.longName);
  4555. first = false;
  4556. }
  4557. foreach(TokenDeclSDType impld in implements)
  4558. {
  4559. sb.Append(first ? " : " : ", ");
  4560. sb.Append(impld.longName);
  4561. first = false;
  4562. }
  4563. sb.Append(" {");
  4564. // Inner type definitions.
  4565. foreach(TokenDeclSDType subs in innerSDTypes.Values)
  4566. {
  4567. subs.DebString(sb);
  4568. }
  4569. // Members (fields, methods, properties).
  4570. foreach(TokenDeclVar memb in members)
  4571. {
  4572. if((memb == instFieldInit) || (memb == staticFieldInit))
  4573. {
  4574. memb.DebStringInitFields(sb);
  4575. }
  4576. else if(memb.retType != null)
  4577. {
  4578. memb.DebString(sb);
  4579. }
  4580. }
  4581. sb.Append('}');
  4582. }
  4583. }
  4584. public class TokenDeclSDTypeDelegate: TokenDeclSDType
  4585. {
  4586. private TokenType retType;
  4587. private TokenType[] argTypes;
  4588. private string argSig;
  4589. private string wholeSig;
  4590. private Type sysType;
  4591. private Type retSysType;
  4592. private Type[] argSysTypes;
  4593. private string retStr;
  4594. private string[] argStrs;
  4595. private static Dictionary<string, TokenDeclSDTypeDelegate> inlines = new();
  4596. private static Dictionary<Type, string> inlrevs = new();
  4597. public TokenDeclSDTypeDelegate(TokenName shortName) : base(shortName)
  4598. {
  4599. this.shortName = shortName;
  4600. }
  4601. public void SetRetArgTypes(TokenType retType, TokenType[] argTypes)
  4602. {
  4603. this.retType = retType;
  4604. this.argTypes = argTypes;
  4605. }
  4606. protected override TokenDeclSDType MakeBlank(TokenName shortName)
  4607. {
  4608. return new TokenDeclSDTypeDelegate(shortName);
  4609. }
  4610. public override TokenType MakeRefToken(Token t)
  4611. {
  4612. return new TokenTypeSDTypeDelegate(t, this);
  4613. }
  4614. /**
  4615. * @brief Get system type for the whole delegate.
  4616. */
  4617. public override Type GetSysType()
  4618. {
  4619. if(sysType == null)
  4620. FillInStuff();
  4621. return sysType;
  4622. }
  4623. /**
  4624. * @brief Get the function's return value type (TokenTypeVoid if void, never null)
  4625. */
  4626. public TokenType GetRetType()
  4627. {
  4628. if(retType == null)
  4629. FillInStuff();
  4630. return retType;
  4631. }
  4632. /**
  4633. * @brief Get the function's argument types
  4634. */
  4635. public TokenType[] GetArgTypes()
  4636. {
  4637. if(argTypes == null)
  4638. FillInStuff();
  4639. return argTypes;
  4640. }
  4641. /**
  4642. * @brief Get signature for the whole delegate, eg, "void(integer,list)"
  4643. */
  4644. public string GetWholeSig()
  4645. {
  4646. if(wholeSig == null)
  4647. FillInStuff();
  4648. return wholeSig;
  4649. }
  4650. /**
  4651. * @brief Get signature for the arguments, eg, "(integer,list)"
  4652. */
  4653. public string GetArgSig()
  4654. {
  4655. if(argSig == null)
  4656. FillInStuff();
  4657. return argSig;
  4658. }
  4659. /**
  4660. * @brief Find out how to create one of these delegates.
  4661. */
  4662. public ConstructorInfo GetConstructorInfo()
  4663. {
  4664. if(sysType == null)
  4665. FillInStuff();
  4666. return sysType.GetConstructor(DelegateCommon.constructorArgTypes);
  4667. }
  4668. /**
  4669. * @brief Find out how to call what one of these delegates points to.
  4670. */
  4671. public MethodInfo GetInvokerInfo()
  4672. {
  4673. if(sysType == null)
  4674. FillInStuff();
  4675. return sysType.GetMethod("Invoke", argSysTypes);
  4676. }
  4677. /**
  4678. * @brief Write enough out to a file so delegate can be reconstructed in ReadFromFile().
  4679. */
  4680. public override void WriteToFile(BinaryWriter objFileWriter)
  4681. {
  4682. objFileWriter.Write(this.file);
  4683. objFileWriter.Write(this.line);
  4684. objFileWriter.Write(this.posn);
  4685. objFileWriter.Write((byte)DELEGATE);
  4686. objFileWriter.Write(this.sdTypeIndex);
  4687. objFileWriter.Write(retType.ToString());
  4688. int nArgs = argTypes.Length;
  4689. objFileWriter.Write(nArgs);
  4690. for(int i = 0; i < nArgs; i++)
  4691. {
  4692. objFileWriter.Write(argTypes[i].ToString());
  4693. }
  4694. }
  4695. /**
  4696. * @brief Read that data from file so we can reconstruct.
  4697. * Don't actually reconstruct yet in case any forward-referenced types are undefined.
  4698. */
  4699. public override void ReadFromFile(BinaryReader objFileReader, TextWriter asmFileWriter)
  4700. {
  4701. retStr = objFileReader.ReadString();
  4702. int nArgs = objFileReader.ReadInt32();
  4703. asmFileWriter?.Write(" delegate " + retStr + " " + longName.val + "(");
  4704. argStrs = new string[nArgs];
  4705. for(int i = 0; i < nArgs; i++)
  4706. {
  4707. argStrs[i] = objFileReader.ReadString();
  4708. if(asmFileWriter != null)
  4709. {
  4710. if(i > 0)
  4711. asmFileWriter.Write(",");
  4712. asmFileWriter.Write(argStrs[i]);
  4713. }
  4714. }
  4715. asmFileWriter?.WriteLine(");");
  4716. }
  4717. /**
  4718. * @brief Fill in missing internal data.
  4719. */
  4720. private void FillInStuff()
  4721. {
  4722. // This happens when the node was restored via ReadFromFile().
  4723. // It leaves the types in retStr/argStrs for resolution after
  4724. // all definitions have been read from the object file in case
  4725. // there are forward references.
  4726. retType ??= MakeTypeToken(retStr);
  4727. if(argTypes == null)
  4728. {
  4729. argTypes = new TokenType[argStrs.Length];
  4730. for(int i = 0; i < argStrs.Length; i++)
  4731. {
  4732. argTypes[i] = MakeTypeToken(argStrs[i]);
  4733. }
  4734. }
  4735. // Fill in system types from token types.
  4736. // Might as well build the signature strings too from token types.
  4737. retSysType = retType.ToSysType();
  4738. StringBuilder sb = new();
  4739. sb.Append('(');
  4740. argSysTypes = new Type[argTypes.Length];
  4741. for(int i = 0; i < argTypes.Length; i++)
  4742. {
  4743. if(i > 0)
  4744. sb.Append(',');
  4745. sb.Append(argTypes[i].ToString());
  4746. argSysTypes[i] = argTypes[i].ToSysType();
  4747. }
  4748. sb.Append(')');
  4749. argSig = sb.ToString();
  4750. wholeSig = retType.ToString() + argSig;
  4751. // Now we can create a system delegate type from the given
  4752. // return and argument types. Give it an unique name using
  4753. // the whole signature string.
  4754. sysType = DelegateCommon.GetType(retSysType, argSysTypes, wholeSig);
  4755. }
  4756. /**
  4757. * @brief create delegate reference token for inline functions.
  4758. * there is just one instance of these per inline function
  4759. * shared by all scripts, and it is just used when the
  4760. * script engine is loaded.
  4761. */
  4762. public static TokenDeclSDTypeDelegate CreateInline(TokenType retType, TokenType[] argTypes)
  4763. {
  4764. // Name it after the whole signature string.
  4765. StringBuilder sb = new("$inline");
  4766. sb.Append(retType.ToString());
  4767. sb.Append('(');
  4768. bool first = true;
  4769. foreach(TokenType at in argTypes)
  4770. {
  4771. if(!first)
  4772. sb.Append(',');
  4773. sb.Append(at.ToString());
  4774. first = false;
  4775. }
  4776. sb.Append(')');
  4777. string inlname = sb.ToString();
  4778. if(!inlines.TryGetValue(inlname, out TokenDeclSDTypeDelegate decldel))
  4779. {
  4780. // Create the corresponding declaration and link to it
  4781. TokenName name = new(null, inlname);
  4782. decldel = new TokenDeclSDTypeDelegate(name)
  4783. {
  4784. retType = retType,
  4785. argTypes = argTypes
  4786. };
  4787. inlines.Add(inlname, decldel);
  4788. inlrevs.Add(decldel.GetSysType(), inlname);
  4789. }
  4790. return decldel;
  4791. }
  4792. public static string TryGetInlineName(Type sysType)
  4793. {
  4794. if(inlrevs.TryGetValue(sysType, out string name))
  4795. return name;
  4796. return null;
  4797. }
  4798. public static Type TryGetInlineSysType(string name)
  4799. {
  4800. if (inlines.TryGetValue(name, out TokenDeclSDTypeDelegate decl))
  4801. return decl.GetSysType();
  4802. return null;
  4803. }
  4804. }
  4805. public class TokenDeclSDTypeInterface: TokenDeclSDType
  4806. {
  4807. public VarDict methsNProps = new(false);
  4808. // any class that implements this interface
  4809. // must implement all of these methods & properties
  4810. public List<TokenDeclSDTypeInterface> implements = new();
  4811. // any class that implements this interface
  4812. // must also implement all of the methods & properties
  4813. // of all of these interfaces
  4814. public TokenDeclSDTypeInterface(TokenName shortName) : base(shortName)
  4815. {
  4816. this.shortName = shortName;
  4817. }
  4818. protected override TokenDeclSDType MakeBlank(TokenName shortName)
  4819. {
  4820. return new TokenDeclSDTypeInterface(shortName);
  4821. }
  4822. public override TokenType MakeRefToken(Token t)
  4823. {
  4824. return new TokenTypeSDTypeInterface(t, this);
  4825. }
  4826. public override Type GetSysType()
  4827. {
  4828. // interfaces are implemented as arrays of delegates
  4829. // they are taken from iDynMeths[interfaceIndex] of a script-defined class object
  4830. return typeof(Delegate[]);
  4831. }
  4832. public override void WriteToFile(BinaryWriter objFileWriter)
  4833. {
  4834. objFileWriter.Write(this.file);
  4835. objFileWriter.Write(this.line);
  4836. objFileWriter.Write(this.posn);
  4837. objFileWriter.Write((byte)INTERFACE);
  4838. objFileWriter.Write(this.sdTypeIndex);
  4839. }
  4840. public override void ReadFromFile(BinaryReader objFileReader, TextWriter asmFileWriter)
  4841. {
  4842. }
  4843. /**
  4844. * @brief Add this interface to the list of interfaces implemented by a class if not already.
  4845. * And also add this interface's implemented interfaces to the class for those not already there,
  4846. * just as if the class itself had declared to implement those interfaces.
  4847. */
  4848. public void AddToClassDecl(TokenDeclSDTypeClass tokdeclcl)
  4849. {
  4850. if(!tokdeclcl.implements.Contains(this))
  4851. {
  4852. tokdeclcl.implements.Add(this);
  4853. foreach(TokenDeclSDTypeInterface subimpl in this.implements)
  4854. {
  4855. subimpl.AddToClassDecl(tokdeclcl);
  4856. }
  4857. }
  4858. }
  4859. /**
  4860. * @brief See if the 'this' interface implements the new interface.
  4861. * Do a recursive (deep) check.
  4862. */
  4863. public bool Implements(TokenDeclSDTypeInterface newDecl)
  4864. {
  4865. foreach(TokenDeclSDTypeInterface ii in this.implements)
  4866. {
  4867. if(ii == newDecl)
  4868. return true;
  4869. if(ii.Implements(newDecl))
  4870. return true;
  4871. }
  4872. return false;
  4873. }
  4874. /**
  4875. * @brief Scan an interface and all its implemented interfaces for a method or property
  4876. * @param scg = script code generator (ie, which script is being compiled)
  4877. * @param fieldName = name of the member being looked for
  4878. * @param argsig = the method's argument signature
  4879. * @returns null: no such member; intf = undefined
  4880. * else: member; intf = which interface actually found in
  4881. */
  4882. public TokenDeclVar FindIFaceMember(ScriptCodeGen scg, TokenName fieldName, TokenType[] argsig, out TokenDeclSDTypeInterface intf)
  4883. {
  4884. intf = this;
  4885. TokenDeclVar var = scg.FindSingleMember(this.methsNProps, fieldName, argsig);
  4886. if(var == null)
  4887. {
  4888. foreach(TokenDeclSDTypeInterface ii in this.implements)
  4889. {
  4890. var = ii.FindIFaceMember(scg, fieldName, argsig, out intf);
  4891. if(var != null)
  4892. break;
  4893. }
  4894. }
  4895. return var;
  4896. }
  4897. }
  4898. public class TokenDeclSDTypeTypedef: TokenDeclSDType
  4899. {
  4900. public TokenDeclSDTypeTypedef(TokenName shortName) : base(shortName)
  4901. {
  4902. this.shortName = shortName;
  4903. }
  4904. protected override TokenDeclSDType MakeBlank(TokenName shortName)
  4905. {
  4906. return new TokenDeclSDTypeTypedef(shortName);
  4907. }
  4908. public override TokenType MakeRefToken(Token t)
  4909. {
  4910. // if our body is a single type token, that is what we return
  4911. // otherwise return null saying maybe our body needs some substitutions
  4912. if(nextToken is not TokenType)
  4913. return null;
  4914. if(nextToken.nextToken != this.endToken)
  4915. {
  4916. nextToken.nextToken.ErrorMsg("extra tokens for typedef");
  4917. return null;
  4918. }
  4919. return (TokenType)nextToken.CopyToken(t);
  4920. }
  4921. public override Type GetSysType()
  4922. {
  4923. // we are just a macro
  4924. // we are asked for system type because we are cataloged
  4925. // but we don't really have one so return null
  4926. return null;
  4927. }
  4928. public override void WriteToFile(BinaryWriter objFileWriter)
  4929. {
  4930. objFileWriter.Write(this.file);
  4931. objFileWriter.Write(this.line);
  4932. objFileWriter.Write(this.posn);
  4933. objFileWriter.Write((byte)TYPEDEF);
  4934. objFileWriter.Write(this.sdTypeIndex);
  4935. }
  4936. public override void ReadFromFile(BinaryReader objFileReader, TextWriter asmFileWriter)
  4937. {
  4938. }
  4939. }
  4940. /**
  4941. * @brief Script-defined type references.
  4942. * These occur in the source code wherever it specifies (eg, variable declaration) a script-defined type.
  4943. * These must be copyable via CopyToken().
  4944. */
  4945. public abstract class TokenTypeSDType: TokenType
  4946. {
  4947. public TokenTypeSDType(TokenErrorMessage emsg, string file, int line, int posn) : base(emsg, file, line, posn) { }
  4948. public TokenTypeSDType(Token t) : base(t) { }
  4949. public abstract TokenDeclSDType GetDecl();
  4950. public abstract void SetDecl(TokenDeclSDType decl);
  4951. }
  4952. public class TokenTypeSDTypeClass: TokenTypeSDType
  4953. {
  4954. private static readonly FieldInfo iarSDTClObjsFieldInfo = typeof(XMRInstArrays).GetField("iarSDTClObjs");
  4955. public TokenDeclSDTypeClass decl;
  4956. public TokenTypeSDTypeClass(Token t, TokenDeclSDTypeClass decl) : base(t)
  4957. {
  4958. this.decl = decl;
  4959. }
  4960. public override TokenDeclSDType GetDecl()
  4961. {
  4962. return decl;
  4963. }
  4964. public override void SetDecl(TokenDeclSDType decl)
  4965. {
  4966. this.decl = (TokenDeclSDTypeClass)decl;
  4967. }
  4968. public override string ToString()
  4969. {
  4970. return decl.longName.val;
  4971. }
  4972. public override Type ToSysType()
  4973. {
  4974. return typeof(XMRSDTypeClObj);
  4975. }
  4976. public override void AssignVarSlot(TokenDeclVar declVar, XMRInstArSizes ias)
  4977. {
  4978. declVar.vTableArray = iarSDTClObjsFieldInfo;
  4979. declVar.vTableIndex = ias.iasSDTClObjs++;
  4980. }
  4981. // debugging
  4982. public override void DebString(StringBuilder sb)
  4983. {
  4984. sb.Append(decl.longName);
  4985. }
  4986. }
  4987. public class TokenTypeSDTypeDelegate: TokenTypeSDType
  4988. {
  4989. private static readonly FieldInfo iarObjectsFieldInfo = typeof(XMRInstArrays).GetField("iarObjects");
  4990. public TokenDeclSDTypeDelegate decl;
  4991. /**
  4992. * @brief create a reference to an explicitly declared delegate
  4993. * @param t = where the reference is being made in the source file
  4994. * @param decl = the explicit delegate declaration
  4995. */
  4996. public TokenTypeSDTypeDelegate(Token t, TokenDeclSDTypeDelegate decl) : base(t)
  4997. {
  4998. this.decl = decl;
  4999. }
  5000. public override TokenDeclSDType GetDecl()
  5001. {
  5002. return decl;
  5003. }
  5004. public override void SetDecl(TokenDeclSDType decl)
  5005. {
  5006. this.decl = (TokenDeclSDTypeDelegate)decl;
  5007. }
  5008. /**
  5009. * @brief create a reference to a possibly anonymous delegate
  5010. * @param t = where the reference is being made in the source file
  5011. * @param retType = return type (TokenTypeVoid if void, never null)
  5012. * @param argTypes = script-visible argument types
  5013. * @param tokenScript = what script this is part of
  5014. */
  5015. public TokenTypeSDTypeDelegate(Token t, TokenType retType, TokenType[] argTypes, TokenScript tokenScript) : base(t)
  5016. {
  5017. TokenDeclSDTypeDelegate decldel;
  5018. // See if we already have a matching declared one cataloged.
  5019. int nArgs = argTypes.Length;
  5020. foreach(TokenDeclSDType decl in tokenScript.sdSrcTypesValues)
  5021. {
  5022. if(decl is TokenDeclSDTypeDelegate decldelg)
  5023. {
  5024. TokenType rt = decldelg.GetRetType();
  5025. TokenType[] ats = decldelg.GetArgTypes();
  5026. if((rt.ToString() == retType.ToString()) && (ats.Length == nArgs))
  5027. {
  5028. for(int i = 0; i < nArgs; i++)
  5029. {
  5030. if(ats[i].ToString() != argTypes[i].ToString())
  5031. goto nomatch;
  5032. }
  5033. this.decl = decldelg;
  5034. return;
  5035. }
  5036. }
  5037. nomatch:
  5038. ;
  5039. }
  5040. // No such luck, create a new anonymous declaration.
  5041. StringBuilder sb = new("$anondel$");
  5042. sb.Append(retType.ToString());
  5043. sb.Append('(');
  5044. bool first = true;
  5045. foreach(TokenType at in argTypes)
  5046. {
  5047. if(!first)
  5048. sb.Append(',');
  5049. sb.Append(at.ToString());
  5050. first = false;
  5051. }
  5052. sb.Append(')');
  5053. TokenName name = new(t, sb.ToString());
  5054. decldel = new TokenDeclSDTypeDelegate(name);
  5055. decldel.SetRetArgTypes(retType, argTypes);
  5056. tokenScript.sdSrcTypesAdd(name.val, decldel);
  5057. this.decl = decldel;
  5058. }
  5059. public override Type ToSysType()
  5060. {
  5061. return decl.GetSysType();
  5062. }
  5063. public override string ToString()
  5064. {
  5065. return decl.longName.val;
  5066. }
  5067. /**
  5068. * @brief Assign slots in the gblObjects[] array because we have to typecast out in any case.
  5069. * Likewise with the sdtcObjects[] array.
  5070. */
  5071. public override void AssignVarSlot(TokenDeclVar declVar, XMRInstArSizes ias)
  5072. {
  5073. declVar.vTableArray = iarObjectsFieldInfo;
  5074. declVar.vTableIndex = ias.iasObjects++;
  5075. }
  5076. /**
  5077. * @brief create delegate reference token for inline functions.
  5078. */
  5079. public TokenTypeSDTypeDelegate(TokenType retType, TokenType[] argTypes) : base(null)
  5080. {
  5081. this.decl = TokenDeclSDTypeDelegate.CreateInline(retType, argTypes);
  5082. }
  5083. // debugging
  5084. public override void DebString(StringBuilder sb)
  5085. {
  5086. sb.Append(decl.longName);
  5087. }
  5088. }
  5089. public class TokenTypeSDTypeInterface: TokenTypeSDType
  5090. {
  5091. private static readonly FieldInfo iarSDTIntfObjsFieldInfo = typeof(XMRInstArrays).GetField("iarSDTIntfObjs");
  5092. public TokenDeclSDTypeInterface decl;
  5093. public TokenTypeSDTypeInterface(Token t, TokenDeclSDTypeInterface decl) : base(t)
  5094. {
  5095. this.decl = decl;
  5096. }
  5097. public override TokenDeclSDType GetDecl()
  5098. {
  5099. return decl;
  5100. }
  5101. public override void SetDecl(TokenDeclSDType decl)
  5102. {
  5103. this.decl = (TokenDeclSDTypeInterface)decl;
  5104. }
  5105. public override string ToString()
  5106. {
  5107. return decl.longName.val;
  5108. }
  5109. public override Type ToSysType()
  5110. {
  5111. return typeof(Delegate[]);
  5112. }
  5113. /**
  5114. * @brief Assign slots in the gblSDTIntfObjs[] array
  5115. * Likewise with the sdtcSDTIntfObjs[] array.
  5116. */
  5117. public override void AssignVarSlot(TokenDeclVar declVar, XMRInstArSizes ias)
  5118. {
  5119. declVar.vTableArray = iarSDTIntfObjsFieldInfo;
  5120. declVar.vTableIndex = ias.iasSDTIntfObjs++;
  5121. }
  5122. // debugging
  5123. public override void DebString(StringBuilder sb)
  5124. {
  5125. sb.Append(decl.longName);
  5126. }
  5127. }
  5128. /**
  5129. * @brief function argument list declaration
  5130. */
  5131. public class TokenArgDecl: Token
  5132. {
  5133. public VarDict varDict = new (false);
  5134. public TokenArgDecl(Token original) : base(original) { }
  5135. public bool AddArg(TokenType type, TokenName name)
  5136. {
  5137. TokenDeclVar var = new (name, null, null)
  5138. {
  5139. name = name,
  5140. type = type,
  5141. vTableIndex = varDict.Count
  5142. };
  5143. return varDict.AddEntry(var);
  5144. }
  5145. /**
  5146. * @brief Get an array of the argument types.
  5147. */
  5148. private TokenType[] _types;
  5149. public TokenType[] types
  5150. {
  5151. get
  5152. {
  5153. if(_types == null)
  5154. {
  5155. _types = new TokenType[varDict.Count];
  5156. foreach(TokenDeclVar var in varDict)
  5157. {
  5158. _types[var.vTableIndex] = var.type;
  5159. }
  5160. }
  5161. return _types;
  5162. }
  5163. }
  5164. /**
  5165. * @brief Access the arguments as an array of variables.
  5166. */
  5167. private TokenDeclVar[] _vars;
  5168. public TokenDeclVar[] vars
  5169. {
  5170. get
  5171. {
  5172. if(_vars == null)
  5173. {
  5174. _vars = new TokenDeclVar[varDict.Count];
  5175. foreach(TokenDeclVar var in varDict)
  5176. {
  5177. _vars[var.vTableIndex] = var;
  5178. }
  5179. }
  5180. return _vars;
  5181. }
  5182. }
  5183. /**
  5184. * @brief Get argument signature string, eg, "(list,vector,integer)"
  5185. */
  5186. private string argSig = null;
  5187. public string GetArgSig()
  5188. {
  5189. argSig ??= ScriptCodeGen.ArgSigString(types);
  5190. return argSig;
  5191. }
  5192. }
  5193. /**
  5194. * @brief encapsulate a state declaration in a single token
  5195. */
  5196. public class TokenDeclState: Token
  5197. {
  5198. public TokenName name; // null for default state
  5199. public TokenStateBody body;
  5200. public TokenDeclState(Token original) : base(original) { }
  5201. public override void DebString(StringBuilder sb)
  5202. {
  5203. if(name == null)
  5204. {
  5205. sb.Append("default");
  5206. }
  5207. else
  5208. {
  5209. sb.Append("state ");
  5210. sb.Append(name);
  5211. }
  5212. body.DebString(sb);
  5213. }
  5214. }
  5215. /**
  5216. * @brief encapsulate the declaration of a field/function/method/property/variable.
  5217. */
  5218. public enum Triviality
  5219. { // function triviality: has no loops and doesn't call anything that has loops
  5220. // such a function does not need all the CheckRun() and stack serialization stuff
  5221. unknown, // function's Triviality unknown as of yet
  5222. // - it does not have any loops or backward gotos
  5223. // - nothing it calls is known to be complex
  5224. trivial, // function known to be trivial
  5225. // - it does not have any loops or backward gotos
  5226. // - everything it calls is known to be trivial
  5227. complex, // function known to be complex
  5228. // - it has loops or backward gotos
  5229. // - something it calls is known to be complex
  5230. analyzing // triviality is being analyzed (used to detect recursive loops)
  5231. };
  5232. public class TokenDeclVar: TokenStmt
  5233. {
  5234. public TokenName name; // vars: name; funcs: bare name, ie, no signature
  5235. public TokenRVal init; // vars: null if none; funcs: null
  5236. public bool constant; // vars: 'constant'; funcs: false
  5237. public uint sdtFlags; // SDT_<*> flags
  5238. public CompValu location; // used by codegen to keep track of location
  5239. public FieldInfo vTableArray;
  5240. public int vTableIndex = -1; // local vars: not used (-1)
  5241. // arg vars: index in the arg list
  5242. // global vars: which slot in gbl<Type>s[] array it is stored
  5243. // instance vars: which slot in inst<Types>s[] array it is stored
  5244. // static vars: which slot in gbl<Type>s[] array it is stored
  5245. // global funcs: not used (-1)
  5246. // virt funcs: which slot in vTable[] array it is stored
  5247. // instance func: not used (-1)
  5248. public TokenDeclVar getProp; // if property, function that reads value
  5249. public TokenDeclVar setProp; // if property, function that writes value
  5250. public TokenScript tokenScript; // what script this function is part of
  5251. public TokenDeclSDType sdtClass; // null: script global member
  5252. // else: member is part of this script-defined type
  5253. // function-only data:
  5254. public TokenType retType; // vars: null; funcs: TokenTypeVoid if void
  5255. public TokenArgDecl argDecl; // vars: null; funcs: argument list prototypes
  5256. public TokenStmtBlock body; // vars: null; funcs: statements (null iff abstract)
  5257. public Dictionary<string, TokenStmtLabel> labels = new();
  5258. // all labels defined in the function
  5259. public LinkedList<TokenDeclVar> localVars = new();
  5260. // all local variables declared by this function
  5261. // - doesn't include argument variables
  5262. public TokenIntfImpl implements; // if script-defined type method, what interface method(s) this func implements
  5263. public TokenRValCall baseCtorCall; // if script-defined type constructor, call to base constructor, if any
  5264. public Triviality triviality = Triviality.unknown;
  5265. // vars: unknown (not used for any thing); funcs: unknown/trivial/complex
  5266. public LinkedList<TokenRValCall> unknownTrivialityCalls = new();
  5267. // reduction puts all calls here
  5268. // compilation sorts it all out
  5269. public ScriptObjWriter ilGen; // codegen stores emitted code here
  5270. /**
  5271. * @brief Set up a variable declaration token.
  5272. * @param original = original source token that triggered definition
  5273. * (for error messages)
  5274. * @param func = null: global variable
  5275. * else: local to the given function
  5276. */
  5277. public TokenDeclVar(Token original, TokenDeclVar func, TokenScript ts) : base(original)
  5278. {
  5279. func?.localVars.AddLast(this);
  5280. tokenScript = ts;
  5281. }
  5282. /**
  5283. * @brief Get/Set overall type
  5284. * For vars, this is the type of the location
  5285. * For funcs, this is the delegate type
  5286. */
  5287. private TokenType _type;
  5288. public TokenType type
  5289. {
  5290. get
  5291. {
  5292. if(_type == null)
  5293. {
  5294. GetDelType();
  5295. }
  5296. return _type;
  5297. }
  5298. set
  5299. {
  5300. _type = value;
  5301. }
  5302. }
  5303. /**
  5304. * @brief Full name: <fulltype>.<name>(<argsig>)
  5305. * (<argsig>) missing for fields/variables
  5306. * <fulltype>. missing for top-level functions/variables
  5307. */
  5308. public string fullName
  5309. {
  5310. get
  5311. {
  5312. if(sdtClass == null)
  5313. {
  5314. if(retType == null)
  5315. return name.val;
  5316. return funcNameSig.val;
  5317. }
  5318. if(retType == null)
  5319. return sdtClass.longName.val + "." + name.val;
  5320. return sdtClass.longName.val + "." + funcNameSig.val;
  5321. }
  5322. }
  5323. /**
  5324. * @brief See if reading or writing the variable is trivial.
  5325. * Note that for functions, this is reading the function itself,
  5326. * as in 'someDelegate = SomeFunction;', not calling it as such.
  5327. * The triviality of actually calling the function is IsFuncTrivial().
  5328. */
  5329. public bool IsVarTrivial(ScriptCodeGen scg)
  5330. {
  5331. // reading or writing a property involves a function call however
  5332. // so we need to check the triviality of the property functions
  5333. if((getProp != null) && !getProp.IsFuncTrivial(scg))
  5334. return false;
  5335. if((setProp != null) && !setProp.IsFuncTrivial(scg))
  5336. return false;
  5337. // otherwise for variables it is a trivial access
  5338. // and likewise for getting a delegate that points to a function
  5339. return true;
  5340. }
  5341. /***************************\
  5342. * FUNCTION-only methods *
  5343. \***************************/
  5344. private TokenName _funcNameSig; // vars: null; funcs: function name including argumet signature, eg, "PrintStuff(list,string)"
  5345. public TokenName funcNameSig
  5346. {
  5347. get
  5348. {
  5349. if(_funcNameSig == null)
  5350. {
  5351. if(argDecl == null)
  5352. return null;
  5353. _funcNameSig = new TokenName(name, name.val + argDecl.GetArgSig());
  5354. }
  5355. return _funcNameSig;
  5356. }
  5357. }
  5358. /**
  5359. * @brief The bare function name, ie, without any signature info
  5360. */
  5361. public string GetSimpleName()
  5362. {
  5363. return name.val;
  5364. }
  5365. /**
  5366. * @brief The function name as it appears in the object code,
  5367. * ie, script-defined type name if any,
  5368. * bare function name and argument signature,
  5369. * eg, "MyClass.PrintStuff(string)"
  5370. */
  5371. public string GetObjCodeName()
  5372. {
  5373. if(sdtClass != null)
  5374. {
  5375. return sdtClass.longName.val + "." + funcNameSig.val;
  5376. }
  5377. return funcNameSig.val;
  5378. }
  5379. /**
  5380. * @brief Get delegate type.
  5381. * This is the function's script-visible type,
  5382. * It includes return type and all script-visible argument types.
  5383. * @returns null for vars; else delegate type for funcs
  5384. */
  5385. public TokenTypeSDTypeDelegate GetDelType()
  5386. {
  5387. if(argDecl == null)
  5388. return null;
  5389. if(_type == null)
  5390. {
  5391. if(tokenScript == null)
  5392. {
  5393. // used during startup to define inline function delegate types
  5394. _type = new TokenTypeSDTypeDelegate(retType, argDecl.types);
  5395. }
  5396. else
  5397. {
  5398. // used for normal script processing
  5399. _type = new TokenTypeSDTypeDelegate(this, retType, argDecl.types, tokenScript);
  5400. }
  5401. }
  5402. if(_type is TokenTypeSDTypeDelegate TokenTypeSDTypeDelegate_type)
  5403. return TokenTypeSDTypeDelegate_type;
  5404. return null;
  5405. }
  5406. /**
  5407. * @brief See if the function's code itself is trivial or not.
  5408. * If it contains any loops (calls to CheckRun()), it is not trivial.
  5409. * If it calls anything that is not trivial, it is not trivial.
  5410. * Otherwise it is trivial.
  5411. */
  5412. public bool IsFuncTrivial(ScriptCodeGen scg)
  5413. {
  5414. // If not really a function, assume it's a delegate.
  5415. // And since we don't really know what functions it can point to,
  5416. // assume it can point to a non-trivial one.
  5417. if(retType == null)
  5418. return false;
  5419. // All virtual functions are non-trivial because although a particular
  5420. // one might be trivial, it might be overidden with a non-trivial one.
  5421. if((sdtFlags & (ScriptReduce.SDT_ABSTRACT | ScriptReduce.SDT_OVERRIDE |
  5422. ScriptReduce.SDT_VIRTUAL)) != 0)
  5423. {
  5424. return false;
  5425. }
  5426. // Check the triviality status of the function.
  5427. switch(triviality)
  5428. {
  5429. // Don't yet know if it is trivial.
  5430. // We know at this point it doesn't have any direct looping.
  5431. // But if it calls something that has loops, it isn't trivial.
  5432. // Otherwise it is trivial.
  5433. case Triviality.unknown:
  5434. {
  5435. // Mark that we are analyzing this function now. So if there are
  5436. // any recursive call loops, that will show that the function is
  5437. // non-trivial and the analysis will terminate at that point.
  5438. triviality = Triviality.analyzing;
  5439. // Check out everything else this function calls. If any say they
  5440. // aren't trivial, then we say this function isn't trivial.
  5441. foreach(TokenRValCall call in unknownTrivialityCalls)
  5442. {
  5443. if(!call.IsRValTrivial(scg, null))
  5444. {
  5445. triviality = Triviality.complex;
  5446. return false;
  5447. }
  5448. }
  5449. // All functions called by this function are trivial, and this
  5450. // function's code doesn't have any loops, so we can mark this
  5451. // function as being trivial.
  5452. triviality = Triviality.trivial;
  5453. return true;
  5454. }
  5455. // We already know that it is trivial.
  5456. case Triviality.trivial:
  5457. {
  5458. return true;
  5459. }
  5460. // We either know it is complex or are trying to analyze it already.
  5461. // If we are already analyzing it, it means it has a recursive loop
  5462. // and we assume those are non-trivial.
  5463. default:
  5464. return false;
  5465. }
  5466. }
  5467. // debugging
  5468. public override void DebString(StringBuilder sb)
  5469. {
  5470. DebStringSDTFlags(sb);
  5471. if(retType == null)
  5472. {
  5473. sb.Append(constant ? "constant" : type.ToString());
  5474. sb.Append(' ');
  5475. sb.Append(name.val);
  5476. if(init != null)
  5477. {
  5478. sb.Append(" = ");
  5479. init.DebString(sb);
  5480. }
  5481. sb.Append(';');
  5482. }
  5483. else
  5484. {
  5485. if(retType is not TokenTypeVoid)
  5486. {
  5487. sb.Append(retType.ToString());
  5488. sb.Append(' ');
  5489. }
  5490. string namestr = name.val;
  5491. if(namestr == "$ctor")
  5492. namestr = "constructor";
  5493. sb.Append(namestr);
  5494. sb.Append(" (");
  5495. for(int i = 0; i < argDecl.vars.Length; i++)
  5496. {
  5497. if(i > 0)
  5498. sb.Append(", ");
  5499. sb.Append(argDecl.vars[i].type.ToString());
  5500. sb.Append(' ');
  5501. sb.Append(argDecl.vars[i].name.val);
  5502. }
  5503. sb.Append(')');
  5504. if(body == null)
  5505. sb.Append(';');
  5506. else
  5507. {
  5508. sb.Append(' ');
  5509. body.DebString(sb);
  5510. }
  5511. }
  5512. }
  5513. // debugging
  5514. // - used to output contents of a $globalvarinit(), $instfieldinit() or $statisfieldinit() function
  5515. // as a series of variable declaration statements with initial value assignments
  5516. // so we get the initial value assignments done in same order as specified in script
  5517. public void DebStringInitFields(StringBuilder sb)
  5518. {
  5519. if(retType is not TokenTypeVoid)
  5520. throw new Exception("bad return type " + retType.GetType().Name);
  5521. if(argDecl.vars.Length != 0)
  5522. throw new Exception("has " + argDecl.vars.Length + " arg(s)");
  5523. for(Token stmt = body.statements; stmt != null; stmt = stmt.nextToken)
  5524. {
  5525. // Body of the function should all be arithmetic statements (not eg for loops, if statements etc).
  5526. TokenRVal rval = ((TokenStmtRVal)stmt).rVal;
  5527. // And the opcode should be a simple assignment operator.
  5528. TokenRValOpBin rvob = (TokenRValOpBin)rval;
  5529. if(rvob.opcode is not TokenKwAssign)
  5530. throw new Exception("bad op type " + rvob.opcode.GetType().Name);
  5531. // Get field or variable being assigned to.
  5532. TokenDeclVar tdvar = null;
  5533. TokenRVal left = rvob.rValLeft;
  5534. if(left is TokenLValIField ifield)
  5535. {
  5536. TokenRValThis zhis = (TokenRValThis)ifield.baseRVal;
  5537. TokenDeclSDTypeClass sdt = zhis.sdtClass;
  5538. tdvar = sdt.members.FindExact(ifield.fieldName.val, null);
  5539. }
  5540. if(left is TokenLValName global)
  5541. {
  5542. tdvar = global.stack.FindExact(global.name.val, null);
  5543. }
  5544. if(left is TokenLValSField sfield)
  5545. {
  5546. TokenTypeSDTypeClass sdtc = (TokenTypeSDTypeClass)sfield.baseType;
  5547. TokenDeclSDTypeClass decl = sdtc.decl;
  5548. tdvar = decl.members.FindExact(sfield.fieldName.val, null);
  5549. }
  5550. if(tdvar == null)
  5551. throw new Exception("unknown var type " + left.GetType().Name);
  5552. // Output flags, type name and bare variable name.
  5553. // This should look like a declaration in the 'sb'
  5554. // as it is not enclosed in a function.
  5555. tdvar.DebStringSDTFlags(sb);
  5556. tdvar.type.DebString(sb);
  5557. sb.Append(' ');
  5558. sb.Append(tdvar.name.val);
  5559. // Maybe it has a non-default initialization value.
  5560. if((tdvar.init != null) && tdvar.init is not TokenRValInitDef)
  5561. {
  5562. sb.Append(" = ");
  5563. tdvar.init.DebString(sb);
  5564. }
  5565. // End of declaration statement.
  5566. sb.Append(';');
  5567. }
  5568. }
  5569. private void DebStringSDTFlags(StringBuilder sb)
  5570. {
  5571. if((sdtFlags & ScriptReduce.SDT_PRIVATE) != 0)
  5572. sb.Append("private ");
  5573. if((sdtFlags & ScriptReduce.SDT_PROTECTED) != 0)
  5574. sb.Append("protected ");
  5575. if((sdtFlags & ScriptReduce.SDT_PUBLIC) != 0)
  5576. sb.Append("public ");
  5577. if((sdtFlags & ScriptReduce.SDT_ABSTRACT) != 0)
  5578. sb.Append("abstract ");
  5579. if((sdtFlags & ScriptReduce.SDT_FINAL) != 0)
  5580. sb.Append("final ");
  5581. if((sdtFlags & ScriptReduce.SDT_NEW) != 0)
  5582. sb.Append("new ");
  5583. if((sdtFlags & ScriptReduce.SDT_OVERRIDE) != 0)
  5584. sb.Append("override ");
  5585. if((sdtFlags & ScriptReduce.SDT_STATIC) != 0)
  5586. sb.Append("static ");
  5587. if((sdtFlags & ScriptReduce.SDT_VIRTUAL) != 0)
  5588. sb.Append("virtual ");
  5589. }
  5590. }
  5591. /**
  5592. * @brief Indicates an interface type.method that is implemented by the function
  5593. */
  5594. public class TokenIntfImpl: Token
  5595. {
  5596. public TokenTypeSDTypeInterface intfType;
  5597. public TokenName methName; // simple name, no arg signature
  5598. public TokenIntfImpl(TokenTypeSDTypeInterface intfType, TokenName methName) : base(intfType)
  5599. {
  5600. this.intfType = intfType;
  5601. this.methName = methName;
  5602. }
  5603. }
  5604. /**
  5605. * @brief any expression that can go on left side of an "="
  5606. */
  5607. public abstract class TokenLVal: TokenRVal
  5608. {
  5609. public TokenLVal(Token original) : base(original) { }
  5610. public abstract override TokenType GetRValType(ScriptCodeGen scg, TokenType[] argsig);
  5611. public abstract override bool IsRValTrivial(ScriptCodeGen scg, TokenType[] argsig);
  5612. }
  5613. /**
  5614. * @brief an element of an array is an L-value
  5615. */
  5616. public class TokenLValArEle: TokenLVal
  5617. {
  5618. public TokenRVal baseRVal;
  5619. public TokenRVal subRVal;
  5620. public TokenLValArEle(Token original) : base(original) { }
  5621. public override TokenType GetRValType(ScriptCodeGen scg, TokenType[] argsig)
  5622. {
  5623. TokenType baseType = baseRVal.GetRValType(scg, null);
  5624. // Maybe referencing element of a fixed-dimension array.
  5625. if((baseType is TokenTypeSDTypeClass bbtype) && bbtype.decl.arrayOfType != null)
  5626. {
  5627. return bbtype.decl.arrayOfType;
  5628. }
  5629. // Maybe referencing $idxprop property of script-defined class or interface.
  5630. if(baseType is TokenTypeSDTypeClass bc)
  5631. {
  5632. TokenDeclSDTypeClass sdtDecl = bc.decl;
  5633. TokenDeclVar idxProp = scg.FindSingleMember(sdtDecl.members, new TokenName(this, "$idxprop"), null);
  5634. if(idxProp != null)
  5635. return idxProp.type;
  5636. }
  5637. if(baseType is TokenTypeSDTypeInterface bi)
  5638. {
  5639. TokenDeclSDTypeInterface sdtDecl = bi.decl;
  5640. TokenDeclVar idxProp = sdtDecl.FindIFaceMember(scg, new TokenName(this, "$idxprop"), null, out sdtDecl);
  5641. if(idxProp != null)
  5642. return idxProp.type;
  5643. }
  5644. // Maybe referencing single character of a string.
  5645. if((baseType is TokenTypeKey) || (baseType is TokenTypeStr))
  5646. {
  5647. return new TokenTypeChar(this);
  5648. }
  5649. // Assume XMR_Array element or extracting element from list.
  5650. if((baseType is TokenTypeArray) || (baseType is TokenTypeList))
  5651. {
  5652. return new TokenTypeObject(this);
  5653. }
  5654. scg.ErrorMsg(this, "unknown array reference");
  5655. return new TokenTypeVoid(this);
  5656. }
  5657. public override bool IsRValTrivial(ScriptCodeGen scg, TokenType[] argsig)
  5658. {
  5659. return baseRVal.IsRValTrivial(scg, null) && subRVal.IsRValTrivial(scg, null);
  5660. }
  5661. public override void DebString(StringBuilder sb)
  5662. {
  5663. baseRVal.DebString(sb);
  5664. sb.Append('[');
  5665. subRVal.DebString(sb);
  5666. sb.Append(']');
  5667. }
  5668. }
  5669. /**
  5670. * @brief 'base.' being used to reference a field/method of the extended class.
  5671. */
  5672. public class TokenLValBaseField: TokenLVal
  5673. {
  5674. public TokenName fieldName;
  5675. private TokenDeclSDTypeClass thisClass;
  5676. public TokenLValBaseField(Token original, TokenName fieldName, TokenDeclSDTypeClass thisClass) : base(original)
  5677. {
  5678. this.fieldName = fieldName;
  5679. this.thisClass = thisClass;
  5680. }
  5681. public override TokenType GetRValType(ScriptCodeGen scg, TokenType[] argsig)
  5682. {
  5683. TokenDeclVar var = scg.FindThisMember(thisClass.extends, fieldName, argsig);
  5684. if(var != null)
  5685. return var.type;
  5686. scg.ErrorMsg(fieldName, "unknown member of " + thisClass.extends.ToString());
  5687. return new TokenTypeVoid(fieldName);
  5688. }
  5689. public override bool IsRValTrivial(ScriptCodeGen scg, TokenType[] argsig)
  5690. {
  5691. TokenDeclVar var = scg.FindThisMember(thisClass.extends, fieldName, argsig);
  5692. return (var != null) && var.IsVarTrivial(scg);
  5693. }
  5694. public override bool IsCallTrivial(ScriptCodeGen scg, TokenType[] argsig)
  5695. {
  5696. TokenDeclVar var = scg.FindThisMember(thisClass.extends, fieldName, argsig);
  5697. return (var != null) && var.IsFuncTrivial(scg);
  5698. }
  5699. }
  5700. /**
  5701. * @brief a field within an struct is an L-value
  5702. */
  5703. public class TokenLValIField: TokenLVal
  5704. {
  5705. public TokenRVal baseRVal;
  5706. public TokenName fieldName;
  5707. public TokenLValIField(Token original) : base(original) { }
  5708. public override TokenType GetRValType(ScriptCodeGen scg, TokenType[] argsig)
  5709. {
  5710. TokenType baseType = baseRVal.GetRValType(scg, null);
  5711. if(baseType is TokenTypeSDTypeClass TokenTypeSDTypeClassbaseType)
  5712. {
  5713. TokenDeclVar tvar = scg.FindThisMember(TokenTypeSDTypeClassbaseType, fieldName, argsig);
  5714. if(tvar != null)
  5715. return tvar.type;
  5716. }
  5717. if(baseType is TokenTypeSDTypeInterface TokenTypeSDTypeInterfacebaseType)
  5718. {
  5719. TokenDeclSDTypeInterface baseIntfDecl = (TokenTypeSDTypeInterfacebaseType).decl;
  5720. TokenDeclVar tvar = baseIntfDecl.FindIFaceMember(scg, fieldName, argsig, out baseIntfDecl);
  5721. if(tvar != null)
  5722. return tvar.type;
  5723. }
  5724. if(baseType is TokenTypeArray)
  5725. {
  5726. return XMR_Array.GetRValType(fieldName);
  5727. }
  5728. if((baseType is TokenTypeRot) || (baseType is TokenTypeVec))
  5729. {
  5730. return new TokenTypeFloat(fieldName);
  5731. }
  5732. scg.ErrorMsg(fieldName, "unknown member of " + baseType.ToString());
  5733. return new TokenTypeVoid(fieldName);
  5734. }
  5735. public override bool IsRValTrivial(ScriptCodeGen scg, TokenType[] argsig)
  5736. {
  5737. // If getting pointer to instance isn't trivial, then accessing the member isn't trivial either.
  5738. if(!baseRVal.IsRValTrivial(scg, null))
  5739. return false;
  5740. // Accessing a member of a class depends on the member.
  5741. // In the case of a method, this is accessing it as a delegate, not calling it, and
  5742. // argsig simply serves as selecting which of possibly overloaded methods to select.
  5743. // The case of accessing a property, however, depends on the property implementation,
  5744. // as there could be looping inside the property code.
  5745. TokenType baseType = baseRVal.GetRValType(scg, null);
  5746. if(baseType is TokenTypeSDTypeClass TokenTypeSDTypeClassbaseType)
  5747. {
  5748. TokenDeclVar tvar = scg.FindThisMember(TokenTypeSDTypeClassbaseType, fieldName, argsig);
  5749. return (tvar != null) && tvar.IsVarTrivial(scg);
  5750. }
  5751. // Accessing the members of anything else (arrays, rotations, vectors) is always trivial.
  5752. return true;
  5753. }
  5754. /**
  5755. * @brief Check to see if the case of calling an instance method of some object is trivial.
  5756. * @param scg = script making the call
  5757. * @param argsig = argument types of the call (used to select among overloads)
  5758. * @returns true iff we can tell at compile time that the call will always call a trivial method
  5759. */
  5760. public override bool IsCallTrivial(ScriptCodeGen scg, TokenType[] argsig)
  5761. {
  5762. // If getting pointer to instance isn't trivial, then calling the method isn't trivial either.
  5763. if(!baseRVal.IsRValTrivial(scg, null))
  5764. return false;
  5765. // Calling a method of a class depends on the method.
  5766. TokenType baseType = baseRVal.GetRValType(scg, null);
  5767. if(baseType is TokenTypeSDTypeClass TokenTypeSDTypeClassbaseType)
  5768. {
  5769. TokenDeclVar tvar = scg.FindThisMember(TokenTypeSDTypeClassbaseType, fieldName, argsig);
  5770. return (tvar != null) && tvar.IsFuncTrivial(scg);
  5771. }
  5772. // Calling via a pointer to an interface instance is never trivial.
  5773. // (It is really a pointer to an array of delegates).
  5774. // We can't tell for this call site whether the actual method being called is trivial or not,
  5775. // so we have to assume it isn't.
  5776. // ??? We could theoretically check to see if *all* implementations of this method of
  5777. // this interface are trivial, then we could conclude that this call is trivial.
  5778. if(baseType is TokenTypeSDTypeInterface)
  5779. return false;
  5780. // Calling a method of anything else (arrays, rotations, vectors) is always trivial.
  5781. // Even methods of delegates, such as ".GetArgTypes()" that we may someday do is trivial.
  5782. return true;
  5783. }
  5784. // debugging
  5785. public override void DebString(StringBuilder sb)
  5786. {
  5787. baseRVal.DebString(sb);
  5788. sb.Append('.');
  5789. sb.Append(fieldName.val);
  5790. }
  5791. }
  5792. /**
  5793. * @brief a name is being used as an L-value
  5794. */
  5795. public class TokenLValName: TokenLVal
  5796. {
  5797. public TokenName name;
  5798. public VarDict stack;
  5799. public TokenLValName(TokenName name, VarDict stack) : base(name)
  5800. {
  5801. // Save name of variable/method/function/field.
  5802. this.name = name;
  5803. // Save where in the stack it can be looked up.
  5804. // If the current stack is for locals, do not allow forward references.
  5805. // this allows idiocy like:
  5806. // list buttons = [ 1, 2, 3 ];
  5807. // x () {
  5808. // list buttons = llList2List (buttons, 0, 1);
  5809. // llOwnerSay (llList2CSV (buttons));
  5810. // }
  5811. // If it is not locals, allow forward references.
  5812. // this allows function X() to call Y() and Y() to call X().
  5813. this.stack = stack.FreezeLocals();
  5814. }
  5815. public override TokenType GetRValType(ScriptCodeGen scg, TokenType[] argsig)
  5816. {
  5817. TokenDeclVar var = scg.FindNamedVar(this, argsig);
  5818. if(var != null)
  5819. return var.type;
  5820. scg.ErrorMsg(name, "undefined name " + name.val + ScriptCodeGen.ArgSigString(argsig));
  5821. return new TokenTypeVoid(name);
  5822. }
  5823. public override bool IsRValTrivial(ScriptCodeGen scg, TokenType[] argsig)
  5824. {
  5825. TokenDeclVar var = scg.FindNamedVar(this, argsig);
  5826. return (var != null) && var.IsVarTrivial(scg);
  5827. }
  5828. /**
  5829. * @brief Check to see if the case of calling a global method is trivial.
  5830. * @param scg = script making the call
  5831. * @param argsig = argument types of the call (used to select among overloads)
  5832. * @returns true iff we can tell at compile time that the call will always call a trivial method
  5833. */
  5834. public override bool IsCallTrivial(ScriptCodeGen scg, TokenType[] argsig)
  5835. {
  5836. TokenDeclVar var = scg.FindNamedVar(this, argsig);
  5837. return (var != null) && var.IsFuncTrivial(scg);
  5838. }
  5839. // debugging
  5840. public override void DebString(StringBuilder sb)
  5841. {
  5842. sb.Append(name.val);
  5843. }
  5844. }
  5845. /**
  5846. * @brief a static field within a struct is an L-value
  5847. */
  5848. public class TokenLValSField: TokenLVal
  5849. {
  5850. public TokenType baseType;
  5851. public TokenName fieldName;
  5852. public TokenLValSField(Token original) : base(original) { }
  5853. public override TokenType GetRValType(ScriptCodeGen scg, TokenType[] argsig)
  5854. {
  5855. if(baseType is TokenTypeSDTypeClass TokenTypeSDTypeClassbaseType)
  5856. {
  5857. TokenDeclVar var = scg.FindThisMember(TokenTypeSDTypeClassbaseType, fieldName, argsig);
  5858. if(var != null)
  5859. return var.type;
  5860. }
  5861. scg.ErrorMsg(fieldName, "unknown member of " + baseType.ToString());
  5862. return new TokenTypeVoid(fieldName);
  5863. }
  5864. public override bool IsRValTrivial(ScriptCodeGen scg, TokenType[] argsig)
  5865. {
  5866. // Accessing a member of a class depends on the member.
  5867. // In the case of a method, this is accessing it as a delegate, not calling it, and
  5868. // argsig simply serves as selecting which of possibly overloaded methods to select.
  5869. // The case of accessing a property, however, depends on the property implementation,
  5870. // as there could be looping inside the property code.
  5871. if(baseType is TokenTypeSDTypeClass TokenTypeSDTypeClassbaseType)
  5872. {
  5873. TokenDeclVar tvar = scg.FindThisMember(TokenTypeSDTypeClassbaseType, fieldName, argsig);
  5874. return (tvar != null) && tvar.IsVarTrivial(scg);
  5875. }
  5876. // Accessing the fields/methods/properties of anything else (arrays, rotations, vectors) is always trivial.
  5877. return true;
  5878. }
  5879. /**
  5880. * @brief Check to see if the case of calling a class' static method is trivial.
  5881. * @param scg = script making the call
  5882. * @param argsig = argument types of the call (used to select among overloads)
  5883. * @returns true iff we can tell at compile time that the call will always call a trivial method
  5884. */
  5885. public override bool IsCallTrivial(ScriptCodeGen scg, TokenType[] argsig)
  5886. {
  5887. // Calling a static method of a class depends on the method.
  5888. if(baseType is TokenTypeSDTypeClass TokenTypeSDTypeClassbaseType)
  5889. {
  5890. TokenDeclVar tvar = scg.FindThisMember(TokenTypeSDTypeClassbaseType, fieldName, argsig);
  5891. return (tvar != null) && tvar.IsFuncTrivial(scg);
  5892. }
  5893. // Calling a static method of anything else (arrays, rotations, vectors) is always trivial.
  5894. return true;
  5895. }
  5896. public override void DebString(StringBuilder sb)
  5897. {
  5898. if(fieldName.val == "$new")
  5899. {
  5900. sb.Append("new ");
  5901. baseType.DebString(sb);
  5902. }
  5903. else
  5904. {
  5905. baseType.DebString(sb);
  5906. sb.Append('.');
  5907. fieldName.DebString(sb);
  5908. }
  5909. }
  5910. }
  5911. /**
  5912. * @brief any expression that can go on right side of "="
  5913. */
  5914. public delegate TokenRVal TCCLookup(TokenRVal rVal, ref bool didOne);
  5915. public abstract class TokenRVal: Token
  5916. {
  5917. public TokenRVal(Token original) : base(original) { }
  5918. /**
  5919. * @brief Tell us the type of the expression.
  5920. */
  5921. public abstract TokenType GetRValType(ScriptCodeGen scg, TokenType[] argsig);
  5922. /**
  5923. * @brief Tell us if reading and writing the value is trivial.
  5924. *
  5925. * @param scg = script code generator of script making the access
  5926. * @param argsig = argument types of the call (used to select among overloads)
  5927. * @returns true: we can tell at compile time that reading/writing this location
  5928. * will always be trivial (no looping or CheckRun() calls possible).
  5929. * false: otherwise
  5930. */
  5931. public abstract bool IsRValTrivial(ScriptCodeGen scg, TokenType[] argsig);
  5932. /**
  5933. * @brief Tell us if calling the method is trivial.
  5934. *
  5935. * This is the default implementation that returns false.
  5936. * It is only used if the location is holding a delegate
  5937. * and the method that the delegate is pointing to is being
  5938. * called. Since we can't tell if the actual runtime method
  5939. * is trivial or not, we assume it isn't.
  5940. *
  5941. * For the more usual ways of calling functions, see the
  5942. * various overrides of IsCallTrivial().
  5943. *
  5944. * @param scg = script code generator of script making the call
  5945. * @param argsig = argument types of the call (used to select among overloads)
  5946. * @returns true: we can tell at compile time that this call will always
  5947. * be to a trivial function/method (no looping or CheckRun()
  5948. * calls possible).
  5949. * false: otherwise
  5950. */
  5951. public virtual bool IsCallTrivial(ScriptCodeGen scg, TokenType[] argsig)
  5952. {
  5953. return false;
  5954. }
  5955. /**
  5956. * @brief If the result of the expression is a constant,
  5957. * create a TokenRValConst equivalent, set didOne, and return that.
  5958. * Otherwise, just return the original without changing didOne.
  5959. */
  5960. public virtual TokenRVal TryComputeConstant(TCCLookup lookup, ref bool didOne)
  5961. {
  5962. return lookup(this, ref didOne);
  5963. }
  5964. }
  5965. /**
  5966. * @brief a postfix operator and corresponding L-value
  5967. */
  5968. public class TokenRValAsnPost: TokenRVal
  5969. {
  5970. public TokenLVal lVal;
  5971. public Token postfix;
  5972. public TokenRValAsnPost(Token original) : base(original) { }
  5973. public override TokenType GetRValType(ScriptCodeGen scg, TokenType[] argsig)
  5974. {
  5975. return lVal.GetRValType(scg, argsig);
  5976. }
  5977. public override bool IsRValTrivial(ScriptCodeGen scg, TokenType[] argsig)
  5978. {
  5979. return lVal.IsRValTrivial(scg, null);
  5980. }
  5981. public override void DebString(StringBuilder sb)
  5982. {
  5983. lVal.DebString(sb);
  5984. sb.Append(' ');
  5985. postfix.DebString(sb);
  5986. }
  5987. }
  5988. /**
  5989. * @brief a prefix operator and corresponding L-value
  5990. */
  5991. public class TokenRValAsnPre: TokenRVal
  5992. {
  5993. public Token prefix;
  5994. public TokenLVal lVal;
  5995. public TokenRValAsnPre(Token original) : base(original) { }
  5996. public override TokenType GetRValType(ScriptCodeGen scg, TokenType[] argsig)
  5997. {
  5998. return lVal.GetRValType(scg, argsig);
  5999. }
  6000. public override bool IsRValTrivial(ScriptCodeGen scg, TokenType[] argsig)
  6001. {
  6002. return lVal.IsRValTrivial(scg, null);
  6003. }
  6004. public override void DebString(StringBuilder sb)
  6005. {
  6006. prefix.DebString(sb);
  6007. sb.Append(' ');
  6008. lVal.DebString(sb);
  6009. }
  6010. }
  6011. /**
  6012. * @brief calling a function or method, ie, may have side-effects
  6013. */
  6014. public class TokenRValCall: TokenRVal
  6015. {
  6016. public TokenRVal meth; // points to the function to be called
  6017. // - might be a reference to a global function (TokenLValName)
  6018. // - or an instance method of a class (TokenLValIField)
  6019. // - or a static method of a class (TokenLValSField)
  6020. // - or a delegate stored in a variable (assumption for anything else)
  6021. public TokenRVal args; // null-terminated TokenRVal list
  6022. public int nArgs; // number of elements in args
  6023. public TokenRValCall(Token original) : base(original) { }
  6024. private TokenType[] myArgSig;
  6025. /**
  6026. * @brief The type of a call is the type of the return value.
  6027. */
  6028. public override TokenType GetRValType(ScriptCodeGen scg, TokenType[] argsig)
  6029. {
  6030. // Build type signature so we select correct overloaded function.
  6031. if(myArgSig == null)
  6032. {
  6033. myArgSig = new TokenType[nArgs];
  6034. int i = 0;
  6035. for(Token t = args; t != null; t = t.nextToken)
  6036. {
  6037. myArgSig[i++] = ((TokenRVal)t).GetRValType(scg, null);
  6038. }
  6039. }
  6040. // Get the type of the method itself. This should get us a delegate type.
  6041. TokenType delType = meth.GetRValType(scg, myArgSig);
  6042. if(delType is not TokenTypeSDTypeDelegate)
  6043. {
  6044. scg.ErrorMsg(meth, "must be function or method");
  6045. return new TokenTypeVoid(meth);
  6046. }
  6047. // Get the return type from the delegate type.
  6048. return ((TokenTypeSDTypeDelegate)delType).decl.GetRetType();
  6049. }
  6050. /**
  6051. * @brief See if the call to the function/method is trivial.
  6052. * It is trivial if all the argument computations are trivial and
  6053. * the function is not being called via virtual table or delegate
  6054. * and the function body is trivial.
  6055. */
  6056. public override bool IsRValTrivial(ScriptCodeGen scg, TokenType[] argsig)
  6057. {
  6058. // Build type signature so we select correct overloaded function.
  6059. if(myArgSig == null)
  6060. {
  6061. myArgSig = new TokenType[nArgs];
  6062. int i = 0;
  6063. for(Token t = args; t != null; t = t.nextToken)
  6064. {
  6065. myArgSig[i++] = ((TokenRVal)t).GetRValType(scg, null);
  6066. }
  6067. }
  6068. // Make sure all arguments can be computed trivially.
  6069. for(Token t = args; t != null; t = t.nextToken)
  6070. {
  6071. if(!((TokenRVal)t).IsRValTrivial(scg, null))
  6072. return false;
  6073. }
  6074. // See if the function call itself and the function body are trivial.
  6075. return meth.IsCallTrivial(scg, myArgSig);
  6076. }
  6077. // debugging
  6078. public override void DebString(StringBuilder sb)
  6079. {
  6080. meth.DebString(sb);
  6081. sb.Append(" (");
  6082. bool first = true;
  6083. for(Token t = args; t != null; t = t.nextToken)
  6084. {
  6085. if(!first)
  6086. sb.Append(", ");
  6087. t.DebString(sb);
  6088. first = false;
  6089. }
  6090. sb.Append(')');
  6091. }
  6092. }
  6093. /**
  6094. * @brief encapsulates a typecast, ie, (type)
  6095. */
  6096. public class TokenRValCast: TokenRVal
  6097. {
  6098. public TokenType castTo;
  6099. public TokenRVal rVal;
  6100. public TokenRValCast(TokenType type, TokenRVal value) : base(type)
  6101. {
  6102. castTo = type;
  6103. rVal = value;
  6104. }
  6105. public override TokenType GetRValType(ScriptCodeGen scg, TokenType[] argsig)
  6106. {
  6107. return castTo;
  6108. }
  6109. public override bool IsRValTrivial(ScriptCodeGen scg, TokenType[] argsig)
  6110. {
  6111. if(castTo is TokenTypeSDTypeDelegate tokencastto)
  6112. argsig = tokencastto.decl.GetArgTypes();
  6113. else
  6114. argsig = null;
  6115. return rVal.IsRValTrivial(scg, argsig);
  6116. }
  6117. /**
  6118. * @brief If operand is constant, maybe we can say the whole thing is a constant.
  6119. */
  6120. public override TokenRVal TryComputeConstant(TCCLookup lookup, ref bool didOne)
  6121. {
  6122. rVal = rVal.TryComputeConstant(lookup, ref didOne);
  6123. if(rVal is TokenRValConst TokenRValConstrVal)
  6124. {
  6125. try
  6126. {
  6127. object val = TokenRValConstrVal.val;
  6128. object nval = null;
  6129. if(castTo is TokenTypeChar)
  6130. {
  6131. if(val is char)
  6132. return rVal;
  6133. if(val is int intval)
  6134. nval = (char)intval;
  6135. }
  6136. else if (castTo is TokenTypeFloat)
  6137. {
  6138. if(val is double)
  6139. return rVal;
  6140. if(val is int intval)
  6141. nval = (double)intval;
  6142. if(val is string sval)
  6143. nval = new LSL_Float(sval).value;
  6144. }
  6145. else if (castTo is TokenTypeInt)
  6146. {
  6147. if(val is int)
  6148. return rVal;
  6149. if(val is char charval)
  6150. nval = (int)charval;
  6151. if(val is double dval)
  6152. nval = (int)dval;
  6153. if(val is string sval)
  6154. nval = new LSL_Integer(sval).value;
  6155. }
  6156. else if (castTo is TokenTypeRot)
  6157. {
  6158. if(val is LSL_Rotation)
  6159. return rVal;
  6160. if(val is string sval)
  6161. nval = new LSL_Rotation(sval);
  6162. }
  6163. else if ((castTo is TokenTypeKey) || (castTo is TokenTypeStr))
  6164. {
  6165. if(val is string)
  6166. nval = val; // in case of key/string conversion
  6167. if(val is char cval)
  6168. nval = TypeCast.CharToString(cval);
  6169. if(val is double dval)
  6170. nval = TypeCast.FloatToString(dval);
  6171. if(val is int ival)
  6172. nval = TypeCast.IntegerToString(ival);
  6173. if(val is LSL_Rotation lslrot)
  6174. nval = TypeCast.RotationToString(lslrot);
  6175. if(val is LSL_Vector lslvec)
  6176. nval = TypeCast.VectorToString(lslvec);
  6177. }
  6178. else if (castTo is TokenTypeVec)
  6179. {
  6180. if(val is LSL_Vector)
  6181. return rVal;
  6182. if(val is string sval)
  6183. nval = new LSL_Vector(sval);
  6184. }
  6185. if(nval != null)
  6186. {
  6187. TokenRVal rValConst = new TokenRValConst(castTo, nval);
  6188. didOne = true;
  6189. return rValConst;
  6190. }
  6191. }
  6192. catch
  6193. {
  6194. }
  6195. }
  6196. return this;
  6197. }
  6198. public override void DebString(StringBuilder sb)
  6199. {
  6200. sb.Append('(');
  6201. castTo.DebString(sb);
  6202. sb.Append(')');
  6203. rVal.DebString(sb);
  6204. }
  6205. }
  6206. /**
  6207. * @brief Encapsulate a conditional expression:
  6208. * <condExpr> ? <trueExpr> : <falseExpr>
  6209. */
  6210. public class TokenRValCondExpr: TokenRVal
  6211. {
  6212. public TokenRVal condExpr;
  6213. public TokenRVal trueExpr;
  6214. public TokenRVal falseExpr;
  6215. public TokenRValCondExpr(Token original) : base(original)
  6216. {
  6217. }
  6218. public override TokenType GetRValType(ScriptCodeGen scg, TokenType[] argsig)
  6219. {
  6220. TokenType trueType = trueExpr.GetRValType(scg, argsig);
  6221. TokenType falseType = falseExpr.GetRValType(scg, argsig);
  6222. if(trueType.ToString() != falseType.ToString())
  6223. {
  6224. scg.ErrorMsg(condExpr, "true & false expr types don't match");
  6225. }
  6226. return trueType;
  6227. }
  6228. public override bool IsRValTrivial(ScriptCodeGen scg, TokenType[] argsig)
  6229. {
  6230. return condExpr.IsRValTrivial(scg, null) &&
  6231. trueExpr.IsRValTrivial(scg, argsig) &&
  6232. falseExpr.IsRValTrivial(scg, argsig);
  6233. }
  6234. /**
  6235. * @brief If condition is constant, then the whole expression is constant
  6236. * iff the corresponding trueExpr or falseExpr is constant.
  6237. */
  6238. public override TokenRVal TryComputeConstant(TCCLookup lookup, ref bool didOne)
  6239. {
  6240. TokenRVal rValCond = condExpr.TryComputeConstant(lookup, ref didOne);
  6241. if(rValCond is TokenRValConst TokenRValConstrValCond)
  6242. {
  6243. didOne = true;
  6244. return (TokenRValConstrValCond.IsConstBoolTrue() ? trueExpr : falseExpr).TryComputeConstant(lookup, ref didOne);
  6245. }
  6246. return this;
  6247. }
  6248. // debugging
  6249. public override void DebString(StringBuilder sb)
  6250. {
  6251. condExpr.DebString(sb);
  6252. sb.Append(" ? ");
  6253. trueExpr.DebString(sb);
  6254. sb.Append(" : ");
  6255. falseExpr.DebString(sb);
  6256. }
  6257. }
  6258. /**
  6259. * @brief all constants supposed to end up here
  6260. */
  6261. public enum TokenRValConstType: byte { CHAR = 0, FLOAT = 1, INT = 2, KEY = 3, STRING = 4 };
  6262. public class TokenRValConst: TokenRVal
  6263. {
  6264. public object val; // always a system type (char, int, double, string), never LSL-wrapped
  6265. public TokenRValConstType type;
  6266. public TokenType tokType;
  6267. public TokenRValConst(Token original, object value) : base(original)
  6268. {
  6269. val = value;
  6270. TokenType tt;
  6271. if(val is char)
  6272. {
  6273. type = TokenRValConstType.CHAR;
  6274. tt = new TokenTypeChar(this);
  6275. }
  6276. else if(val is int)
  6277. {
  6278. type = TokenRValConstType.INT;
  6279. tt = new TokenTypeInt(this);
  6280. }
  6281. else if(val is double)
  6282. {
  6283. type = TokenRValConstType.FLOAT;
  6284. tt = new TokenTypeFloat(this);
  6285. }
  6286. else if(val is string)
  6287. {
  6288. type = TokenRValConstType.STRING;
  6289. tt = new TokenTypeStr(this);
  6290. }
  6291. else
  6292. {
  6293. throw new Exception("invalid constant type " + val.GetType());
  6294. }
  6295. tokType = (original is TokenType type1) ? type1 : tt;
  6296. if(tokType is TokenTypeKey)
  6297. {
  6298. type = TokenRValConstType.KEY;
  6299. }
  6300. }
  6301. public override TokenType GetRValType(ScriptCodeGen scg, TokenType[] argsig)
  6302. {
  6303. return tokType;
  6304. }
  6305. public override bool IsRValTrivial(ScriptCodeGen scg, TokenType[] argsig)
  6306. {
  6307. return true;
  6308. }
  6309. public CompValu GetCompValu()
  6310. {
  6311. switch(type)
  6312. {
  6313. case TokenRValConstType.CHAR:
  6314. {
  6315. return new CompValuChar(tokType, (char)val);
  6316. }
  6317. case TokenRValConstType.FLOAT:
  6318. {
  6319. return new CompValuFloat(tokType, (double)val);
  6320. }
  6321. case TokenRValConstType.INT:
  6322. {
  6323. return new CompValuInteger(tokType, (int)val);
  6324. }
  6325. case TokenRValConstType.KEY:
  6326. case TokenRValConstType.STRING:
  6327. {
  6328. return new CompValuString(tokType, (string)val);
  6329. }
  6330. default:
  6331. throw new Exception("unknown type");
  6332. }
  6333. }
  6334. public override TokenRVal TryComputeConstant(TCCLookup lookup, ref bool didOne)
  6335. {
  6336. // gotta end somewhere
  6337. return this;
  6338. }
  6339. public bool IsConstBoolTrue()
  6340. {
  6341. switch(type)
  6342. {
  6343. case TokenRValConstType.CHAR:
  6344. {
  6345. return (char)val != 0;
  6346. }
  6347. case TokenRValConstType.FLOAT:
  6348. {
  6349. return (double)val != 0;
  6350. }
  6351. case TokenRValConstType.INT:
  6352. {
  6353. return (int)val != 0;
  6354. }
  6355. case TokenRValConstType.KEY:
  6356. {
  6357. return (string)val != "" && (string)val != ScriptBaseClass.NULL_KEY;
  6358. }
  6359. case TokenRValConstType.STRING:
  6360. {
  6361. return (string)val != "";
  6362. }
  6363. default:
  6364. throw new Exception("unknown type");
  6365. }
  6366. }
  6367. public override void DebString(StringBuilder sb)
  6368. {
  6369. if(val is char charval)
  6370. {
  6371. sb.Append('\'');
  6372. EscapeQuotes(sb, new string(new char[] { charval }));
  6373. sb.Append('\'');
  6374. }
  6375. else if(val is int intval)
  6376. {
  6377. sb.Append(intval);
  6378. }
  6379. else if(val is double dval)
  6380. {
  6381. string str = dval.ToString();
  6382. sb.Append(str);
  6383. if((str.IndexOf('.') < 0) &&
  6384. (str.IndexOf('E') < 0) &&
  6385. (str.IndexOf('e') < 0))
  6386. {
  6387. sb.Append(".0");
  6388. }
  6389. }
  6390. else if(val is string sval)
  6391. {
  6392. sb.Append('"');
  6393. EscapeQuotes(sb, sval);
  6394. sb.Append('"');
  6395. }
  6396. else
  6397. {
  6398. throw new Exception("invalid constant type " + val.GetType());
  6399. }
  6400. }
  6401. private static void EscapeQuotes(StringBuilder sb, string s)
  6402. {
  6403. foreach(char c in s)
  6404. {
  6405. switch(c)
  6406. {
  6407. case '\n':
  6408. {
  6409. sb.Append("\\n");
  6410. break;
  6411. }
  6412. case '\t':
  6413. {
  6414. sb.Append("\\t");
  6415. break;
  6416. }
  6417. case '\\':
  6418. {
  6419. sb.Append("\\\\");
  6420. break;
  6421. }
  6422. case '\'':
  6423. {
  6424. sb.Append("\\'");
  6425. break;
  6426. }
  6427. case '\"':
  6428. {
  6429. sb.Append("\\\"");
  6430. break;
  6431. }
  6432. default:
  6433. {
  6434. sb.Append(c);
  6435. break;
  6436. }
  6437. }
  6438. }
  6439. }
  6440. }
  6441. /**
  6442. * @brief Default initialization value for the corresponding variable.
  6443. */
  6444. public class TokenRValInitDef: TokenRVal
  6445. {
  6446. public TokenType type;
  6447. public static TokenRValInitDef Construct(TokenDeclVar tokenDeclVar)
  6448. {
  6449. TokenRValInitDef zhis = new(tokenDeclVar)
  6450. {
  6451. type = tokenDeclVar.type
  6452. };
  6453. return zhis;
  6454. }
  6455. private TokenRValInitDef(Token original) : base(original) { }
  6456. public override TokenType GetRValType(ScriptCodeGen scg, TokenType[] argsig)
  6457. {
  6458. return type;
  6459. }
  6460. public override bool IsRValTrivial(ScriptCodeGen scg, TokenType[] argsig)
  6461. {
  6462. // it's always just a constant so it's always very trivial
  6463. return true;
  6464. }
  6465. public override void DebString(StringBuilder sb)
  6466. {
  6467. sb.Append("<default ");
  6468. sb.Append(type.ToString());
  6469. sb.Append('>');
  6470. }
  6471. }
  6472. /**
  6473. * @brief encapsulation of <rval> is <typeexp>
  6474. */
  6475. public class TokenRValIsType: TokenRVal
  6476. {
  6477. public TokenRVal rValExp;
  6478. public TokenTypeExp typeExp;
  6479. public TokenRValIsType(Token original) : base(original) { }
  6480. public override TokenType GetRValType(ScriptCodeGen scg, TokenType[] argsig)
  6481. {
  6482. return new TokenTypeBool(rValExp);
  6483. }
  6484. public override bool IsRValTrivial(ScriptCodeGen scg, TokenType[] argsig)
  6485. {
  6486. return rValExp.IsRValTrivial(scg, argsig);
  6487. }
  6488. }
  6489. /**
  6490. * @brief an R-value enclosed in brackets is an LSLList
  6491. */
  6492. public class TokenRValList: TokenRVal
  6493. {
  6494. public TokenRVal rVal; // null-terminated list of TokenRVal objects
  6495. public int nItems;
  6496. public TokenRValList(Token original) : base(original) { }
  6497. public override TokenType GetRValType(ScriptCodeGen scg, TokenType[] argsig)
  6498. {
  6499. return new TokenTypeList(rVal);
  6500. }
  6501. public override bool IsRValTrivial(ScriptCodeGen scg, TokenType[] argsig)
  6502. {
  6503. for(Token t = rVal; t != null; t = t.nextToken)
  6504. {
  6505. if(!((TokenRVal)t).IsRValTrivial(scg, null))
  6506. return false;
  6507. }
  6508. return true;
  6509. }
  6510. public override void DebString(StringBuilder sb)
  6511. {
  6512. bool first = true;
  6513. sb.Append('[');
  6514. for(Token t = rVal; t != null; t = t.nextToken)
  6515. {
  6516. if(!first)
  6517. sb.Append(',');
  6518. sb.Append(' ');
  6519. t.DebString(sb);
  6520. first = false;
  6521. }
  6522. sb.Append(" ]");
  6523. }
  6524. }
  6525. /**
  6526. * @brief encapsulates '$new' arraytype '{' ... '}'
  6527. */
  6528. public class TokenRValNewArIni: TokenRVal
  6529. {
  6530. public TokenType arrayType;
  6531. public TokenList valueList; // TokenList : a sub-list
  6532. // TokenKwComma : a default value
  6533. // TokenRVal : init expression
  6534. public TokenRValNewArIni(Token original) : base(original)
  6535. {
  6536. valueList = new TokenList(original);
  6537. }
  6538. // type of the expression = the array type allocated by $new()
  6539. public override TokenType GetRValType(ScriptCodeGen scg, TokenType[] argsig)
  6540. {
  6541. return arrayType;
  6542. }
  6543. // The expression is trivial if all the initializers are trivial.
  6544. // An array's constructor is always trivial (no CheckRun() calls).
  6545. public override bool IsRValTrivial(ScriptCodeGen scg, TokenType[] argsig)
  6546. {
  6547. return ListIsTrivial(scg, valueList);
  6548. }
  6549. private bool ListIsTrivial(ScriptCodeGen scg, TokenList valList)
  6550. {
  6551. foreach(Token val in valList.tl)
  6552. {
  6553. if(val is TokenRVal TokenRValval)
  6554. {
  6555. if(!TokenRValval.IsRValTrivial(scg, null))
  6556. return false;
  6557. }
  6558. if(val is TokenList TokenListval)
  6559. {
  6560. if(!ListIsTrivial(scg, TokenListval))
  6561. return false;
  6562. }
  6563. }
  6564. return true;
  6565. }
  6566. public override void DebString(StringBuilder sb)
  6567. {
  6568. sb.Append("new ");
  6569. arrayType.DebString(sb);
  6570. sb.Append(' ');
  6571. valueList.DebString(sb);
  6572. }
  6573. }
  6574. public class TokenList: Token
  6575. {
  6576. public List<Token> tl = new();
  6577. public TokenList(Token original) : base(original) { }
  6578. public override void DebString(StringBuilder sb)
  6579. {
  6580. sb.Append('{');
  6581. bool first = true;
  6582. foreach(Token t in tl)
  6583. {
  6584. if(!first)
  6585. sb.Append(", ");
  6586. t.DebString(sb);
  6587. first = false;
  6588. }
  6589. sb.Append('}');
  6590. }
  6591. }
  6592. /**
  6593. * @brief a binary operator and its two operands
  6594. */
  6595. public class TokenRValOpBin: TokenRVal
  6596. {
  6597. public TokenRVal rValLeft;
  6598. public TokenKw opcode;
  6599. public TokenRVal rValRight;
  6600. public TokenRValOpBin(TokenRVal left, TokenKw op, TokenRVal right) : base(op)
  6601. {
  6602. rValLeft = left;
  6603. opcode = op;
  6604. rValRight = right;
  6605. }
  6606. public override TokenType GetRValType(ScriptCodeGen scg, TokenType[] argsig)
  6607. {
  6608. // Comparisons and the like always return bool.
  6609. string opstr = opcode.ToString();
  6610. if((opstr == "==") || (opstr == "!=") || (opstr == ">=") || (opstr == ">") ||
  6611. (opstr == "&&") || (opstr == "||") || (opstr == "<=") || (opstr == "<") ||
  6612. (opstr == "&&&") || (opstr == "|||"))
  6613. {
  6614. return new TokenTypeBool(opcode);
  6615. }
  6616. // Comma is always type of right-hand operand.
  6617. if(opstr == ",")
  6618. return rValRight.GetRValType(scg, argsig);
  6619. // Assignments are always the type of the left-hand operand,
  6620. // including stuff like "+=".
  6621. if(opstr.EndsWith("="))
  6622. {
  6623. return rValLeft.GetRValType(scg, argsig);
  6624. }
  6625. // string+something or something+string is always string.
  6626. // except list+something or something+list is always a list.
  6627. string lType = rValLeft.GetRValType(scg, argsig).ToString();
  6628. string rType = rValRight.GetRValType(scg, argsig).ToString();
  6629. if((opstr == "+") && ((lType == "list") || (rType == "list")))
  6630. {
  6631. return new TokenTypeList(opcode);
  6632. }
  6633. if((opstr == "+") && ((lType == "key") || (lType == "string") ||
  6634. (rType == "key") || (rType == "string")))
  6635. {
  6636. return new TokenTypeStr(opcode);
  6637. }
  6638. // Everything else depends on both operands.
  6639. string key = lType + opstr + rType;
  6640. if(BinOpStr.defined.TryGetValue(key, out BinOpStr binOpStr))
  6641. {
  6642. return TokenType.FromSysType(opcode, binOpStr.outtype);
  6643. }
  6644. scg.ErrorMsg(opcode, "undefined operation " + key);
  6645. return new TokenTypeVoid(opcode);
  6646. }
  6647. public override bool IsRValTrivial(ScriptCodeGen scg, TokenType[] argsig)
  6648. {
  6649. return rValLeft.IsRValTrivial(scg, null) && rValRight.IsRValTrivial(scg, null);
  6650. }
  6651. /**
  6652. * @brief If both operands are constants, maybe we can say the whole thing is a constant.
  6653. */
  6654. public override TokenRVal TryComputeConstant(TCCLookup lookup, ref bool didOne)
  6655. {
  6656. rValLeft = rValLeft.TryComputeConstant(lookup, ref didOne);
  6657. rValRight = rValRight.TryComputeConstant(lookup, ref didOne);
  6658. if((rValLeft is TokenRValConst TRValConstrValLeft) && (rValRight is TokenRValConst TRValConstrValRight))
  6659. {
  6660. //try
  6661. {
  6662. object val = opcode.binOpConst(TRValConstrValLeft.val, TRValConstrValRight.val);
  6663. TokenRVal rValConst = new TokenRValConst(opcode, val);
  6664. didOne = true;
  6665. return rValConst;
  6666. }
  6667. //catch
  6668. {
  6669. }
  6670. }
  6671. return this;
  6672. }
  6673. // debugging
  6674. public override void DebString(StringBuilder sb)
  6675. {
  6676. rValLeft.DebString(sb);
  6677. sb.Append(' ');
  6678. sb.Append(opcode.ToString());
  6679. sb.Append(' ');
  6680. rValRight.DebString(sb);
  6681. }
  6682. }
  6683. /**
  6684. * @brief an unary operator and its one operand
  6685. */
  6686. public class TokenRValOpUn: TokenRVal
  6687. {
  6688. public TokenKw opcode;
  6689. public TokenRVal rVal;
  6690. public TokenRValOpUn(TokenKw op, TokenRVal right) : base(op)
  6691. {
  6692. opcode = op;
  6693. rVal = right;
  6694. }
  6695. public override TokenType GetRValType(ScriptCodeGen scg, TokenType[] argsig)
  6696. {
  6697. if(opcode is TokenKwExclam)
  6698. return new TokenTypeInt(opcode);
  6699. return rVal.GetRValType(scg, null);
  6700. }
  6701. public override bool IsRValTrivial(ScriptCodeGen scg, TokenType[] argsig)
  6702. {
  6703. return rVal.IsRValTrivial(scg, null);
  6704. }
  6705. /**
  6706. * @brief If operand is constant, maybe we can say the whole thing is a constant.
  6707. */
  6708. public override TokenRVal TryComputeConstant(TCCLookup lookup, ref bool didOne)
  6709. {
  6710. rVal = rVal.TryComputeConstant(lookup, ref didOne);
  6711. if(rVal is TokenRValConst TokenRValConstrVal)
  6712. {
  6713. try
  6714. {
  6715. object val = opcode.unOpConst(TokenRValConstrVal.val);
  6716. TokenRVal rValConst = new TokenRValConst(opcode, val);
  6717. didOne = true;
  6718. return rValConst;
  6719. }
  6720. catch
  6721. {
  6722. }
  6723. }
  6724. return this;
  6725. }
  6726. /**
  6727. * @brief Serialization/Deserialization.
  6728. */
  6729. public TokenRValOpUn(Token original) : base(original) { }
  6730. // debugging
  6731. public override void DebString(StringBuilder sb)
  6732. {
  6733. sb.Append(opcode.ToString());
  6734. rVal.DebString(sb);
  6735. }
  6736. }
  6737. /**
  6738. * @brief an R-value enclosed in parentheses
  6739. */
  6740. public class TokenRValParen: TokenRVal
  6741. {
  6742. public TokenRVal rVal;
  6743. public TokenRValParen(Token original) : base(original) { }
  6744. public override TokenType GetRValType(ScriptCodeGen scg, TokenType[] argsig)
  6745. {
  6746. // pass argsig through in this simple case, ie, let
  6747. // them do something like (llOwnerSay)("blabla...");
  6748. return rVal.GetRValType(scg, argsig);
  6749. }
  6750. public override bool IsRValTrivial(ScriptCodeGen scg, TokenType[] argsig)
  6751. {
  6752. // pass argsig through in this simple case, ie, let
  6753. // them do something like (llOwnerSay)("blabla...");
  6754. return rVal.IsRValTrivial(scg, argsig);
  6755. }
  6756. /**
  6757. * @brief If operand is constant, we can say the whole thing is a constant.
  6758. */
  6759. public override TokenRVal TryComputeConstant(TCCLookup lookup, ref bool didOne)
  6760. {
  6761. rVal = rVal.TryComputeConstant(lookup, ref didOne);
  6762. if(rVal is TokenRValConst)
  6763. {
  6764. didOne = true;
  6765. return rVal;
  6766. }
  6767. return this;
  6768. }
  6769. public override void DebString(StringBuilder sb)
  6770. {
  6771. sb.Append('(');
  6772. rVal.DebString(sb);
  6773. sb.Append(')');
  6774. }
  6775. }
  6776. public class TokenRValRot: TokenRVal
  6777. {
  6778. public TokenRVal xRVal;
  6779. public TokenRVal yRVal;
  6780. public TokenRVal zRVal;
  6781. public TokenRVal wRVal;
  6782. public TokenRValRot(Token original) : base(original) { }
  6783. public override TokenType GetRValType(ScriptCodeGen scg, TokenType[] argsig)
  6784. {
  6785. return new TokenTypeRot(xRVal);
  6786. }
  6787. public override bool IsRValTrivial(ScriptCodeGen scg, TokenType[] argsig)
  6788. {
  6789. return xRVal.IsRValTrivial(scg, null) &&
  6790. yRVal.IsRValTrivial(scg, null) &&
  6791. zRVal.IsRValTrivial(scg, null) &&
  6792. wRVal.IsRValTrivial(scg, null);
  6793. }
  6794. public override void DebString(StringBuilder sb)
  6795. {
  6796. sb.Append('<');
  6797. xRVal.DebString(sb);
  6798. sb.Append(',');
  6799. yRVal.DebString(sb);
  6800. sb.Append(',');
  6801. zRVal.DebString(sb);
  6802. sb.Append(',');
  6803. wRVal.DebString(sb);
  6804. sb.Append('>');
  6805. }
  6806. }
  6807. /**
  6808. * @brief 'this' is being used as an rval inside an instance method.
  6809. */
  6810. public class TokenRValThis: TokenRVal
  6811. {
  6812. public Token original;
  6813. public TokenDeclSDTypeClass sdtClass;
  6814. public TokenRValThis(Token original, TokenDeclSDTypeClass sdtClass) : base(original)
  6815. {
  6816. this.original = original;
  6817. this.sdtClass = sdtClass;
  6818. }
  6819. public override TokenType GetRValType(ScriptCodeGen scg, TokenType[] argsig)
  6820. {
  6821. return sdtClass.MakeRefToken(original);
  6822. }
  6823. public override bool IsRValTrivial(ScriptCodeGen scg, TokenType[] argsig)
  6824. {
  6825. return true; // ldarg.0/starg.0 can't possibly loop
  6826. }
  6827. // debugging
  6828. public override void DebString(StringBuilder sb)
  6829. {
  6830. sb.Append("this");
  6831. }
  6832. }
  6833. /**
  6834. * @brief the 'undef' keyword is being used as a value in an expression.
  6835. * It is the null object pointer and has type TokenTypeUndef.
  6836. */
  6837. public class TokenRValUndef: TokenRVal
  6838. {
  6839. readonly Token original;
  6840. public TokenRValUndef(Token original) : base(original)
  6841. {
  6842. this.original = original;
  6843. }
  6844. public override TokenType GetRValType(ScriptCodeGen scg, TokenType[] argsig)
  6845. {
  6846. return new TokenTypeUndef(original);
  6847. }
  6848. public override bool IsRValTrivial(ScriptCodeGen scg, TokenType[] argsig)
  6849. {
  6850. return true;
  6851. }
  6852. public override void DebString(StringBuilder sb)
  6853. {
  6854. sb.Append("undef");
  6855. }
  6856. }
  6857. /**
  6858. * @brief put 3 RVals together as a Vector value.
  6859. */
  6860. public class TokenRValVec: TokenRVal
  6861. {
  6862. public TokenRVal xRVal;
  6863. public TokenRVal yRVal;
  6864. public TokenRVal zRVal;
  6865. public TokenRValVec(Token original) : base(original) { }
  6866. public override TokenType GetRValType(ScriptCodeGen scg, TokenType[] argsig)
  6867. {
  6868. return new TokenTypeVec(xRVal);
  6869. }
  6870. public override bool IsRValTrivial(ScriptCodeGen scg, TokenType[] argsig)
  6871. {
  6872. return xRVal.IsRValTrivial(scg, null) &&
  6873. yRVal.IsRValTrivial(scg, null) &&
  6874. zRVal.IsRValTrivial(scg, null);
  6875. }
  6876. public override void DebString(StringBuilder sb)
  6877. {
  6878. sb.Append('<');
  6879. xRVal.DebString(sb);
  6880. sb.Append(',');
  6881. yRVal.DebString(sb);
  6882. sb.Append(',');
  6883. zRVal.DebString(sb);
  6884. sb.Append('>');
  6885. }
  6886. }
  6887. /**
  6888. * @brief encapsulates the whole script in a single token
  6889. */
  6890. public class TokenScript: Token
  6891. {
  6892. public int expiryDays = Int32.MaxValue;
  6893. public TokenDeclState defaultState;
  6894. public Dictionary<string, TokenDeclState> states = new();
  6895. public VarDict variablesStack = new (false); // initial one is used for global functions and variables
  6896. public TokenDeclVar globalVarInit; // $globalvarinit function
  6897. // - performs explicit global var and static field inits
  6898. private Dictionary<string, TokenDeclSDType> sdSrcTypes = new();
  6899. private bool sdSrcTypesSealed = false;
  6900. public TokenScript(Token original) : base(original) { }
  6901. /*
  6902. * Handle variable definition stack.
  6903. * Generally a '{' pushes a new frame and a '}' pops the frame.
  6904. * Function parameters are pushed in an additional frame (just outside the body's { ... } block)
  6905. */
  6906. public void PushVarFrame(bool locals)
  6907. {
  6908. PushVarFrame(new VarDict(locals));
  6909. }
  6910. public void PushVarFrame(VarDict newFrame)
  6911. {
  6912. newFrame.outerVarDict = variablesStack;
  6913. variablesStack = newFrame;
  6914. }
  6915. public void PopVarFrame()
  6916. {
  6917. variablesStack = variablesStack.outerVarDict;
  6918. }
  6919. public bool AddVarEntry(TokenDeclVar var)
  6920. {
  6921. return variablesStack.AddEntry(var);
  6922. }
  6923. /*
  6924. * Handle list of script-defined types.
  6925. */
  6926. public void sdSrcTypesSeal()
  6927. {
  6928. sdSrcTypesSealed = true;
  6929. }
  6930. public bool sdSrcTypesContainsKey(string key)
  6931. {
  6932. return sdSrcTypes.ContainsKey(key);
  6933. }
  6934. public bool sdSrcTypesTryGetValue(string key, out TokenDeclSDType value)
  6935. {
  6936. return sdSrcTypes.TryGetValue(key, out value);
  6937. }
  6938. public void sdSrcTypesAdd(string key, TokenDeclSDType value)
  6939. {
  6940. if(sdSrcTypesSealed)
  6941. throw new Exception("sdSrcTypes is sealed");
  6942. value.sdTypeIndex = sdSrcTypes.Count;
  6943. sdSrcTypes.Add(key, value);
  6944. }
  6945. public void sdSrcTypesRep(string key, TokenDeclSDType value)
  6946. {
  6947. if(sdSrcTypesSealed)
  6948. throw new Exception("sdSrcTypes is sealed");
  6949. value.sdTypeIndex = sdSrcTypes[key].sdTypeIndex;
  6950. sdSrcTypes[key] = value;
  6951. }
  6952. public void sdSrcTypesReplace(string key, TokenDeclSDType value)
  6953. {
  6954. if(sdSrcTypesSealed)
  6955. throw new Exception("sdSrcTypes is sealed");
  6956. sdSrcTypes[key] = value;
  6957. }
  6958. public Dictionary<string, TokenDeclSDType>.ValueCollection sdSrcTypesValues
  6959. {
  6960. get
  6961. {
  6962. return sdSrcTypes.Values;
  6963. }
  6964. }
  6965. public int sdSrcTypesCount
  6966. {
  6967. get
  6968. {
  6969. return sdSrcTypes.Count;
  6970. }
  6971. }
  6972. /**
  6973. * @brief Debug output.
  6974. */
  6975. public override void DebString(StringBuilder sb)
  6976. {
  6977. /*
  6978. * Script-defined types.
  6979. */
  6980. foreach(TokenDeclSDType srcType in sdSrcTypes.Values)
  6981. {
  6982. srcType.DebString(sb);
  6983. }
  6984. /*
  6985. * Global constants.
  6986. * Variables are handled by outputting the $globalvarinit function.
  6987. */
  6988. foreach(TokenDeclVar var in variablesStack)
  6989. {
  6990. if(var.constant)
  6991. {
  6992. var.DebString(sb);
  6993. }
  6994. }
  6995. /*
  6996. * Global functions.
  6997. */
  6998. foreach(TokenDeclVar var in variablesStack)
  6999. {
  7000. if(var == globalVarInit)
  7001. {
  7002. var.DebStringInitFields(sb);
  7003. }
  7004. else if(var.retType != null)
  7005. {
  7006. var.DebString(sb);
  7007. }
  7008. }
  7009. /*
  7010. * States and their event handler functions.
  7011. */
  7012. defaultState.DebString(sb);
  7013. foreach(TokenDeclState st in states.Values)
  7014. {
  7015. st.DebString(sb);
  7016. }
  7017. }
  7018. }
  7019. /**
  7020. * @brief state body declaration
  7021. */
  7022. public class TokenStateBody: Token
  7023. {
  7024. public TokenDeclVar eventFuncs;
  7025. public int index = -1; // (codegen) row in ScriptHandlerEventTable (0=default)
  7026. public TokenStateBody(Token original) : base(original) { }
  7027. public override void DebString(StringBuilder sb)
  7028. {
  7029. sb.Append(" { ");
  7030. for(Token t = eventFuncs; t != null; t = t.nextToken)
  7031. {
  7032. t.DebString(sb);
  7033. }
  7034. sb.Append(" } ");
  7035. }
  7036. }
  7037. /**
  7038. * @brief a single statement, such as ending on a semicolon or enclosed in braces
  7039. * TokenStmt includes the terminating semicolon or the enclosing braces
  7040. * Also includes @label; for jump targets.
  7041. * Also includes stray ; null statements.
  7042. * Also includes local variable declarations with or without initialization value.
  7043. */
  7044. public class TokenStmt: Token
  7045. {
  7046. public TokenStmt(Token original) : base(original) { }
  7047. }
  7048. /**
  7049. * @brief a group of statements enclosed in braces
  7050. */
  7051. public class TokenStmtBlock: TokenStmt
  7052. {
  7053. public Token statements; // null-terminated list of statements, can also have TokenDeclVar's in here
  7054. public TokenStmtBlock outerStmtBlock; // next outer stmtBlock or null if top-level, ie, function definition
  7055. public TokenDeclVar function; // function it is part of
  7056. public bool isTry; // true iff it's a try statement block
  7057. public bool isCatch; // true iff it's a catch statement block
  7058. public bool isFinally; // true iff it's a finally statement block
  7059. public TokenStmtTry tryStmt; // set iff isTry|isCatch|isFinally is set
  7060. public TokenStmtBlock(Token original) : base(original) { }
  7061. // debugging
  7062. public override void DebString(StringBuilder sb)
  7063. {
  7064. sb.Append("{ ");
  7065. for(Token stmt = statements; stmt != null; stmt = stmt.nextToken)
  7066. {
  7067. stmt.DebString(sb);
  7068. }
  7069. sb.Append("} ");
  7070. }
  7071. }
  7072. /**
  7073. * @brief definition of branch target name
  7074. */
  7075. public class TokenStmtLabel: TokenStmt
  7076. {
  7077. public TokenName name; // the label's name
  7078. public TokenStmtBlock block; // which block it is defined in
  7079. public bool hasBkwdRefs = false;
  7080. public bool labelTagged; // code gen: location of label
  7081. public ScriptMyLabel labelStruct;
  7082. public TokenStmtLabel(Token original) : base(original) { }
  7083. public override void DebString(StringBuilder sb)
  7084. {
  7085. sb.Append('@');
  7086. name.DebString(sb);
  7087. sb.Append(';');
  7088. }
  7089. }
  7090. /**
  7091. * @brief those types of RVals with a semi-colon on the end
  7092. * that are allowed to stand alone as statements
  7093. */
  7094. public class TokenStmtRVal: TokenStmt
  7095. {
  7096. public TokenRVal rVal;
  7097. public TokenStmtRVal(Token original) : base(original) { }
  7098. // debugging
  7099. public override void DebString(StringBuilder sb)
  7100. {
  7101. rVal.DebString(sb);
  7102. sb.Append("; ");
  7103. }
  7104. }
  7105. public class TokenStmtBreak: TokenStmt
  7106. {
  7107. public TokenStmtBreak(Token original) : base(original) { }
  7108. public override void DebString(StringBuilder sb)
  7109. {
  7110. sb.Append("break;");
  7111. }
  7112. }
  7113. public class TokenStmtCont: TokenStmt
  7114. {
  7115. public TokenStmtCont(Token original) : base(original) { }
  7116. public override void DebString(StringBuilder sb)
  7117. {
  7118. sb.Append("continue;");
  7119. }
  7120. }
  7121. /**
  7122. * @brief "do" statement
  7123. */
  7124. public class TokenStmtDo: TokenStmt
  7125. {
  7126. public TokenStmt bodyStmt;
  7127. public TokenRValParen testRVal;
  7128. public TokenStmtDo(Token original) : base(original) { }
  7129. public override void DebString(StringBuilder sb)
  7130. {
  7131. sb.Append("do ");
  7132. bodyStmt.DebString(sb);
  7133. sb.Append(" while ");
  7134. testRVal.DebString(sb);
  7135. sb.Append(';');
  7136. }
  7137. }
  7138. /**
  7139. * @brief "for" statement
  7140. */
  7141. public class TokenStmtFor: TokenStmt
  7142. {
  7143. public TokenStmt initStmt; // there is always an init statement, though it may be a null statement
  7144. public TokenRVal testRVal; // there may or may not be a test (null if not)
  7145. public TokenRVal incrRVal; // there may or may not be an increment (null if not)
  7146. public TokenStmt bodyStmt; // there is always a body statement, though it may be a null statement
  7147. public TokenStmtFor(Token original) : base(original) { }
  7148. public override void DebString(StringBuilder sb)
  7149. {
  7150. sb.Append("for (");
  7151. if(initStmt != null)
  7152. initStmt.DebString(sb);
  7153. else
  7154. sb.Append(';');
  7155. testRVal?.DebString(sb);
  7156. sb.Append(';');
  7157. incrRVal?.DebString(sb);
  7158. sb.Append(") ");
  7159. bodyStmt.DebString(sb);
  7160. }
  7161. }
  7162. /**
  7163. * @brief "foreach" statement
  7164. */
  7165. public class TokenStmtForEach: TokenStmt
  7166. {
  7167. public TokenLVal keyLVal;
  7168. public TokenLVal valLVal;
  7169. public TokenRVal arrayRVal;
  7170. public TokenStmt bodyStmt; // there is always a body statement, though it may be a null statement
  7171. public TokenStmtForEach(Token original) : base(original) { }
  7172. public override void DebString(StringBuilder sb)
  7173. {
  7174. sb.Append("foreach (");
  7175. keyLVal?.DebString(sb);
  7176. sb.Append(',');
  7177. valLVal?.DebString(sb);
  7178. sb.Append(" in ");
  7179. arrayRVal.DebString(sb);
  7180. sb.Append(')');
  7181. bodyStmt.DebString(sb);
  7182. }
  7183. }
  7184. public class TokenStmtIf: TokenStmt
  7185. {
  7186. public TokenRValParen testRVal;
  7187. public TokenStmt trueStmt;
  7188. public TokenStmt elseStmt;
  7189. public TokenStmtIf(Token original) : base(original) { }
  7190. public override void DebString(StringBuilder sb)
  7191. {
  7192. sb.Append("if ");
  7193. testRVal.DebString(sb);
  7194. sb.Append(' ');
  7195. trueStmt.DebString(sb);
  7196. if(elseStmt != null)
  7197. {
  7198. sb.Append(" else ");
  7199. elseStmt.DebString(sb);
  7200. }
  7201. }
  7202. }
  7203. public class TokenStmtJump: TokenStmt
  7204. {
  7205. public TokenName label;
  7206. public TokenStmtJump(Token original) : base(original) { }
  7207. public override void DebString(StringBuilder sb)
  7208. {
  7209. sb.Append("jump ");
  7210. label.DebString(sb);
  7211. sb.Append(';');
  7212. }
  7213. }
  7214. public class TokenStmtNull: TokenStmt
  7215. {
  7216. public TokenStmtNull(Token original) : base(original) { }
  7217. public override void DebString(StringBuilder sb)
  7218. {
  7219. sb.Append(';');
  7220. }
  7221. }
  7222. public class TokenStmtRet: TokenStmt
  7223. {
  7224. public TokenRVal rVal; // null if void
  7225. public TokenStmtRet(Token original) : base(original) { }
  7226. public override void DebString(StringBuilder sb)
  7227. {
  7228. sb.Append("return");
  7229. if(rVal != null)
  7230. {
  7231. sb.Append(' ');
  7232. rVal.DebString(sb);
  7233. }
  7234. sb.Append(';');
  7235. }
  7236. }
  7237. /**
  7238. * @brief statement that changes the current state.
  7239. */
  7240. public class TokenStmtState: TokenStmt
  7241. {
  7242. public TokenName state; // null for default
  7243. public TokenStmtState(Token original) : base(original) { }
  7244. public override void DebString(StringBuilder sb)
  7245. {
  7246. sb.Append("state ");
  7247. sb.Append((state == null) ? "default" : state.val);
  7248. sb.Append(';');
  7249. }
  7250. }
  7251. /**
  7252. * @brief Encapsulates a whole switch statement including the body and all cases.
  7253. */
  7254. public class TokenStmtSwitch: TokenStmt
  7255. {
  7256. public TokenRValParen testRVal; // the integer index expression
  7257. public TokenSwitchCase cases = null; // list of all cases, linked by .nextCase
  7258. public TokenSwitchCase lastCase = null; // used during reduce to point to last in 'cases' list
  7259. public TokenStmtSwitch(Token original) : base(original) { }
  7260. public override void DebString(StringBuilder sb)
  7261. {
  7262. sb.Append("switch ");
  7263. testRVal.DebString(sb);
  7264. sb.Append('{');
  7265. for(TokenSwitchCase kase = cases; kase != null; kase = kase.nextCase)
  7266. {
  7267. kase.DebString(sb);
  7268. }
  7269. sb.Append('}');
  7270. }
  7271. }
  7272. /**
  7273. * @brief Encapsulates a case/default clause from a switch statement including the
  7274. * two values and the corresponding body statements.
  7275. */
  7276. public class TokenSwitchCase: Token
  7277. {
  7278. public TokenSwitchCase nextCase; // next case in source-code order
  7279. public TokenRVal rVal1; // null means 'default', else 'case'
  7280. public TokenRVal rVal2; // null means 'case expr:', else 'case expr ... expr:'
  7281. public TokenStmt stmts; // statements associated with the case
  7282. public TokenStmt lastStmt; // used during reduce for building statement list
  7283. public int val1; // codegen: value of rVal1 here
  7284. public int val2; // codegen: value of rVal2 here
  7285. public ScriptMyLabel label; // codegen: target label here
  7286. public TokenSwitchCase nextSortedCase; // codegen: next case in ascending val order
  7287. public string str1;
  7288. public string str2;
  7289. public TokenSwitchCase lowerCase;
  7290. public TokenSwitchCase higherCase;
  7291. public TokenSwitchCase(Token original) : base(original) { }
  7292. public override void DebString(StringBuilder sb)
  7293. {
  7294. if(rVal1 == null)
  7295. {
  7296. sb.Append("default: ");
  7297. }
  7298. else
  7299. {
  7300. sb.Append("case ");
  7301. rVal1.DebString(sb);
  7302. if(rVal2 != null)
  7303. {
  7304. sb.Append(" ... ");
  7305. rVal2.DebString(sb);
  7306. }
  7307. sb.Append(": ");
  7308. }
  7309. for(Token t = stmts; t != null; t = t.nextToken)
  7310. {
  7311. t.DebString(sb);
  7312. }
  7313. }
  7314. }
  7315. public class TokenStmtThrow: TokenStmt
  7316. {
  7317. public TokenRVal rVal; // null if rethrow style
  7318. public TokenStmtThrow(Token original) : base(original) { }
  7319. public override void DebString(StringBuilder sb)
  7320. {
  7321. sb.Append("throw ");
  7322. rVal.DebString(sb);
  7323. sb.Append(';');
  7324. }
  7325. }
  7326. /**
  7327. * @brief Encapsulates related try, catch and finally statements.
  7328. */
  7329. public class TokenStmtTry: TokenStmt
  7330. {
  7331. public TokenStmtBlock tryStmt;
  7332. public TokenDeclVar catchVar; // null iff catchStmt is null
  7333. public TokenStmtBlock catchStmt; // can be null
  7334. public TokenStmtBlock finallyStmt; // can be null
  7335. public Dictionary<string, IntermediateLeave> iLeaves = new();
  7336. public TokenStmtTry(Token original) : base(original) { }
  7337. public override void DebString(StringBuilder sb)
  7338. {
  7339. sb.Append("try ");
  7340. tryStmt.DebString(sb);
  7341. if(catchStmt != null)
  7342. {
  7343. sb.Append("catch (");
  7344. sb.Append(catchVar.type.ToString());
  7345. sb.Append(' ');
  7346. sb.Append(catchVar.name.val);
  7347. sb.Append(") ");
  7348. catchStmt.DebString(sb);
  7349. }
  7350. if(finallyStmt != null)
  7351. {
  7352. sb.Append("finally ");
  7353. finallyStmt.DebString(sb);
  7354. }
  7355. }
  7356. }
  7357. public class IntermediateLeave
  7358. {
  7359. public ScriptMyLabel jumpIntoLabel;
  7360. public ScriptMyLabel jumpAwayLabel;
  7361. }
  7362. public class TokenStmtVarIniDef: TokenStmt
  7363. {
  7364. public TokenLVal var;
  7365. public TokenStmtVarIniDef(Token original) : base(original) { }
  7366. }
  7367. public class TokenStmtWhile: TokenStmt
  7368. {
  7369. public TokenRValParen testRVal;
  7370. public TokenStmt bodyStmt;
  7371. public TokenStmtWhile(Token original) : base(original) { }
  7372. public override void DebString(StringBuilder sb)
  7373. {
  7374. sb.Append("while ");
  7375. testRVal.DebString(sb);
  7376. sb.Append(' ');
  7377. bodyStmt.DebString(sb);
  7378. }
  7379. }
  7380. /**
  7381. * @brief type expressions (right-hand of 'is' keyword).
  7382. */
  7383. public class TokenTypeExp: Token
  7384. {
  7385. public TokenTypeExp(Token original) : base(original) { }
  7386. }
  7387. public class TokenTypeExpBinOp: TokenTypeExp
  7388. {
  7389. public TokenTypeExp leftOp;
  7390. public Token binOp;
  7391. public TokenTypeExp rightOp;
  7392. public TokenTypeExpBinOp(Token original) : base(original) { }
  7393. }
  7394. public class TokenTypeExpNot: TokenTypeExp
  7395. {
  7396. public TokenTypeExp typeExp;
  7397. public TokenTypeExpNot(Token original) : base(original) { }
  7398. }
  7399. public class TokenTypeExpPar: TokenTypeExp
  7400. {
  7401. public TokenTypeExp typeExp;
  7402. public TokenTypeExpPar(Token original) : base(original) { }
  7403. }
  7404. public class TokenTypeExpType: TokenTypeExp
  7405. {
  7406. public TokenType typeToken;
  7407. public TokenTypeExpType(Token original) : base(original) { }
  7408. }
  7409. public class TokenTypeExpUndef: TokenTypeExp
  7410. {
  7411. public TokenTypeExpUndef(Token original) : base(original) { }
  7412. }
  7413. }