bcc.c 206 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952
  1. /*
  2. Copyright (c) 2021, bartpleiter
  3. Copyright (c) 2012-2020, Alexey Frunze
  4. All rights reserved.
  5. Redistribution and use in source and binary forms, with or without
  6. modification, are permitted provided that the following conditions are met:
  7. 1. Redistributions of source code must retain the above copyright notice, this
  8. list of conditions and the following disclaimer.
  9. 2. Redistributions in binary form must reproduce the above copyright notice,
  10. this list of conditions and the following disclaimer in the documentation
  11. and/or other materials provided with the distribution.
  12. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
  13. ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  14. WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  15. DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
  16. ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  17. (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  18. LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  19. ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  20. (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  21. SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  22. */
  23. /*****************************************************************************/
  24. /* */
  25. /* BCC (B322 C Compiler) */
  26. /* */
  27. /* C compiler for B322 */
  28. /* Modified version intended to run on FPGC */
  29. /* */
  30. /* Based on SmallerC: */
  31. /* A simple and small single-pass C compiler */
  32. /* */
  33. /* Main file */
  34. /* */
  35. /*****************************************************************************/
  36. /* PLAN:
  37. - move through program from execution start to finish
  38. - implement missing (mostly FS) functions on the go (skip unimportant ones first, and do them later)
  39. - try to implement vararg printf, since it will save hours of printf replacements
  40. - FS functions (test/create library in a seperate test program):
  41. - fopen: just return a pointer to (global var!) the full path of the file, init cursor (private)
  42. - fput/get: open the file if not already opened, use cursor to read/write
  43. */
  44. // Making most functions static helps with code optimization,
  45. // use that to further reduce compiler's code size on RetroBSD.
  46. #define word char
  47. #define NO_EXTRAS
  48. #define CAN_COMPILE_32BIT
  49. #define MIPS
  50. #define B322
  51. #define NO_PPACK
  52. #define NO_TYPEDEF_ENUM
  53. #define NO_FUNC_
  54. #define NO_EXTRA_WARNS
  55. #define NO_FOR_DECL
  56. #define NO_STRUCT_BY_VAL
  57. #define NO_FP
  58. #define NO_WCHAR
  59. #define NULL 0
  60. #define size_t word //unsigned int
  61. #define CHAR_BIT (8)
  62. #define CHAR_MIN (-128)
  63. #define CHAR_MAX (127)
  64. #define INT_MAX (2147483647)
  65. #define INT_MIN (-2147483647 - 1)
  66. #define UINT_MAX (4294967295u)
  67. #define UINT_MIN (0u)
  68. #define EXIT_FAILURE 1
  69. #define MACROTABLE_ADDR 0x440000
  70. #define IDENTTABLE_ADDR 0x450000
  71. #define SYNSTACK0_ADDR 0x460000
  72. #define SYNSTACK1_ADDR 0x470000
  73. #define INPUTBUFFER_ADDR 0x480000
  74. #define FILENAMES_ADDR 0x490000
  75. #include "lib/math.c"
  76. #include "lib/sys.c"
  77. //#include "lib/gfx.c"
  78. #include "lib/stdlib.c"
  79. #include "lib/fs.c"
  80. #include "lib/stdio.c"
  81. ////////////////////////////////////////////////////////////////////////////////
  82. // all public macros
  83. #define MAX_IDENT_LEN 63
  84. #define MAX_STRING_LEN 255
  85. #define MAX_CHAR_QUEUE_LEN (MAX_STRING_LEN + 1)
  86. #define MAX_MACRO_TABLE_LEN (4096+1024)
  87. #define MAX_IDENT_TABLE_LEN (4096+1024+512) // must be greater than MAX_IDENT_LEN
  88. #define SYNTAX_STACK_MAX (2048+1024)
  89. #define MAX_FILE_NAME_LEN 95
  90. #define MAX_INCLUDES 8
  91. #define PREP_STACK_SIZE 8
  92. #define MAX_SEARCH_PATH 256
  93. /* +-~* /% &|^! << >> && || < <= > >= == != () *[] ++ -- = += -= ~= *= /= %= &= |= ^= <<= >>= {} ,;: -> ... */
  94. #define tokEof 0
  95. #define tokNumInt 1
  96. #define tokNumUint 2
  97. #define tokLitStr 3
  98. #define tokLShift 4
  99. #define tokRShift 5
  100. #define tokLogAnd 6
  101. #define tokLogOr 7
  102. #define tokEQ 8
  103. #define tokNEQ 9
  104. #define tokLEQ 10
  105. #define tokGEQ 11
  106. #define tokInc 12
  107. #define tokDec 13
  108. #define tokArrow 14
  109. #define tokEllipsis 15
  110. #define tokIdent 16
  111. #define tokVoid 17
  112. #define tokChar 18
  113. #define tokInt 19
  114. #define tokReturn 20
  115. #define tokGoto 21
  116. #define tokIf 22
  117. #define tokElse 23
  118. #define tokWhile 24
  119. #define tokCont 25
  120. #define tokBreak 26
  121. #define tokSizeof 27
  122. #define tokAssignMul 'A'
  123. #define tokAssignDiv 'B'
  124. #define tokAssignMod 'C'
  125. #define tokAssignAdd 'D'
  126. #define tokAssignSub 'E'
  127. #define tokAssignLSh 'F'
  128. #define tokAssignRSh 'G'
  129. #define tokAssignAnd 'H'
  130. #define tokAssignXor 'I'
  131. #define tokAssignOr 'J'
  132. #define tokFloat 'a'
  133. #define tokDouble 'b'
  134. #define tokLong 'c'
  135. #define tokShort 'd'
  136. #define tokUnsigned 'e'
  137. #define tokSigned 'f'
  138. #define tokConst 'g'
  139. #define tokVolatile 'h'
  140. #define tokRestrict 'i'
  141. #define tokStatic 'j'
  142. #define tokInline 'k'
  143. #define tokExtern 'l'
  144. #define tokAuto 'm'
  145. #define tokRegister 'n'
  146. #define tokTypedef 'o'
  147. #define tokEnum 'p'
  148. #define tokStruct 'q'
  149. #define tokUnion 'r'
  150. #define tokDo 's'
  151. #define tokFor 't'
  152. #define tokSwitch 'u'
  153. #define tokCase 'v'
  154. #define tokDefault 'w'
  155. #define tok_Bool 'x'
  156. #define tok_Complex 'y'
  157. #define tok_Imagin 'z'
  158. #define tok_Asm '`'
  159. /* Pseudo-tokens (converted from others or generated) */
  160. #define tokURShift 28
  161. #define tokUDiv 29
  162. #define tokUMod 30
  163. #define tokAssignURSh 31
  164. #define tokAssignUDiv '@'
  165. #define tokAssignUMod 'K'
  166. #define tokComma '0'
  167. #define tokIfNot 'L'
  168. #define tokUnaryAnd 'M'
  169. #define tokUnaryStar 'N'
  170. #define tokUnaryPlus 'O'
  171. #define tokUnaryMinus 'P'
  172. #define tokPostInc 'Q'
  173. #define tokPostDec 'R'
  174. #define tokPostAdd 'S'
  175. #define tokPostSub 'T'
  176. #define tokULess 'U'
  177. #define tokUGreater 'V'
  178. #define tokULEQ 'W'
  179. #define tokUGEQ 'X'
  180. #define tokLocalOfs 'Y'
  181. #define tokShortCirc 'Z'
  182. #define tokSChar 0x80
  183. #define tokUChar 0x81
  184. #define tokUShort 0x82
  185. #define tokULong 0x83
  186. //#define tokLongLong 0x84
  187. //#define tokULongLong 0x85
  188. //#define tokLongDbl 0x86
  189. #define tokGotoLabel 0x8F
  190. #define tokStructPtr 0x90
  191. #define tokTag 0x91
  192. #define tokMemberIdent 0x92
  193. #define tokEnumPtr 0x93
  194. #define tokIntr 0x94
  195. #define tokNumFloat 0x95
  196. #define tokNumCharWide 0x96
  197. #define tokLitStrWide 0x97
  198. //#define FormatFlat 0
  199. #define FormatSegmented 1
  200. //#define FormatSegTurbo 2
  201. #define FormatSegHuge 3
  202. #define FormatSegUnreal 4
  203. #define SymVoidSynPtr 0
  204. #define SymIntSynPtr 1
  205. #define SymUintSynPtr 2
  206. #define SymWideCharSynPtr 3
  207. #define SymFloatSynPtr 4
  208. #define SymFuncPtr 5
  209. #define STACK_SIZE 129
  210. #define SymFxn 1
  211. #define SymGlobalVar 2
  212. #define SymGlobalArr 3
  213. #define SymLocalVar 4
  214. #define SymLocalArr 5
  215. // all public prototypes
  216. unsigned truncUint(unsigned);
  217. word truncInt(word);
  218. word GetToken(void);
  219. char* GetTokenName(word token);
  220. void DumpMacroTable(void);
  221. word AddIdent(char* name);
  222. word FindIdent(char* name);
  223. void DumpIdentTable(void);
  224. char* lab2str(char* p, word n);
  225. void GenInit(void);
  226. void GenFin(void);
  227. void GenInitFinalize(void);
  228. void GenStartCommentLine(void);
  229. void GenWordAlignment(word bss);
  230. void GenLabel(char* Label, word Static);
  231. void GenNumLabel(word Label);
  232. void GenZeroData(unsigned Size, word bss);
  233. void GenIntData(word Size, word Val);
  234. void GenStartAsciiString(void);
  235. void GenAddrData(word Size, char* Label, word ofs);
  236. void GenJumpUncond(word Label);
  237. void GenJumpIfZero(word Label);
  238. void GenJumpIfNotZero(word Label);
  239. void GenJumpIfEqual(word val, word Label);
  240. void GenFxnProlog(void);
  241. void GenFxnEpilog(void);
  242. void GenIsrProlog(void);
  243. void GenIsrEpilog(void);
  244. word GenMaxLocalsSize(void);
  245. void GenDumpChar(word ch);
  246. void GenExpr(void);
  247. void PushSyntax(word t);
  248. void PushSyntax2(word t, word v);
  249. void DumpSynDecls(void);
  250. void push2(word v, word v2);
  251. void ins2(word pos, word v, word v2);
  252. void ins(word pos, word v);
  253. void del(word pos, word cnt);
  254. word TokenStartsDeclaration(word t, word params);
  255. word ParseDecl(word tok, unsigned structInfo[4], word cast, word label);
  256. void ShiftChar(void);
  257. word puts2(char*);
  258. word printf2(char*);
  259. void error(char* strToPrint);
  260. void warning(char* strToPrint);
  261. void errorFile(char* n);
  262. void errorFileName(void);
  263. void errorInternal(word n);
  264. void errorChrStr(void);
  265. void errorStrLen(void);
  266. void errorUnexpectedToken(word tok);
  267. void errorDirective(void);
  268. void errorCtrlOutOfScope(void);
  269. void errorDecl(void);
  270. void errorVarSize(void);
  271. void errorInit(void);
  272. void errorUnexpectedVoid(void);
  273. void errorOpType(void);
  274. void errorNotLvalue(void);
  275. void errorNotConst(void);
  276. void errorLongExpr(void);
  277. word FindSymbol(char* s);
  278. word SymType(word SynPtr);
  279. word FindTaggedDecl(char* s, word start, word* CurScope);
  280. word GetDeclSize(word SyntaxPtr, word SizeForDeref);
  281. word ParseExpr(word tok, word* GotUnary, word* ExprTypeSynPtr, word* ConstExpr, word* ConstVal, word option, word option2);
  282. word GetFxnInfo(word ExprTypeSynPtr, word* MinParams, word* MaxParams, word* ReturnExprTypeSynPtr, word* FirstParamSynPtr);
  283. // all data
  284. word verbose = 0;
  285. word warnings = 0;
  286. word warnCnt = 0;
  287. word doAnnotations = 0;
  288. // custom compiler flags
  289. word compileUserBDOS = 0;
  290. word compileOS = 0;
  291. // prep.c data
  292. // TBD!!! get rid of TokenIdentName[] and TokenValueString[]
  293. // and work with CharQueue[] directly
  294. word TokenValueInt = 0;
  295. char TokenIdentName[MAX_IDENT_LEN + 1];
  296. word TokenIdentNameLen = 0;
  297. char TokenValueString[MAX_STRING_LEN + 1];
  298. unsigned TokenStringLen = 0;
  299. unsigned TokenStringSize = 0; // TokenStringLen * sizeof(char/wchar_t)
  300. word LineNo = 1;
  301. word LinePos = 1;
  302. char CharQueue[MAX_CHAR_QUEUE_LEN];
  303. word CharQueueLen = 0;
  304. /*
  305. Macro table entry format:
  306. idlen char: identifier length (<= 127)
  307. id char[idlen]: identifier (ASCIIZ)
  308. exlen char: length of what the identifier expands into (<= 127)
  309. ex char[exlen]: what the identifier expands into (ASCII)
  310. */
  311. char *MacroTable = (char*) MACROTABLE_ADDR; //[MAX_MACRO_TABLE_LEN];
  312. word MacroTableLen = 0;
  313. /*
  314. Identifier table entry format:
  315. id char[idlen]: string (ASCIIZ)
  316. idlen char: string length (<= 127)
  317. */
  318. char *IdentTable = (char*) IDENTTABLE_ADDR; //[MAX_IDENT_TABLE_LEN];
  319. word IdentTableLen = 0;
  320. word DummyIdent; // corresponds to empty string
  321. #define MAX_GOTO_LABELS 16
  322. word gotoLabels[MAX_GOTO_LABELS][2];
  323. // gotoLabStat[]: bit 1 = used (by "goto label;"), bit 0 = defined (with "label:")
  324. char gotoLabStat[MAX_GOTO_LABELS];
  325. word gotoLabCnt = 0;
  326. #define MAX_CASES 128
  327. word Cases[MAX_CASES][2]; // [0] is case constant, [1] is case label number
  328. word CasesCnt = 0;
  329. // Data structures to support #include
  330. word FileCnt = 0;
  331. char (*FileNames)[MAX_FILE_NAME_LEN + 1] = (char (*)[MAX_FILE_NAME_LEN + 1]) FILENAMES_ADDR;
  332. //char FileNames[MAX_INCLUDES][MAX_FILE_NAME_LEN + 1];
  333. word Files[MAX_INCLUDES]; // FILE
  334. word OutFile; // FILE
  335. char CharQueues[MAX_INCLUDES][3];
  336. word LineNos[MAX_INCLUDES];
  337. word LinePoss[MAX_INCLUDES];
  338. char SysSearchPaths[MAX_SEARCH_PATH];
  339. word SysSearchPathsLen = 0;
  340. char SearchPaths[MAX_SEARCH_PATH];
  341. word SearchPathsLen = 0;
  342. // Data structures to support #ifdef/#ifndef,#else,#endif
  343. word PrepDontSkipTokens = 1;
  344. word PrepStack[PREP_STACK_SIZE][2];
  345. word PrepSp = 0;
  346. // expr.c data
  347. word ExprLevel = 0;
  348. // TBD??? merge expression and operator stacks into one
  349. word stack[STACK_SIZE][2];
  350. word sp = 0;
  351. #define OPERATOR_STACK_SIZE STACK_SIZE
  352. word opstack[OPERATOR_STACK_SIZE][2];
  353. word opsp = 0;
  354. // smc.c data
  355. word OutputFormat = FormatSegmented;
  356. word GenExterns = 1;
  357. word UseBss = 1;
  358. // Names of C functions and variables are usually prefixed with an underscore.
  359. // One notable exception is the ELF format used by gcc in Linux.
  360. // Global C identifiers in the ELF format should not be predixed with an underscore.
  361. word UseLeadingUnderscores = 1;
  362. char* FileHeader = "";
  363. char* CodeHeaderFooter[2] = { "", "" };
  364. char* DataHeaderFooter[2] = { "", "" };
  365. char* RoDataHeaderFooter[2] = { "", "" };
  366. char* BssHeaderFooter[2] = { "", "" };
  367. char** CurHeaderFooter;
  368. word CharIsSigned = 1;
  369. word SizeOfWord = 2; // in chars (char can be a multiple of octets); ints and pointers are of word size
  370. //word SizeOfWideChar = 2; // in chars/bytes, 2 or 4
  371. //word WideCharIsSigned = 0; // 0 or 1
  372. //word WideCharType1;
  373. //word WideCharType2; // (un)signed counterpart of WideCharType1
  374. // TBD??? implement a function to allocate N labels with overflow checks
  375. word LabelCnt = 1; // label counter for jumps
  376. word StructCpyLabel = 0; // label of the function to copy structures/unions
  377. //word StructPushLabel = 0; // label of the function to push structures/unions onto the stack
  378. // call stack (from higher to lower addresses):
  379. // arg n
  380. // ...
  381. // arg 1
  382. // return address
  383. // saved xbp register
  384. // local var 1
  385. // ...
  386. // local var n
  387. word CurFxnSyntaxPtr = 0;
  388. word CurFxnParamCntMin = 0;
  389. word CurFxnParamCntMax = 0;
  390. word CurFxnLocalOfs = 0; // negative
  391. word CurFxnMinLocalOfs = 0; // negative
  392. word CurFxnReturnExprTypeSynPtr = 0;
  393. word CurFxnEpilogLabel = 0;
  394. char* CurFxnName = NULL;
  395. word IsMain; // if inside main()
  396. word ParseLevel = 0; // Parse level/scope (file:0, fxn:1+)
  397. word ParamLevel = 0; // 1+ if parsing params, 0 otherwise
  398. unsigned char *SyntaxStack0 = (unsigned char*) SYNSTACK0_ADDR; //[SYNTAX_STACK_MAX];
  399. word *SyntaxStack1 = (word*) SYNSTACK1_ADDR; //[SYNTAX_STACK_MAX];
  400. word SyntaxStackCnt;
  401. // all code
  402. unsigned truncUint(unsigned n)
  403. {
  404. // Truncate n to SizeOfWord * 8 bits
  405. if (SizeOfWord == 2)
  406. n &= ~(~0u << 8 << 8);
  407. else if (SizeOfWord == 4)
  408. n &= ~(~0u << 8 << 12 << 12);
  409. return n;
  410. }
  411. word truncInt(word n)
  412. {
  413. // Truncate n to SizeOfWord * 8 bits and then sign-extend it
  414. unsigned un = n;
  415. if (SizeOfWord == 2)
  416. {
  417. un &= ~(~0u << 8 << 8);
  418. un |= (((un >> 8 >> 7) & 1) * ~0u) << 8 << 8;
  419. }
  420. else if (SizeOfWord == 4)
  421. {
  422. un &= ~(~0u << 8 << 12 << 12);
  423. un |= (((un >> 8 >> 12 >> 11) & 1) * ~0u) << 8 << 12 << 12;
  424. }
  425. return (word)un;
  426. }
  427. // prep.c code
  428. word FindMacro(char* name)
  429. {
  430. word i;
  431. for (i = 0; i < MacroTableLen; )
  432. {
  433. if (!strcmp(MacroTable + i + 1, name))
  434. return i + 1 + MacroTable[i];
  435. i = i + 1 + MacroTable[i]; // skip id
  436. i = i + 1 + MacroTable[i]; // skip ex
  437. }
  438. return -1;
  439. }
  440. word UndefineMacro(char* name)
  441. {
  442. word i;
  443. for (i = 0; i < MacroTableLen; )
  444. {
  445. if (!strcmp(MacroTable + i + 1, name))
  446. {
  447. word len = 1 + MacroTable[i]; // id part len
  448. len = len + 1 + MacroTable[i + len]; // + ex part len
  449. memmove(MacroTable + i,
  450. MacroTable + i + len,
  451. MacroTableLen - i - len);
  452. MacroTableLen -= len;
  453. return 1;
  454. }
  455. i = i + 1 + MacroTable[i]; // skip id
  456. i = i + 1 + MacroTable[i]; // skip ex
  457. }
  458. return 0;
  459. }
  460. void AddMacroIdent(char* name)
  461. {
  462. word l = strlen(name);
  463. if (l >= 127)
  464. {
  465. printf("Macro identifier too long ");
  466. printf(name);
  467. error("\n");
  468. }
  469. if (MAX_MACRO_TABLE_LEN - MacroTableLen < l + 3)
  470. error("Macro table exhausted\n");
  471. MacroTable[MacroTableLen++] = l + 1; // idlen
  472. strcpy(MacroTable + MacroTableLen, name);
  473. MacroTableLen += l + 1;
  474. MacroTable[MacroTableLen] = 0; // exlen
  475. }
  476. void AddMacroExpansionChar(char e)
  477. {
  478. if (e == '\0')
  479. {
  480. // finalize macro definition entry
  481. // remove trailing space first
  482. while (MacroTable[MacroTableLen] &&
  483. strchr(" \t", MacroTable[MacroTableLen + MacroTable[MacroTableLen]]))
  484. MacroTable[MacroTableLen]--;
  485. MacroTableLen += 1 + MacroTable[MacroTableLen];
  486. return;
  487. }
  488. if (MacroTableLen + 1 + MacroTable[MacroTableLen] >= MAX_MACRO_TABLE_LEN)
  489. error("Macro table exhausted\n");
  490. if (MacroTable[MacroTableLen] >= 127)
  491. error("Macro definition too long\n");
  492. MacroTable[MacroTableLen + 1 + MacroTable[MacroTableLen]] = e;
  493. MacroTable[MacroTableLen]++;
  494. }
  495. void DumpMacroTable(void)
  496. {
  497. word i, j;
  498. puts2("");
  499. GenStartCommentLine(); printf2("Macro table:\n");
  500. for (i = 0; i < MacroTableLen; )
  501. {
  502. GenStartCommentLine();
  503. printf2("Macro ");
  504. printf2(MacroTable + i + 1);
  505. printf2(" = ");
  506. i = i + 1 + MacroTable[i]; // skip id
  507. printf2("`");
  508. j = MacroTable[i++];
  509. while (j--)
  510. {
  511. char* c = " ";
  512. c[0] = MacroTable[i++];
  513. printf2(c);
  514. }
  515. printf2("`\n");
  516. }
  517. GenStartCommentLine(); //TODO: printf2("Bytes used: %d/%d\n\n", MacroTableLen, MAX_MACRO_TABLE_LEN);
  518. }
  519. word FindIdent(char* name)
  520. {
  521. word i;
  522. for (i = IdentTableLen; i > 0; )
  523. {
  524. i -= 1 + IdentTable[i - 1];
  525. if (!strcmp(IdentTable + i, name))
  526. return i;
  527. }
  528. return -1;
  529. }
  530. word AddIdent(char* name)
  531. {
  532. word i, len;
  533. if ((i = FindIdent(name)) >= 0)
  534. return i;
  535. i = IdentTableLen;
  536. len = strlen(name);
  537. if (len >= 127)
  538. error("Identifier too long\n");
  539. if (MAX_IDENT_TABLE_LEN - IdentTableLen < len + 2)
  540. error("Identifier table exhausted\n");
  541. strcpy(IdentTable + IdentTableLen, name);
  542. IdentTableLen += len + 1;
  543. IdentTable[IdentTableLen++] = len + 1;
  544. return i;
  545. }
  546. word AddNumericIdent(word n)
  547. {
  548. char s[1 + (2 + CHAR_BIT * sizeof n) / 3];
  549. char *p = s + sizeof s;
  550. *--p = '\0';
  551. p = lab2str(p, n);
  552. return AddIdent(p);
  553. }
  554. word AddGotoLabel(char* name, word label)
  555. {
  556. word i;
  557. for (i = 0; i < gotoLabCnt; i++)
  558. {
  559. if (!strcmp(IdentTable + gotoLabels[i][0], name))
  560. {
  561. if (gotoLabStat[i] & label)
  562. {
  563. printf("Redefinition of label ");
  564. printf(name);
  565. error("\n");
  566. }
  567. gotoLabStat[i] |= 2*!label + label;
  568. return gotoLabels[i][1];
  569. }
  570. }
  571. if (gotoLabCnt >= MAX_GOTO_LABELS)
  572. error("Goto table exhausted\n");
  573. gotoLabels[gotoLabCnt][0] = AddIdent(name);
  574. gotoLabels[gotoLabCnt][1] = LabelCnt++;
  575. gotoLabStat[gotoLabCnt] = 2*!label + label;
  576. return gotoLabels[gotoLabCnt++][1];
  577. }
  578. void UndoNonLabelIdents(word len)
  579. {
  580. word i;
  581. IdentTableLen = len;
  582. for (i = 0; i < gotoLabCnt; i++)
  583. if (gotoLabels[i][0] >= len)
  584. {
  585. char* pfrom = IdentTable + gotoLabels[i][0];
  586. char* pto = IdentTable + IdentTableLen;
  587. word l = strlen(pfrom) + 2;
  588. memmove(pto, pfrom, l);
  589. IdentTableLen += l;
  590. gotoLabels[i][0] = pto - IdentTable;
  591. }
  592. }
  593. void AddCase(word val, word label)
  594. {
  595. if (CasesCnt >= MAX_CASES)
  596. error("Case table exhausted\n");
  597. Cases[CasesCnt][0] = val;
  598. Cases[CasesCnt++][1] = label;
  599. }
  600. void DumpIdentTable(void)
  601. {
  602. word i;
  603. puts2("");
  604. GenStartCommentLine(); printf2("Identifier table:\n");
  605. for (i = 0; i < IdentTableLen; )
  606. {
  607. GenStartCommentLine();
  608. printf2("Ident ");
  609. printf2(IdentTable + i);
  610. printf2("\n");
  611. i += strlen(IdentTable + i) + 2;
  612. }
  613. GenStartCommentLine(); //TODO: printf2("Bytes used: %d/%d\n\n", IdentTableLen, MAX_IDENT_TABLE_LEN);
  614. }
  615. char* rws[] =
  616. {
  617. "break", "case", "char", "continue", "default", "do", "else",
  618. "extern", "for", "if", "int", "return", "signed", "sizeof",
  619. "static", "switch", "unsigned", "void", "while", "asm", "auto",
  620. "const", "double", "enum", "float", "goto", "inline", "long",
  621. "register", "restrict", "short", "struct", "typedef", "union",
  622. "volatile", "_Bool", "_Complex", "_Imaginary",
  623. "__interrupt"
  624. };
  625. unsigned char rwtk[] =
  626. {
  627. tokBreak, tokCase, tokChar, tokCont, tokDefault, tokDo, tokElse,
  628. tokExtern, tokFor, tokIf, tokInt, tokReturn, tokSigned, tokSizeof,
  629. tokStatic, tokSwitch, tokUnsigned, tokVoid, tokWhile, tok_Asm, tokAuto,
  630. tokConst, tokDouble, tokEnum, tokFloat, tokGoto, tokInline, tokLong,
  631. tokRegister, tokRestrict, tokShort, tokStruct, tokTypedef, tokUnion,
  632. tokVolatile, tok_Bool, tok_Complex, tok_Imagin,
  633. tokIntr
  634. };
  635. word GetTokenByWord(char* wrd)
  636. {
  637. unsigned i;
  638. for (i = 0; i < division(sizeof rws, sizeof rws[0]); i++)
  639. if (!strcmp(rws[i], wrd))
  640. return rwtk[i];
  641. return tokIdent;
  642. }
  643. unsigned char tktk[] =
  644. {
  645. tokEof,
  646. // Single-character operators and punctuators:
  647. '+', '-', '~', '*', '/', '%', '&', '|', '^', '!',
  648. '<', '>', '(', ')', '[', ']',
  649. '{', '}', '=', ',', ';', ':', '.', '?',
  650. // Multi-character operators and punctuators:
  651. tokLShift, tokLogAnd, tokEQ, tokLEQ, tokInc, tokArrow, tokAssignMul,
  652. tokAssignMod, tokAssignSub, tokAssignRSh, tokAssignXor,
  653. tokRShift, tokLogOr, tokNEQ, tokGEQ, tokDec, tokEllipsis,
  654. tokAssignDiv, tokAssignAdd, tokAssignLSh, tokAssignAnd, tokAssignOr,
  655. // Some of the above tokens get converted into these in the process:
  656. tokUnaryAnd, tokUnaryPlus, tokPostInc, tokPostAdd,
  657. tokULess, tokULEQ, tokURShift, tokUDiv, tokUMod, tokComma,
  658. tokUnaryStar, tokUnaryMinus, tokPostDec, tokPostSub,
  659. tokUGreater, tokUGEQ, tokAssignURSh, tokAssignUDiv, tokAssignUMod,
  660. // Helper (pseudo-)tokens:
  661. tokNumInt, tokLitStr, tokLocalOfs, tokNumUint, tokIdent, tokShortCirc,
  662. tokSChar, tokShort, tokLong, tokUChar, tokUShort, tokULong, tokNumFloat,
  663. tokNumCharWide, tokLitStrWide
  664. };
  665. char* tks[] =
  666. {
  667. "<EOF>",
  668. // Single-character operators and punctuators:
  669. "+", "-", "~", "*", "/", "%", "&", "|", "^", "!",
  670. "<", ">", "(", ")", "[", "]",
  671. "{", "}", "=", ",", ";", ":", ".", "?",
  672. // Multi-character operators and punctuators:
  673. "<<", "&&", "==", "<=", "++", "->", "*=",
  674. "%=", "-=", ">>=", "^=",
  675. ">>", "||", "!=", ">=", "--", "...",
  676. "/=", "+=", "<<=", "&=", "|=",
  677. // Some of the above tokens get converted into these in the process:
  678. "&u", "+u", "++p", "+=p",
  679. "<u", "<=u", ">>u", "/u", "%u", ",b",
  680. "*u", "-u", "--p", "-=p",
  681. ">u", ">=u", ">>=u", "/=u", "%=u",
  682. // Helper (pseudo-)tokens:
  683. "<NumInt>", "<LitStr>", "<LocalOfs>", "<NumUint>", "<Ident>", "<ShortCirc>",
  684. "signed char", "short", "long", "unsigned char", "unsigned short", "unsigned long", "float",
  685. "<NumCharWide>", "<LitStrWide>"
  686. };
  687. char* GetTokenName(word token)
  688. {
  689. unsigned i;
  690. /* +-~* /% &|^! << >> && || < <= > >= == != () *[] ++ -- = += -= ~= *= /= %= &= |= ^= <<= >>= {} ,;: -> ... */
  691. // Tokens other than reserved keywords:
  692. for (i = 0; i < division(sizeof tktk , sizeof tktk[0]); i++)
  693. if (tktk[i] == token)
  694. return tks[i];
  695. // Reserved keywords:
  696. for (i = 0; i < division(sizeof rws , sizeof rws[0]); i++)
  697. if (rwtk[i] == token)
  698. return rws[i];
  699. //error("Internal Error: GetTokenName(): Invalid token %d\n", token);
  700. errorInternal(1);
  701. return "";
  702. }
  703. word GetNextChar(void)
  704. {
  705. word ch = EOF;
  706. if (FileCnt && Files[FileCnt - 1])
  707. {
  708. if ((ch = fgetc(Files[FileCnt - 1])) == EOF)
  709. {
  710. fclose(Files[FileCnt - 1]);
  711. Files[FileCnt - 1] = NULL;
  712. // store the last line/pos, they may still be needed later
  713. LineNos[FileCnt - 1] = LineNo;
  714. LinePoss[FileCnt - 1] = LinePos;
  715. // don't drop the file record just yet
  716. }
  717. }
  718. return ch;
  719. }
  720. void ShiftChar(void)
  721. {
  722. if (CharQueueLen)
  723. memmove(CharQueue, CharQueue + 1, --CharQueueLen);
  724. // make sure there always are at least 3 chars in the queue
  725. while (CharQueueLen < 3)
  726. {
  727. word ch = GetNextChar();
  728. if (ch == EOF)
  729. ch = '\0';
  730. CharQueue[CharQueueLen++] = ch;
  731. //BDOS_PrintcConsole(ch);
  732. }
  733. }
  734. void ShiftCharN(word n)
  735. {
  736. while (n-- > 0)
  737. {
  738. ShiftChar();
  739. LinePos++;
  740. }
  741. }
  742. void IncludeFile(word quot)
  743. {
  744. word nlen = strlen(TokenValueString);
  745. if (CharQueueLen != 3)
  746. //error("#include parsing error\n");
  747. errorInternal(2);
  748. if (FileCnt >= MAX_INCLUDES)
  749. error("Too many include files\n");
  750. // store the including file's position and buffered chars
  751. LineNos[FileCnt - 1] = LineNo;
  752. LinePoss[FileCnt - 1] = LinePos;
  753. memcpy(CharQueues[FileCnt - 1], CharQueue, CharQueueLen);
  754. // open the included file
  755. if (nlen > MAX_FILE_NAME_LEN)
  756. //error("File name too long\n");
  757. errorFileName();
  758. // DONE: differentiate between quot == '"' and quot == '<'
  759. // First, try opening "file" in the current directory
  760. // (Open Watcom C/C++ 1.9, Turbo C++ 1.01 use the current directory,
  761. // unlike gcc, which uses the same directory as the current file)
  762. if (quot == '"')
  763. {
  764. // Get path from c file to compile, so it can be appended to the include paths
  765. char cFileDir[255] = "";
  766. strcpy(cFileDir, FileNames[0]);
  767. word len = strlen(cFileDir);
  768. while (len > 0)
  769. {
  770. len--;
  771. if (cFileDir[len] == '/')
  772. {
  773. cFileDir[len+1] = '\0'; // keep the slash
  774. break;
  775. }
  776. }
  777. if (len == 0) // remove directory if there is none
  778. {
  779. cFileDir[0] = '\0';
  780. }
  781. strcpy(FileNames[FileCnt], TokenValueString);
  782. strcat(cFileDir, FileNames[FileCnt]);
  783. Files[FileCnt] = fopen(cFileDir, 0);
  784. }
  785. // Next, iterate the search paths trying to open "file" or <file>.
  786. // "file" is first searched using the list provided by the -I option.
  787. // "file" is then searched using the list provided by the -SI option.
  788. // <file> is searched using the list provided by the -SI option.
  789. if (Files[FileCnt] == NULL)
  790. {
  791. word i;
  792. char *paths = SearchPaths;
  793. word pl = SearchPathsLen;
  794. for (;;)
  795. {
  796. if (quot == '<')
  797. {
  798. paths = SysSearchPaths;
  799. pl = SysSearchPathsLen;
  800. }
  801. for (i = 0; i < pl; )
  802. {
  803. word plen = strlen(paths + i);
  804. if (plen + 1 + nlen < MAX_FILE_NAME_LEN)
  805. {
  806. strcpy(FileNames[FileCnt], paths + i);
  807. strcpy(FileNames[FileCnt] + plen + 1, TokenValueString);
  808. // Use '/' as a separator, typical for Linux/Unix,
  809. // but also supported by file APIs in DOS/Windows just as '\\'
  810. FileNames[FileCnt][plen] = '/';
  811. if ((Files[FileCnt] = fopen(FileNames[FileCnt], 0)) != NULL)
  812. break;
  813. }
  814. i += plen + 1;
  815. }
  816. if (Files[FileCnt] || quot == '<')
  817. break;
  818. quot = '<';
  819. }
  820. }
  821. if (Files[FileCnt] == NULL)
  822. {
  823. //error("Cannot open file \"%s\"\n", TokenValueString);
  824. errorFile(TokenValueString);
  825. }
  826. // reset line/pos and empty the char queue
  827. CharQueueLen = 0;
  828. LineNo = LinePos = 1;
  829. FileCnt++;
  830. // fill the char queue with file data
  831. ShiftChar();
  832. }
  833. word EndOfFiles(void)
  834. {
  835. // if there are no including files, we're done
  836. if (!--FileCnt)
  837. return 1;
  838. // restore the including file's position and buffered chars
  839. LineNo = LineNos[FileCnt - 1];
  840. LinePos = LinePoss[FileCnt - 1];
  841. CharQueueLen = 3;
  842. memcpy(CharQueue, CharQueues[FileCnt - 1], CharQueueLen);
  843. return 0;
  844. }
  845. void SkipSpace(word SkipNewLines)
  846. {
  847. char* p = CharQueue;
  848. while (*p != '\0')
  849. {
  850. if (strchr(" \t\f\v", *p))
  851. {
  852. ShiftCharN(1);
  853. continue;
  854. }
  855. if (strchr("\r\n", *p))
  856. {
  857. if (!SkipNewLines)
  858. return;
  859. if (*p == '\r' && p[1] == '\n')
  860. ShiftChar();
  861. ShiftChar();
  862. LineNo++;
  863. LinePos = 1;
  864. continue;
  865. }
  866. if (*p == '/')
  867. {
  868. if (p[1] == '/')
  869. {
  870. // // comment
  871. ShiftCharN(2);
  872. while (!strchr("\r\n", *p))
  873. ShiftCharN(1);
  874. continue;
  875. }
  876. else if (p[1] == '*')
  877. {
  878. // /**/ comment
  879. ShiftCharN(2);
  880. while (*p != '\0' && !(*p == '*' && p[1] == '/'))
  881. {
  882. if (strchr("\r\n", *p))
  883. {
  884. if (!SkipNewLines)
  885. error("Invalid comment\n");
  886. if (*p == '\r' && p[1] == '\n')
  887. ShiftChar();
  888. ShiftChar();
  889. LineNo++;
  890. LinePos = 1;
  891. }
  892. else
  893. {
  894. ShiftCharN(1);
  895. }
  896. }
  897. if (*p == '\0')
  898. error("Invalid comment\n");
  899. ShiftCharN(2);
  900. continue;
  901. }
  902. } // endof if (*p == '/')
  903. break;
  904. } // endof while (*p != '\0')
  905. }
  906. void SkipLine(void)
  907. {
  908. char* p = CharQueue;
  909. while (*p != '\0')
  910. {
  911. if (strchr("\r\n", *p))
  912. {
  913. if (*p == '\r' && p[1] == '\n')
  914. ShiftChar();
  915. ShiftChar();
  916. LineNo++;
  917. LinePos = 1;
  918. break;
  919. }
  920. else
  921. {
  922. ShiftCharN(1);
  923. }
  924. }
  925. }
  926. void GetIdent(void)
  927. {
  928. char* p = CharQueue;
  929. if (*p != '_' && !isalpha(*p & 0xFFu))
  930. error("Identifier expected\n");
  931. TokenIdentNameLen = 0;
  932. TokenIdentName[TokenIdentNameLen++] = *p;
  933. TokenIdentName[TokenIdentNameLen] = '\0';
  934. ShiftCharN(1);
  935. while (*p == '_' || isalnum(*p & 0xFFu))
  936. {
  937. if (TokenIdentNameLen == MAX_IDENT_LEN)
  938. {
  939. printf("Identifier too long ");
  940. printf(TokenIdentName);
  941. error("\n");
  942. }
  943. TokenIdentName[TokenIdentNameLen++] = *p;
  944. TokenIdentName[TokenIdentNameLen] = '\0';
  945. ShiftCharN(1);
  946. }
  947. }
  948. unsigned GetCharValue(word wide)
  949. {
  950. char* p = CharQueue;
  951. unsigned ch = 0;
  952. word cnt = 0;
  953. if (*p == '\\')
  954. {
  955. ShiftCharN(1);
  956. if (strchr("\n\r", *p))
  957. goto lerr;
  958. if (*p == 'x')
  959. {
  960. // hexadecimal character codes \xN+
  961. // hexadecimal escape sequence is not limited in length per se
  962. // (may have many leading zeroes)
  963. static char digs[] = "0123456789ABCDEFabcdef";
  964. static char vals[] =
  965. {
  966. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
  967. 10, 11, 12, 13, 14, 15,
  968. 10, 11, 12, 13, 14, 15
  969. };
  970. char* pp;
  971. word zeroes = 0;
  972. ShiftCharN(1);
  973. if (strchr("\n\r", *p))
  974. goto lerr;
  975. if (*p == '0')
  976. {
  977. do
  978. {
  979. ShiftCharN(1);
  980. } while (*p == '0');
  981. zeroes = 1;
  982. }
  983. while (*p && (pp = strchr(digs, *p)) != NULL)
  984. {
  985. ch <<= 4;
  986. ch |= vals[pp - digs];
  987. ShiftCharN(1);
  988. if (++cnt > 2)
  989. {
  990. if (PrepDontSkipTokens)
  991. goto lerr;
  992. }
  993. }
  994. if (zeroes + cnt == 0)
  995. goto lerr;
  996. }
  997. else if (*p >= '0' && *p <= '7')
  998. {
  999. // octal character codes \N+
  1000. // octal escape sequence is terminated after three octal digits
  1001. do
  1002. {
  1003. ch <<= 3;
  1004. ch |= *p - '0';
  1005. ShiftCharN(1);
  1006. ++cnt;
  1007. } while (*p >= '0' && *p <= '7' && cnt < 3);
  1008. if (ch >> 8)
  1009. goto lerr;
  1010. }
  1011. else
  1012. {
  1013. switch (*p)
  1014. {
  1015. case 'a': ch = '\a'; ShiftCharN(1); break;
  1016. case 'b': ch = '\b'; ShiftCharN(1); break;
  1017. case 'f': ch = '\f'; ShiftCharN(1); break;
  1018. case 'n': ch = '\n'; ShiftCharN(1); break;
  1019. case 'r': ch = '\r'; ShiftCharN(1); break;
  1020. case 't': ch = '\t'; ShiftCharN(1); break;
  1021. case 'v': ch = '\v'; ShiftCharN(1); break;
  1022. default:
  1023. goto lself;
  1024. }
  1025. }
  1026. }
  1027. else
  1028. {
  1029. lself:
  1030. if (strchr("\n\r", *p))
  1031. {
  1032. lerr:
  1033. //error("Unsupported or invalid character/string constant\n");
  1034. errorChrStr();
  1035. }
  1036. ch = *p & 0xFFu;
  1037. ShiftCharN(1);
  1038. }
  1039. return ch;
  1040. }
  1041. void GetString(char terminator, word wide, word option)
  1042. {
  1043. char* p = CharQueue;
  1044. unsigned ch = '\0';
  1045. unsigned chsz = 1;
  1046. word i;
  1047. char* ctmp = " ";
  1048. TokenStringLen = 0;
  1049. TokenStringSize = 0;
  1050. TokenValueString[TokenStringLen] = '\0';
  1051. ShiftCharN(1);
  1052. while (!(*p == terminator || strchr("\n\r", *p)))
  1053. {
  1054. ch = GetCharValue(wide);
  1055. switch (option)
  1056. {
  1057. case '#': // string literal (with file name) for #line and #include
  1058. if (TokenStringLen == MAX_STRING_LEN)
  1059. errorStrLen();
  1060. TokenValueString[TokenStringLen++] = ch;
  1061. TokenValueString[TokenStringLen] = '\0';
  1062. TokenStringSize += chsz;
  1063. break;
  1064. case 'a': // string literal for asm()
  1065. ctmp[0] = ch;
  1066. printf2(ctmp);
  1067. break;
  1068. case 'd': // string literal / array of char in expression or initializer
  1069. // Dump the char data to the appropriate data section
  1070. for (i = 0; i < chsz; i++)
  1071. {
  1072. GenDumpChar(ch & 0xFFu);
  1073. ch >>= 8;
  1074. TokenStringLen++; // GenDumpChar() expects it to grow, doesn't know about wchar_t
  1075. }
  1076. TokenStringLen -= chsz;
  1077. // fallthrough
  1078. default: // skipped string literal (we may still need the size)
  1079. if (TokenStringSize > UINT_MAX - chsz)
  1080. errorStrLen();
  1081. TokenStringSize += chsz;
  1082. TokenStringLen++;
  1083. break;
  1084. } // endof switch (option)
  1085. } // endof while (!(*p == '\0' || *p == terminator || strchr("\n\r", *p)))
  1086. if (*p != terminator)
  1087. //error("Unsupported or invalid character/string constant\n");
  1088. errorChrStr();
  1089. if (option == 'd')
  1090. GenDumpChar(-1);
  1091. ShiftCharN(1);
  1092. SkipSpace(option != '#');
  1093. }
  1094. void pushPrep(word NoSkip)
  1095. {
  1096. if (PrepSp >= PREP_STACK_SIZE)
  1097. error("Too many #if(n)def's\n");
  1098. PrepStack[PrepSp][0] = PrepDontSkipTokens;
  1099. PrepStack[PrepSp++][1] = NoSkip;
  1100. PrepDontSkipTokens &= NoSkip;
  1101. }
  1102. word popPrep(void)
  1103. {
  1104. if (PrepSp <= 0)
  1105. error("#else or #endif without #if(n)def\n");
  1106. PrepDontSkipTokens = PrepStack[--PrepSp][0];
  1107. return PrepStack[PrepSp][1];
  1108. }
  1109. word GetNumber(void)
  1110. {
  1111. char* p = CharQueue;
  1112. word ch = *p;
  1113. word leadingZero = (ch == '0');
  1114. unsigned n = 0;
  1115. word type = 0;
  1116. word uSuffix = 0;
  1117. word lSuffix = 0;
  1118. char* eTooBig = "Constant too big\n";
  1119. // First, detect and handle hex constants. Octals can't be detected immediately
  1120. // because floating-point constants also may begin with the digit 0.
  1121. if (leadingZero && (p[1] == 'x' || p[1] == 'X'))
  1122. {
  1123. // this is a hex constant
  1124. word cnt = 0;
  1125. type = 'h';
  1126. ShiftCharN(1);
  1127. ShiftCharN(1);
  1128. while ((ch = *p) != '\0' && (isdigit(ch & 0xFFu) || strchr("abcdefABCDEF", ch)))
  1129. {
  1130. if (ch >= 'a') ch -= 'a' - 10;
  1131. else if (ch >= 'A') ch -= 'A' - 10;
  1132. else ch -= '0';
  1133. //if (PrepDontSkipTokens && (n * 16 / 16 != n || n * 16 + ch < n * 16))
  1134. // error(eTooBig);
  1135. n = n * 16 + ch;
  1136. ShiftCharN(1);
  1137. cnt++;
  1138. }
  1139. if (!cnt)
  1140. error("Invalid hexadecimal constant\n");
  1141. }
  1142. else
  1143. {
  1144. // handle decimal and octal integers
  1145. word base = leadingZero ? 8 : 10;
  1146. type = leadingZero ? 'o' : 'd';
  1147. while ((ch = *p) >= '0' && ch < base + '0')
  1148. {
  1149. ch -= '0';
  1150. if (PrepDontSkipTokens && (n * base + ch < n * base)) //n * base / base != n ||
  1151. error(eTooBig);
  1152. n = n * base + ch;
  1153. ShiftCharN(1);
  1154. }
  1155. }
  1156. // possible combinations of integer suffixes:
  1157. // none
  1158. // U
  1159. // UL
  1160. // L
  1161. // LU
  1162. {
  1163. if ((ch = *p) == 'u' || ch == 'U')
  1164. {
  1165. uSuffix = 1;
  1166. ShiftCharN(1);
  1167. }
  1168. if ((ch = *p) == 'l' || ch == 'L')
  1169. {
  1170. lSuffix = 1;
  1171. ShiftCharN(1);
  1172. if (!uSuffix && ((ch = *p) == 'u' || ch == 'U'))
  1173. {
  1174. uSuffix = 1;
  1175. ShiftCharN(1);
  1176. }
  1177. }
  1178. }
  1179. if (!PrepDontSkipTokens)
  1180. {
  1181. // Don't fail on big constants when skipping tokens under #if
  1182. TokenValueInt = 0;
  1183. return tokNumInt;
  1184. }
  1185. // Ensure the constant fits into 16(32) bits
  1186. if (
  1187. (SizeOfWord == 2 && n >> 8 >> 8) // equiv. to SizeOfWord == 2 && n > 0xFFFF
  1188. || (SizeOfWord == 2 && lSuffix) // long (which must have at least 32 bits) isn't supported in 16-bit models
  1189. || (SizeOfWord == 4 && n >> 8 >> 12 >> 12) // equiv. to SizeOfWord == 4 && n > 0xFFFFFFFF
  1190. )
  1191. error("Constant too big for 32-bit type\n");
  1192. TokenValueInt = (word)n;
  1193. // Unsuffixed (with 'u') integer constants (octal, decimal, hex)
  1194. // fitting into 15(31) out of 16(32) bits are signed ints
  1195. if (!uSuffix &&
  1196. (
  1197. (SizeOfWord == 2 && !(n >> 15)) // equiv. to SizeOfWord == 2 && n <= 0x7FFF
  1198. || (SizeOfWord == 4 && !(n >> 8 >> 12 >> 11)) // equiv. to SizeOfWord == 4 && n <= 0x7FFFFFFF
  1199. )
  1200. )
  1201. return tokNumInt;
  1202. // Unlike octal and hex constants, decimal constants are always
  1203. // a signed type. Error out when a decimal constant doesn't fit
  1204. // into an int since currently there's no next bigger signed type
  1205. // (e.g. long) to use instead of int.
  1206. if (!uSuffix && type == 'd')
  1207. error("Constant too big for 32-bit signed type\n");
  1208. return tokNumUint;
  1209. }
  1210. word GetTokenInner(void)
  1211. {
  1212. char* p = CharQueue;
  1213. word ch = *p;
  1214. word wide = 0;
  1215. // these single-character tokens/operators need no further processing
  1216. if (strchr(",;:()[]{}~?", ch))
  1217. {
  1218. ShiftCharN(1);
  1219. return ch;
  1220. }
  1221. // parse multi-character tokens/operators
  1222. // DONE: other assignment operators
  1223. switch (ch)
  1224. {
  1225. case '+':
  1226. if (p[1] == '+') { ShiftCharN(2); return tokInc; }
  1227. if (p[1] == '=') { ShiftCharN(2); return tokAssignAdd; }
  1228. ShiftCharN(1); return ch;
  1229. case '-':
  1230. if (p[1] == '-') { ShiftCharN(2); return tokDec; }
  1231. if (p[1] == '=') { ShiftCharN(2); return tokAssignSub; }
  1232. if (p[1] == '>') { ShiftCharN(2); return tokArrow; }
  1233. ShiftCharN(1); return ch;
  1234. case '!':
  1235. if (p[1] == '=') { ShiftCharN(2); return tokNEQ; }
  1236. ShiftCharN(1); return ch;
  1237. case '=':
  1238. if (p[1] == '=') { ShiftCharN(2); return tokEQ; }
  1239. ShiftCharN(1); return ch;
  1240. case '<':
  1241. if (p[1] == '=') { ShiftCharN(2); return tokLEQ; }
  1242. if (p[1] == '<') { ShiftCharN(2); if (p[0] != '=') return tokLShift; ShiftCharN(1); return tokAssignLSh; }
  1243. ShiftCharN(1); return ch;
  1244. case '>':
  1245. if (p[1] == '=') { ShiftCharN(2); return tokGEQ; }
  1246. if (p[1] == '>') { ShiftCharN(2); if (p[0] != '=') return tokRShift; ShiftCharN(1); return tokAssignRSh; }
  1247. ShiftCharN(1); return ch;
  1248. case '&':
  1249. if (p[1] == '&') { ShiftCharN(2); return tokLogAnd; }
  1250. if (p[1] == '=') { ShiftCharN(2); return tokAssignAnd; }
  1251. ShiftCharN(1); return ch;
  1252. case '|':
  1253. if (p[1] == '|') { ShiftCharN(2); return tokLogOr; }
  1254. if (p[1] == '=') { ShiftCharN(2); return tokAssignOr; }
  1255. ShiftCharN(1); return ch;
  1256. case '^':
  1257. if (p[1] == '=') { ShiftCharN(2); return tokAssignXor; }
  1258. ShiftCharN(1); return ch;
  1259. case '.':
  1260. if (p[1] == '.' && p[2] == '.') { ShiftCharN(3); return tokEllipsis; }
  1261. ShiftCharN(1); return ch;
  1262. case '*':
  1263. if (p[1] == '=') { ShiftCharN(2); return tokAssignMul; }
  1264. ShiftCharN(1); return ch;
  1265. case '%':
  1266. if (p[1] == '=') { ShiftCharN(2); return tokAssignMod; }
  1267. ShiftCharN(1); return ch;
  1268. case '/':
  1269. if (p[1] == '=') { ShiftCharN(2); return tokAssignDiv; }
  1270. ShiftCharN(1); return ch;
  1271. }
  1272. // DONE: hex and octal constants
  1273. if (isdigit(ch & 0xFFu))
  1274. return GetNumber();
  1275. // parse character and string constants
  1276. if (ch == '\'')
  1277. {
  1278. unsigned v = 0;
  1279. word cnt = 0;
  1280. word max_cnt = SizeOfWord;
  1281. ShiftCharN(1);
  1282. if (strchr("'\n\r", *p))
  1283. //error("Character constant too short\n");
  1284. errorChrStr();
  1285. do
  1286. {
  1287. v <<= 8;
  1288. v |= GetCharValue(wide);
  1289. if (++cnt > max_cnt)
  1290. //error("Character constant too long\n");
  1291. errorChrStr();
  1292. } while (!strchr("'\n\r", *p));
  1293. if (*p != '\'')
  1294. //error("Unsupported or invalid character/string constant\n");
  1295. errorChrStr();
  1296. ShiftCharN(1);
  1297. {
  1298. if (cnt == 1)
  1299. {
  1300. TokenValueInt = v;
  1301. TokenValueInt -= (CharIsSigned && TokenValueInt >= 0x80) * 0x100;
  1302. }
  1303. else
  1304. {
  1305. TokenValueInt = v;
  1306. TokenValueInt -= (SizeOfWord == 2 && TokenValueInt >= 0x8000) * 0x10000;
  1307. }
  1308. return tokNumInt;
  1309. }
  1310. }
  1311. else if (ch == '"')
  1312. {
  1313. // The caller of GetTokenInner()/GetToken() will call GetString('"', wide, 'd')
  1314. // to complete string literal parsing and storing as appropriate
  1315. return tokLitStr;
  1316. }
  1317. return tokEof;
  1318. }
  1319. void Reserve4Expansion(char* name, word len)
  1320. {
  1321. if (MAX_CHAR_QUEUE_LEN - CharQueueLen < len + 1)
  1322. {
  1323. printf("Too long expansion of macro ");
  1324. printf(name);
  1325. error("\n");
  1326. }
  1327. memmove(CharQueue + len + 1, CharQueue, CharQueueLen);
  1328. CharQueue[len] = ' '; // space to avoid concatenation
  1329. CharQueueLen += len + 1;
  1330. }
  1331. // TBD??? implement file I/O for input source code and output code (use fxn ptrs/wrappers to make librarization possible)
  1332. // DONE: support string literals
  1333. word GetToken(void)
  1334. {
  1335. char* p = CharQueue;
  1336. word ch;
  1337. word tok;
  1338. for (;;)
  1339. {
  1340. /* +-~* /% &|^! << >> && || < <= > >= == != () *[] ++ -- = += -= ~= *= /= %= &= |= ^= <<= >>= {} ,;: -> ... */
  1341. // skip white space and comments
  1342. SkipSpace(1);
  1343. if ((ch = *p) == '\0')
  1344. {
  1345. // done with the current file, drop its record,
  1346. // pick up the including files (if any) or terminate
  1347. if (EndOfFiles())
  1348. break;
  1349. continue;
  1350. }
  1351. if ((tok = GetTokenInner()) != tokEof)
  1352. {
  1353. if (PrepDontSkipTokens)
  1354. return tok;
  1355. if (tok == tokLitStr)
  1356. GetString('"', 0, 0);
  1357. continue;
  1358. }
  1359. // parse identifiers and reserved keywords
  1360. if (ch == '_' || isalpha(ch & 0xFFu))
  1361. {
  1362. word midx;
  1363. GetIdent();
  1364. if (!PrepDontSkipTokens)
  1365. continue;
  1366. tok = GetTokenByWord(TokenIdentName);
  1367. // TBD!!! think of expanding macros in the context of concatenating string literals,
  1368. // maybe factor out this piece of code
  1369. if (!strcmp(TokenIdentName, "__FILE__"))
  1370. {
  1371. char* p = FileNames[FileCnt - 1];
  1372. word len = strlen(p);
  1373. Reserve4Expansion(TokenIdentName, len + 2);
  1374. *CharQueue = '"';
  1375. memcpy(CharQueue + 1, p, len);
  1376. CharQueue[len + 1] = '"';
  1377. continue;
  1378. }
  1379. else if (!strcmp(TokenIdentName, "__LINE__"))
  1380. {
  1381. char s[(2 + CHAR_BIT * sizeof LineNo) / 3];
  1382. char *p = lab2str(s + sizeof s, LineNo);
  1383. word len = s + sizeof s - p;
  1384. Reserve4Expansion(TokenIdentName, len);
  1385. memcpy(CharQueue, p, len);
  1386. continue;
  1387. }
  1388. else if ((midx = FindMacro(TokenIdentName)) >= 0)
  1389. {
  1390. // this is a macro identifier, need to expand it
  1391. word len = MacroTable[midx];
  1392. Reserve4Expansion(TokenIdentName, len);
  1393. memcpy(CharQueue, MacroTable + midx + 1, len);
  1394. continue;
  1395. }
  1396. // treat keywords auto, const, register, restrict and volatile as white space for now
  1397. if ((tok == tokConst) | (tok == tokVolatile) |
  1398. (tok == tokAuto) | (tok == tokRegister) |
  1399. (tok == tokRestrict))
  1400. continue;
  1401. return tok;
  1402. } // endof if (ch == '_' || isalpha(ch))
  1403. // parse preprocessor directives
  1404. if (ch == '#')
  1405. {
  1406. word line = 0;
  1407. ShiftCharN(1);
  1408. // Skip space
  1409. SkipSpace(0);
  1410. // Allow # not followed by a directive
  1411. if (strchr("\r\n", *p))
  1412. continue;
  1413. // Get preprocessor directive
  1414. if (isdigit(*p & 0xFFu))
  1415. {
  1416. // gcc-style #line directive without "line"
  1417. line = 1;
  1418. }
  1419. else
  1420. {
  1421. GetIdent();
  1422. if (!strcmp(TokenIdentName, "line"))
  1423. {
  1424. // C89-style #line directive
  1425. SkipSpace(0);
  1426. if (!isdigit(*p & 0xFFu))
  1427. errorDirective();
  1428. line = 1;
  1429. }
  1430. }
  1431. if (line)
  1432. {
  1433. // Support for external, gcc-like, preprocessor output:
  1434. // # linenum filename flags
  1435. //
  1436. // no flags, flag = 1 -- start of a file
  1437. // flag = 2 -- return to a file after #include
  1438. // other flags -- uninteresting
  1439. // DONE: should also support the following C89 form:
  1440. // # line linenum filename-opt
  1441. if (GetNumber() != tokNumInt)
  1442. //error("Invalid line number in preprocessor output\n");
  1443. errorDirective();
  1444. line = TokenValueInt;
  1445. SkipSpace(0);
  1446. if (*p == '"' || *p == '<')
  1447. {
  1448. if (*p == '"')
  1449. GetString('"', 0, '#');
  1450. else
  1451. GetString('>', 0, '#');
  1452. if (strlen(TokenValueString) > MAX_FILE_NAME_LEN)
  1453. //error("File name too long in preprocessor output\n");
  1454. errorFileName();
  1455. strcpy(FileNames[FileCnt - 1], TokenValueString);
  1456. }
  1457. // Ignore gcc-style #line's flags, if any
  1458. while (!strchr("\r\n", *p))
  1459. ShiftCharN(1);
  1460. LineNo = line - 1; // "line" is the number of the next line
  1461. LinePos = 1;
  1462. continue;
  1463. } // endof if (line)
  1464. if (!strcmp(TokenIdentName, "define"))
  1465. {
  1466. // Skip space and get macro name
  1467. SkipSpace(0);
  1468. GetIdent();
  1469. if (!PrepDontSkipTokens)
  1470. {
  1471. SkipSpace(0);
  1472. while (!strchr("\r\n", *p))
  1473. ShiftCharN(1);
  1474. continue;
  1475. }
  1476. if (FindMacro(TokenIdentName) >= 0)
  1477. {
  1478. printf("Redefinition of macro ");
  1479. printf(TokenIdentName);
  1480. error("\n");
  1481. }
  1482. if (*p == '(')
  1483. //error("Unsupported type of macro '%s'\n", TokenIdentName);
  1484. errorDirective();
  1485. AddMacroIdent(TokenIdentName);
  1486. SkipSpace(0);
  1487. // accumulate the macro expansion text
  1488. while (!strchr("\r\n", *p))
  1489. {
  1490. AddMacroExpansionChar(*p);
  1491. ShiftCharN(1);
  1492. if (*p != '\0' && (strchr(" \t", *p) || (*p == '/' && (p[1] == '/' || p[1] == '*'))))
  1493. {
  1494. SkipSpace(0);
  1495. AddMacroExpansionChar(' ');
  1496. }
  1497. }
  1498. AddMacroExpansionChar('\0');
  1499. continue;
  1500. }
  1501. else if (!strcmp(TokenIdentName, "undef"))
  1502. {
  1503. // Skip space and get macro name
  1504. SkipSpace(0);
  1505. GetIdent();
  1506. if (PrepDontSkipTokens)
  1507. UndefineMacro(TokenIdentName);
  1508. SkipSpace(0);
  1509. if (!strchr("\r\n", *p))
  1510. //error("Invalid preprocessor directive\n");
  1511. errorDirective();
  1512. continue;
  1513. }
  1514. else if (!strcmp(TokenIdentName, "include"))
  1515. {
  1516. word quot;
  1517. // Skip space and get file name
  1518. SkipSpace(0);
  1519. quot = *p;
  1520. if (*p == '"')
  1521. GetString('"', 0, '#');
  1522. else if (*p == '<')
  1523. GetString('>', 0, '#');
  1524. else
  1525. //error("Invalid file name\n");
  1526. errorFileName();
  1527. SkipSpace(0);
  1528. if (!strchr("\r\n", *p))
  1529. //error("Unsupported or invalid preprocessor directive\n");
  1530. errorDirective();
  1531. if (PrepDontSkipTokens)
  1532. IncludeFile(quot);
  1533. continue;
  1534. }
  1535. else if (!strcmp(TokenIdentName, "ifdef"))
  1536. {
  1537. word def;
  1538. // Skip space and get macro name
  1539. SkipSpace(0);
  1540. GetIdent();
  1541. def = FindMacro(TokenIdentName) >= 0;
  1542. SkipSpace(0);
  1543. if (!strchr("\r\n", *p))
  1544. //error("Invalid preprocessor directive\n");
  1545. errorDirective();
  1546. pushPrep(def);
  1547. continue;
  1548. }
  1549. else if (!strcmp(TokenIdentName, "ifndef"))
  1550. {
  1551. word def;
  1552. // Skip space and get macro name
  1553. SkipSpace(0);
  1554. GetIdent();
  1555. def = FindMacro(TokenIdentName) >= 0;
  1556. SkipSpace(0);
  1557. if (!strchr("\r\n", *p))
  1558. //error("Invalid preprocessor directive\n");
  1559. errorDirective();
  1560. pushPrep(!def);
  1561. continue;
  1562. }
  1563. else if (!strcmp(TokenIdentName, "else"))
  1564. {
  1565. word def;
  1566. SkipSpace(0);
  1567. if (!strchr("\r\n", *p))
  1568. //error("Invalid preprocessor directive\n");
  1569. errorDirective();
  1570. def = popPrep();
  1571. if (def >= 2)
  1572. error("#else or #endif without #if(n)def\n");
  1573. pushPrep(2 + !def); // #else works in opposite way to its preceding #if(n)def
  1574. continue;
  1575. }
  1576. else if (!strcmp(TokenIdentName, "endif"))
  1577. {
  1578. SkipSpace(0);
  1579. if (!strchr("\r\n", *p))
  1580. //error("Invalid preprocessor directive\n");
  1581. errorDirective();
  1582. popPrep();
  1583. continue;
  1584. }
  1585. if (!PrepDontSkipTokens)
  1586. {
  1587. // If skipping code and directives under #ifdef/#ifndef/#else,
  1588. // ignore unsupported directives #if, #elif, #error (no error checking)
  1589. if (!strcmp(TokenIdentName, "if"))
  1590. pushPrep(0);
  1591. else if (!strcmp(TokenIdentName, "elif"))
  1592. popPrep(), pushPrep(0);
  1593. SkipLine();
  1594. continue;
  1595. }
  1596. //error("Unsupported or invalid preprocessor directive\n");
  1597. errorDirective();
  1598. } // endof if (ch == '#')
  1599. error("Invalid or unsupported character");
  1600. //error("Invalid or unsupported character with code 0x%02X\n", *p & 0xFFu);
  1601. } // endof for (;;)
  1602. return tokEof;
  1603. }
  1604. void errorRedecl(char* s)
  1605. {
  1606. printf("Invalid or unsupported redeclaration of ");
  1607. printf(s);
  1608. error("\n");
  1609. }
  1610. #include "backend.c"
  1611. // expr.c code
  1612. void push2(word v, word v2)
  1613. {
  1614. if (sp >= STACK_SIZE)
  1615. //error("expression stack overflow!\n");
  1616. errorLongExpr();
  1617. stack[sp][0] = v;
  1618. stack[sp++][1] = v2;
  1619. }
  1620. void push(word v)
  1621. {
  1622. push2(v, 0);
  1623. }
  1624. word stacktop()
  1625. {
  1626. if (sp == 0)
  1627. //error("expression stack underflow!\n");
  1628. errorInternal(3);
  1629. return stack[sp - 1][0];
  1630. }
  1631. word pop2(word* v2)
  1632. {
  1633. word v = stacktop();
  1634. *v2 = stack[sp - 1][1];
  1635. sp--;
  1636. return v;
  1637. }
  1638. void ins2(word pos, word v, word v2)
  1639. {
  1640. if (sp >= STACK_SIZE)
  1641. //error("expression stack overflow!\n");
  1642. errorLongExpr();
  1643. memmove(&stack[pos + 1], &stack[pos], sizeof(stack[0]) * (sp - pos));
  1644. stack[pos][0] = v;
  1645. stack[pos][1] = v2;
  1646. sp++;
  1647. }
  1648. void ins(word pos, word v)
  1649. {
  1650. ins2(pos, v, 0);
  1651. }
  1652. void del(word pos, word cnt)
  1653. {
  1654. memmove(stack[pos],
  1655. stack[pos + cnt],
  1656. sizeof(stack[0]) * (sp - (pos + cnt)));
  1657. sp -= cnt;
  1658. }
  1659. void pushop2(word v, word v2)
  1660. {
  1661. if (opsp >= OPERATOR_STACK_SIZE)
  1662. //error("operator stack overflow!\n");
  1663. errorLongExpr();
  1664. opstack[opsp][0] = v;
  1665. opstack[opsp++][1] = v2;
  1666. }
  1667. void pushop(word v)
  1668. {
  1669. pushop2(v, 0);
  1670. }
  1671. word opstacktop()
  1672. {
  1673. if (opsp == 0)
  1674. //error("operator stack underflow!\n");
  1675. errorInternal(4);
  1676. return opstack[opsp - 1][0];
  1677. }
  1678. word popop2(word* v2)
  1679. {
  1680. word v = opstacktop();
  1681. *v2 = opstack[opsp - 1][1];
  1682. opsp--;
  1683. return v;
  1684. }
  1685. word popop()
  1686. {
  1687. word v2;
  1688. return popop2(&v2);
  1689. }
  1690. word isop(word tok)
  1691. {
  1692. static unsigned char toks[] =
  1693. {
  1694. '!',
  1695. '~',
  1696. '&',
  1697. '*',
  1698. '/', '%',
  1699. '+', '-',
  1700. '|', '^',
  1701. '<', '>',
  1702. '=',
  1703. tokLogOr, tokLogAnd,
  1704. tokEQ, tokNEQ,
  1705. tokLEQ, tokGEQ,
  1706. tokLShift, tokRShift,
  1707. tokInc, tokDec,
  1708. tokSizeof,
  1709. tokAssignMul, tokAssignDiv, tokAssignMod,
  1710. tokAssignAdd, tokAssignSub,
  1711. tokAssignLSh, tokAssignRSh,
  1712. tokAssignAnd, tokAssignXor, tokAssignOr,
  1713. tokComma,
  1714. '?'
  1715. };
  1716. unsigned i;
  1717. for (i = 0; i < division(sizeof toks , sizeof toks[0]); i++)
  1718. if (toks[i] == tok)
  1719. return 1;
  1720. return 0;
  1721. }
  1722. word isunary(word tok)
  1723. {
  1724. return (tok == '!') | (tok == '~') | (tok == tokInc) | (tok == tokDec) | (tok == tokSizeof);
  1725. }
  1726. word preced(word tok)
  1727. {
  1728. switch (tok)
  1729. {
  1730. case '*': case '/': case '%': return 13;
  1731. case '+': case '-': return 12;
  1732. case tokLShift: case tokRShift: return 11;
  1733. case '<': case '>': case tokLEQ: case tokGEQ: return 10;
  1734. case tokEQ: case tokNEQ: return 9;
  1735. case '&': return 8;
  1736. case '^': return 7;
  1737. case '|': return 6;
  1738. case tokLogAnd: return 5;
  1739. case tokLogOr: return 4;
  1740. case '?': case ':': return 3;
  1741. case '=':
  1742. case tokAssignMul: case tokAssignDiv: case tokAssignMod:
  1743. case tokAssignAdd: case tokAssignSub:
  1744. case tokAssignLSh: case tokAssignRSh:
  1745. case tokAssignAnd: case tokAssignXor: case tokAssignOr:
  1746. return 2;
  1747. case tokComma:
  1748. return 1;
  1749. }
  1750. return 0;
  1751. }
  1752. word precedGEQ(word lfttok, word rhttok)
  1753. {
  1754. // DONE: rethink the comma operator as it could be implemented similarly
  1755. // DONE: is this correct:???
  1756. word pl = preced(lfttok);
  1757. word pr = preced(rhttok);
  1758. // ternary/conditional operator ?: is right-associative
  1759. if (pl == 3 && pr >= 3)
  1760. pl = 0;
  1761. // assignment is right-associative
  1762. if (pl == 2 && pr >= 2)
  1763. pl = 0;
  1764. return pl >= pr;
  1765. }
  1766. word expr(word tok, word* gotUnary, word commaSeparator);
  1767. char* lab2str(char* p, word n)
  1768. {
  1769. do
  1770. {
  1771. *--p = '0' + modulo(n , 10);
  1772. n = division(n, 10);
  1773. } while (n);
  1774. return p;
  1775. }
  1776. word exprUnary(word tok, word* gotUnary, word commaSeparator, word argOfSizeOf)
  1777. {
  1778. static word sizeofLevel = 0;
  1779. word decl = 0;
  1780. *gotUnary = 0;
  1781. if (isop(tok) && (isunary(tok) || strchr("&*+-", tok)))
  1782. {
  1783. word lastTok = tok;
  1784. word sizeofLevelInc = lastTok == tokSizeof;
  1785. sizeofLevel += sizeofLevelInc;
  1786. tok = exprUnary(GetToken(), gotUnary, commaSeparator, sizeofLevelInc);
  1787. sizeofLevel -= sizeofLevelInc;
  1788. if (!*gotUnary)
  1789. //error("exprUnary(): primary expression expected after token %s\n", GetTokenName(lastTok));
  1790. errorUnexpectedToken(tok);
  1791. switch (lastTok)
  1792. {
  1793. // DONE: remove all collapsing of all unary operators.
  1794. // It's wrong because type checking must occur before any optimizations.
  1795. // WRONG: DONE: collapse alternating & and * (e.g. "*&*&x" "&*&*x")
  1796. // WRONGISH: DONE: replace prefix ++/-- with +=1/-=1
  1797. case '&':
  1798. push(tokUnaryAnd);
  1799. break;
  1800. case '*':
  1801. push(tokUnaryStar);
  1802. break;
  1803. case '+':
  1804. push(tokUnaryPlus);
  1805. break;
  1806. case '-':
  1807. push(tokUnaryMinus);
  1808. break;
  1809. case '!':
  1810. // replace "!" with "== 0"
  1811. push(tokNumInt);
  1812. push(tokEQ);
  1813. break;
  1814. default:
  1815. push(lastTok);
  1816. break;
  1817. }
  1818. }
  1819. else
  1820. {
  1821. word inspos = sp;
  1822. if (tok == tokNumInt ||
  1823. tok == tokNumUint)
  1824. {
  1825. push2(tok, TokenValueInt);
  1826. *gotUnary = 1;
  1827. tok = GetToken();
  1828. }
  1829. else if (tok == tokLitStr
  1830. )
  1831. {
  1832. word lbl = LabelCnt++;
  1833. word id;
  1834. word ltok = tok;
  1835. word wide = 0;
  1836. unsigned chsz = 1;
  1837. unsigned sz = chsz;
  1838. // imitate definition: char #[len] = "...";
  1839. if (!sizeofLevel)
  1840. {
  1841. if (CurHeaderFooter)
  1842. puts2(CurHeaderFooter[1]);
  1843. puts2(RoDataHeaderFooter[0]);
  1844. GenNumLabel(lbl);
  1845. }
  1846. do
  1847. {
  1848. GetString('"', wide, sizeofLevel ? 0 : 'd'); // throw away string data inside sizeof, e.g. sizeof "a" or sizeof("a" + 1)
  1849. if (sz + TokenStringSize < sz ||
  1850. sz + TokenStringSize >= truncUint(-1))
  1851. errorStrLen();
  1852. sz += TokenStringSize;
  1853. tok = GetToken();
  1854. } while (tok == ltok); // concatenate adjacent string literals
  1855. if (!sizeofLevel)
  1856. {
  1857. GenZeroData(chsz, 0);
  1858. puts2(RoDataHeaderFooter[1]);
  1859. if (CurHeaderFooter)
  1860. puts2(CurHeaderFooter[0]);
  1861. }
  1862. // DONE: can this break incomplete yet declarations???, e.g.: int x[sizeof("az")][5];
  1863. PushSyntax2(tokIdent, id = AddNumericIdent(lbl));
  1864. PushSyntax('[');
  1865. PushSyntax2(tokNumUint, division(sz, chsz));
  1866. PushSyntax(']');
  1867. PushSyntax(tokChar);
  1868. push2(tokIdent, id);
  1869. *gotUnary = 1;
  1870. }
  1871. else if (tok == tokIdent)
  1872. {
  1873. push2(tok, AddIdent(TokenIdentName));
  1874. *gotUnary = 1;
  1875. tok = GetToken();
  1876. }
  1877. else if (tok == '(')
  1878. {
  1879. tok = GetToken();
  1880. decl = TokenStartsDeclaration(tok, 1);
  1881. if (decl)
  1882. {
  1883. word synPtr;
  1884. word lbl = LabelCnt++;
  1885. char s[1 + (2 + CHAR_BIT * sizeof lbl) / 3 + sizeof "<something>" - 1];
  1886. char *p = s + sizeof s;
  1887. tok = ParseDecl(tok, NULL, !argOfSizeOf, 0);
  1888. if (tok != ')')
  1889. //error("exprUnary(): ')' expected, unexpected token %s\n", GetTokenName(tok));
  1890. errorUnexpectedToken(tok);
  1891. synPtr = FindSymbol("<something>");
  1892. // Rename "<something>" to "<something#>", where # is lbl.
  1893. // This makes the nameless declaration uniquely identifiable by name.
  1894. *--p = '\0';
  1895. *--p = ")>"[argOfSizeOf]; // differentiate casts (something#) from not casts <something#>
  1896. p = lab2str(p, lbl);
  1897. p -= sizeof "<something>" - 2 - 1;
  1898. memcpy(p, "something", sizeof "something" - 1);
  1899. *--p = "(<"[argOfSizeOf]; // differentiate casts (something#) from not casts <something#>
  1900. SyntaxStack1[synPtr] = AddIdent(p);
  1901. tok = GetToken();
  1902. if (argOfSizeOf)
  1903. {
  1904. // expression: sizeof(type)
  1905. *gotUnary = 1;
  1906. }
  1907. else
  1908. {
  1909. // unary type cast operator: (type)
  1910. decl = 0;
  1911. tok = exprUnary(tok, gotUnary, commaSeparator, 0);
  1912. if (!*gotUnary)
  1913. //error("exprUnary(): primary expression expected after '(type)'\n");
  1914. errorUnexpectedToken(tok);
  1915. }
  1916. push2(tokIdent, SyntaxStack1[synPtr]);
  1917. }
  1918. else
  1919. {
  1920. tok = expr(tok, gotUnary, 0);
  1921. if (tok != ')')
  1922. //error("exprUnary(): ')' expected, unexpected token %s\n", GetTokenName(tok));
  1923. errorUnexpectedToken(tok);
  1924. if (!*gotUnary)
  1925. //error("exprUnary(): primary expression expected in '()'\n");
  1926. errorUnexpectedToken(tok);
  1927. tok = GetToken();
  1928. }
  1929. }
  1930. while (*gotUnary && !decl)
  1931. {
  1932. // DONE: f(args1)(args2) and the like: need stack order: args2, args1, f, (), ()
  1933. // DONE: reverse the order of evaluation of groups of args in
  1934. // f(args1)(args2)(args3)
  1935. // DONE: reverse the order of function argument evaluation for variadic functions
  1936. // we want 1st arg to be the closest to the stack top.
  1937. // DONE: (args)[index] can be repeated interchangeably indefinitely
  1938. // DONE: (expr)() & (expr)[]
  1939. // DONE: [index] can be followed by ++/--, which can be followed by [index] and so on...
  1940. // DONE: postfix ++/-- & differentiate from prefix ++/--
  1941. if (tok == '(')
  1942. {
  1943. word acnt = 0;
  1944. ins(inspos, '(');
  1945. for (;;)
  1946. {
  1947. word pos2 = sp;
  1948. tok = GetToken();
  1949. tok = expr(tok, gotUnary, 1);
  1950. // Reverse the order of argument evaluation, which is important for
  1951. // variadic functions like printf():
  1952. // we want 1st arg to be the closest to the stack top.
  1953. // This also reverses the order of evaluation of all groups of
  1954. // arguments.
  1955. while (pos2 < sp)
  1956. {
  1957. // TBD??? not quite efficient
  1958. word v, v2;
  1959. v = pop2(&v2);
  1960. ins2(inspos + 1, v, v2);
  1961. pos2++;
  1962. }
  1963. if (tok == ',')
  1964. {
  1965. if (!*gotUnary)
  1966. //error("exprUnary(): primary expression (fxn argument) expected before ','\n");
  1967. errorUnexpectedToken(tok);
  1968. acnt++;
  1969. ins(inspos + 1, ','); // helper argument separator (hint for expression evaluator)
  1970. continue; // off to next arg
  1971. }
  1972. if (tok == ')')
  1973. {
  1974. if (acnt && !*gotUnary)
  1975. //error("exprUnary(): primary expression (fxn argument) expected between ',' and ')'\n");
  1976. errorUnexpectedToken(tok);
  1977. *gotUnary = 1; // don't fail for 0 args in ()
  1978. break; // end of args
  1979. }
  1980. // DONE: think of inserting special arg pseudo tokens for verification purposes
  1981. //error("exprUnary(): ',' or ')' expected, unexpected token %s\n", GetTokenName(tok));
  1982. errorUnexpectedToken(tok);
  1983. } // endof for(;;) for fxn args
  1984. push(')');
  1985. }
  1986. else if (tok == '[')
  1987. {
  1988. tok = GetToken();
  1989. tok = expr(tok, gotUnary, 0);
  1990. if (!*gotUnary)
  1991. //error("exprUnary(): primary expression expected in '[]'\n");
  1992. errorUnexpectedToken(tok);
  1993. if (tok != ']')
  1994. //error("exprUnary(): ']' expected, unexpected token %s\n", GetTokenName(tok));
  1995. errorUnexpectedToken(tok);
  1996. // TBD??? add implicit casts to size_t of array indicies.
  1997. // E1[E2] -> *(E1 + E2)
  1998. // push('[');
  1999. push('+');
  2000. push(tokUnaryStar);
  2001. }
  2002. // WRONG: DONE: replace postfix ++/-- with (+=1)-1/(-=1)+1
  2003. else if (tok == tokInc)
  2004. {
  2005. push(tokPostInc);
  2006. }
  2007. else if (tok == tokDec)
  2008. {
  2009. push(tokPostDec);
  2010. }
  2011. else if (tok == '.' || tok == tokArrow)
  2012. {
  2013. // transform a.b into (&a)->b
  2014. if (tok == '.')
  2015. push(tokUnaryAnd);
  2016. tok = GetToken();
  2017. if (tok != tokIdent)
  2018. errorUnexpectedToken(tok);
  2019. push2(tok, AddIdent(TokenIdentName));
  2020. // "->" in "a->b" will function as "+" in "*(type_of_b*)((char*)a + offset_of_b_in_a)"
  2021. push(tokArrow);
  2022. push(tokUnaryStar);
  2023. }
  2024. else
  2025. {
  2026. break;
  2027. }
  2028. tok = GetToken();
  2029. } // endof while (*gotUnary)
  2030. }
  2031. if (tok == ',' && !commaSeparator)
  2032. tok = tokComma;
  2033. return tok;
  2034. }
  2035. word expr(word tok, word* gotUnary, word commaSeparator)
  2036. {
  2037. *gotUnary = 0;
  2038. pushop(tokEof);
  2039. tok = exprUnary(tok, gotUnary, commaSeparator, 0);
  2040. while (tok != tokEof && strchr(",;:)]}", tok) == NULL && *gotUnary)
  2041. {
  2042. if (isop(tok) && !isunary(tok))
  2043. {
  2044. while (precedGEQ(opstacktop(), tok))
  2045. {
  2046. word v, v2;
  2047. v = popop2(&v2);
  2048. // move ?expr: as a whole to the expression stack as "expr?"
  2049. if (v == '?')
  2050. {
  2051. word cnt = v2;
  2052. while (cnt--)
  2053. {
  2054. v = popop2(&v2);
  2055. push2(v, v2);
  2056. }
  2057. v = '?';
  2058. v2 = 0;
  2059. }
  2060. push2(v, v2);
  2061. }
  2062. // here: preced(postacktop()) < preced(tok)
  2063. // treat the ternary/conditional operator ?expr: as a pseudo binary operator
  2064. if (tok == '?')
  2065. {
  2066. word ssp = sp;
  2067. word cnt;
  2068. tok = expr(GetToken(), gotUnary, 0);
  2069. if (!*gotUnary || tok != ':')
  2070. errorUnexpectedToken(tok);
  2071. // move ?expr: as a whole to the operator stack
  2072. // this is beautiful and ugly at the same time
  2073. cnt = sp - ssp;
  2074. while (sp > ssp)
  2075. {
  2076. word v, v2;
  2077. v = pop2(&v2);
  2078. pushop2(v, v2);
  2079. }
  2080. // remember the length of the expression between ? and :
  2081. pushop2('?', cnt);
  2082. }
  2083. else
  2084. {
  2085. pushop(tok);
  2086. }
  2087. tok = exprUnary(GetToken(), gotUnary, commaSeparator, 0);
  2088. // DONE: figure out a check to see if exprUnary() fails to add a rhs operand
  2089. if (!*gotUnary)
  2090. //error("expr(): primary expression expected after token %s\n", GetTokenName(lastTok));
  2091. errorUnexpectedToken(tok);
  2092. continue;
  2093. }
  2094. //error("expr(): Unexpected token %s\n", GetTokenName(tok));
  2095. errorUnexpectedToken(tok);
  2096. }
  2097. while (opstacktop() != tokEof)
  2098. {
  2099. word v, v2;
  2100. v = popop2(&v2);
  2101. // move ?expr: as a whole to the expression stack as "expr?"
  2102. if (v == '?')
  2103. {
  2104. word cnt = v2;
  2105. while (cnt--)
  2106. {
  2107. v = popop2(&v2);
  2108. push2(v, v2);
  2109. }
  2110. v = '?';
  2111. v2 = 0;
  2112. }
  2113. push2(v, v2);
  2114. }
  2115. popop();
  2116. return tok;
  2117. }
  2118. word isAnyPtr(word ExprTypeSynPtr)
  2119. {
  2120. if (ExprTypeSynPtr < 0)
  2121. return 1;
  2122. switch (SyntaxStack0[ExprTypeSynPtr])
  2123. {
  2124. case '*':
  2125. case '[':
  2126. case '(':
  2127. return 1;
  2128. }
  2129. return 0;
  2130. }
  2131. word derefAnyPtr(word ExprTypeSynPtr)
  2132. {
  2133. if (ExprTypeSynPtr < 0)
  2134. return -ExprTypeSynPtr;
  2135. switch (SyntaxStack0[ExprTypeSynPtr])
  2136. {
  2137. case '*':
  2138. return ExprTypeSynPtr + 1;
  2139. case '[':
  2140. return ExprTypeSynPtr + 3;
  2141. case '(':
  2142. return ExprTypeSynPtr;
  2143. }
  2144. errorInternal(22);
  2145. return -1;
  2146. }
  2147. void decayArray(word* ExprTypeSynPtr, word arithmetic)
  2148. {
  2149. // Dacay arrays to pointers to their first elements
  2150. if (*ExprTypeSynPtr >= 0 && SyntaxStack0[*ExprTypeSynPtr] == '[')
  2151. {
  2152. (*ExprTypeSynPtr) += 3;
  2153. // we cannot insert another '*' into the type to make it a pointer
  2154. // to the first element, so make the index into the type negative
  2155. *ExprTypeSynPtr = -*ExprTypeSynPtr;
  2156. }
  2157. // DONE: disallow arithmetic on pointers to void
  2158. // DONE: disallow function pointers
  2159. if (arithmetic && isAnyPtr(*ExprTypeSynPtr))
  2160. {
  2161. word pointee = derefAnyPtr(*ExprTypeSynPtr);
  2162. switch (SyntaxStack0[pointee])
  2163. {
  2164. case tokVoid:
  2165. //error("decayArray(): cannot do pointer arithmetic on a pointer to 'void'\n");
  2166. errorUnexpectedVoid();
  2167. default:
  2168. //error("decayArray(): cannot do pointer arithmetic on a pointer to an incomplete type\n");
  2169. if (!GetDeclSize(pointee, 0))
  2170. // "fallthrough"
  2171. case '(':
  2172. //error("decayArray(): cannot do pointer arithmetic on a pointer to a function\n");
  2173. errorOpType();
  2174. }
  2175. }
  2176. }
  2177. void lvalueCheck(word ExprTypeSynPtr, word pos)
  2178. {
  2179. if (ExprTypeSynPtr >= 0 &&
  2180. (SyntaxStack0[ExprTypeSynPtr] == '[' || SyntaxStack0[ExprTypeSynPtr] == '('))
  2181. {
  2182. // we can have arrays formed by dereference, e.g.
  2183. // char (*pac)[1]; // *pac is array of 1 char
  2184. // // ++*pac or (*pac)-- are not allowed
  2185. // and likewise functions, e.g.
  2186. // int (*pf)(int); // *pf is a function taking int and returning int
  2187. // // *pf = 0; is not allowed
  2188. // and that dereference shouldn't be confused for lvalue,
  2189. // hence explicitly checking for array and function types
  2190. //error("exprval(): lvalue expected\n");
  2191. errorNotLvalue();
  2192. }
  2193. // lvalue is a dereferenced address, check for a dereference
  2194. if (stack[pos][0] != tokUnaryStar)
  2195. //error("exprval(): lvalue expected\n");
  2196. errorNotLvalue();
  2197. }
  2198. void nonVoidTypeCheck(word ExprTypeSynPtr)
  2199. {
  2200. if (ExprTypeSynPtr >= 0 && SyntaxStack0[ExprTypeSynPtr] == tokVoid)
  2201. //error("nonVoidTypeCheck(): unexpected operand type 'void' for operator '%s'\n", GetTokenName(tok));
  2202. errorUnexpectedVoid();
  2203. }
  2204. void scalarTypeCheck(word ExprTypeSynPtr)
  2205. {
  2206. nonVoidTypeCheck(ExprTypeSynPtr);
  2207. if (ExprTypeSynPtr >= 0 && SyntaxStack0[ExprTypeSynPtr] == tokStructPtr)
  2208. errorOpType();
  2209. }
  2210. void numericTypeCheck(word ExprTypeSynPtr)
  2211. {
  2212. if (ExprTypeSynPtr >= 0)
  2213. switch (SyntaxStack0[ExprTypeSynPtr])
  2214. {
  2215. case tokChar:
  2216. case tokSChar:
  2217. case tokUChar:
  2218. case tokShort:
  2219. case tokUShort:
  2220. case tokInt:
  2221. case tokUnsigned:
  2222. return;
  2223. }
  2224. //error("numericTypeCheck(): unexpected operand type for operator '%s', numeric type expected\n", GetTokenName(tok));
  2225. errorOpType();
  2226. }
  2227. void anyIntTypeCheck(word ExprTypeSynPtr)
  2228. {
  2229. // Check for any integer type
  2230. numericTypeCheck(ExprTypeSynPtr);
  2231. }
  2232. word isUint(word ExprTypeSynPtr)
  2233. {
  2234. return ExprTypeSynPtr >= 0 && SyntaxStack0[ExprTypeSynPtr] == tokUnsigned;
  2235. }
  2236. void compatCheck(word* ExprTypeSynPtr, word TheOtherExprTypeSynPtr, word ConstExpr[2], word lidx, word ridx)
  2237. {
  2238. word exprTypeSynPtr = *ExprTypeSynPtr;
  2239. word c = 0;
  2240. word lptr, rptr, lnum, rnum;
  2241. // (un)decay/convert functions to pointers to functions
  2242. // and to simplify matters convert all '*' pointers to negative type indices
  2243. if (exprTypeSynPtr >= 0)
  2244. {
  2245. switch (SyntaxStack0[exprTypeSynPtr])
  2246. {
  2247. case '*':
  2248. exprTypeSynPtr++;
  2249. // fallthrough
  2250. case '(':
  2251. exprTypeSynPtr = -exprTypeSynPtr;
  2252. }
  2253. *ExprTypeSynPtr = exprTypeSynPtr;
  2254. }
  2255. if (TheOtherExprTypeSynPtr >= 0)
  2256. {
  2257. switch (SyntaxStack0[TheOtherExprTypeSynPtr])
  2258. {
  2259. case '*':
  2260. TheOtherExprTypeSynPtr++;
  2261. // fallthrough
  2262. case '(':
  2263. TheOtherExprTypeSynPtr = -TheOtherExprTypeSynPtr;
  2264. }
  2265. }
  2266. lptr = exprTypeSynPtr < 0;
  2267. rptr = TheOtherExprTypeSynPtr < 0;
  2268. lnum = !lptr && (SyntaxStack0[exprTypeSynPtr] == tokInt ||
  2269. SyntaxStack0[exprTypeSynPtr] == tokUnsigned);
  2270. rnum = !rptr && (SyntaxStack0[TheOtherExprTypeSynPtr] == tokInt ||
  2271. SyntaxStack0[TheOtherExprTypeSynPtr] == tokUnsigned);
  2272. // both operands have arithmetic type
  2273. // (arithmetic operands have been already promoted):
  2274. if (lnum && rnum)
  2275. return;
  2276. // both operands have void type:
  2277. if (!lptr && SyntaxStack0[exprTypeSynPtr] == tokVoid &&
  2278. !rptr && SyntaxStack0[TheOtherExprTypeSynPtr] == tokVoid)
  2279. return;
  2280. // one operand is a pointer and the other is NULL constant
  2281. // ((void*)0 is also a valid null pointer constant),
  2282. // the type of the expression is that of the pointer:
  2283. if (lptr &&
  2284. ((rnum && ConstExpr[1] && truncInt(stack[ridx][1]) == 0) ||
  2285. (rptr && SyntaxStack0[-TheOtherExprTypeSynPtr] == tokVoid &&
  2286. (stack[ridx][0] == tokNumInt || stack[ridx][0] == tokNumUint) &&
  2287. truncInt(stack[ridx][1]) == 0)))
  2288. return;
  2289. if (rptr &&
  2290. ((lnum && ConstExpr[0] && truncInt(stack[lidx][1]) == 0) ||
  2291. (lptr && SyntaxStack0[-exprTypeSynPtr] == tokVoid &&
  2292. (stack[lidx][0] == tokNumInt || stack[lidx][0] == tokNumUint) &&
  2293. truncInt(stack[lidx][1]) == 0)))
  2294. {
  2295. *ExprTypeSynPtr = TheOtherExprTypeSynPtr;
  2296. return;
  2297. }
  2298. // not expecting non-pointers beyond this point
  2299. if (!(lptr && rptr))
  2300. errorOpType();
  2301. // one operand is a pointer and the other is a pointer to void
  2302. // (except (void*)0 (AKA NULL), which is different from other pointers to void),
  2303. // the type of the expression is pointer to void:
  2304. if (SyntaxStack0[-exprTypeSynPtr] == tokVoid)
  2305. return;
  2306. if (SyntaxStack0[-TheOtherExprTypeSynPtr] == tokVoid)
  2307. {
  2308. *ExprTypeSynPtr = TheOtherExprTypeSynPtr;
  2309. return;
  2310. }
  2311. // both operands are pointers to compatible types:
  2312. if (exprTypeSynPtr == TheOtherExprTypeSynPtr)
  2313. return;
  2314. exprTypeSynPtr = -exprTypeSynPtr;
  2315. TheOtherExprTypeSynPtr = -TheOtherExprTypeSynPtr;
  2316. for (;;)
  2317. {
  2318. word tok = SyntaxStack0[exprTypeSynPtr];
  2319. if (tok != SyntaxStack0[TheOtherExprTypeSynPtr])
  2320. errorOpType();
  2321. if (tok != tokIdent &&
  2322. SyntaxStack1[exprTypeSynPtr] != SyntaxStack1[TheOtherExprTypeSynPtr])
  2323. errorOpType();
  2324. c += (tok == '(') - (tok == ')') + (tok == '[') - (tok == ']');
  2325. if (!c)
  2326. {
  2327. switch (tok)
  2328. {
  2329. case tokVoid:
  2330. case tokChar: case tokSChar: case tokUChar:
  2331. case tokShort: case tokUShort:
  2332. case tokInt: case tokUnsigned:
  2333. case tokStructPtr:
  2334. return;
  2335. }
  2336. }
  2337. exprTypeSynPtr++;
  2338. TheOtherExprTypeSynPtr++;
  2339. }
  2340. }
  2341. void shiftCountCheck(word *psr, word idx, word ExprTypeSynPtr)
  2342. {
  2343. word sr = *psr;
  2344. // can't shift by a negative count and by a count exceeding
  2345. // the number of bits in int
  2346. if ((SyntaxStack0[ExprTypeSynPtr] != tokUnsigned && sr < 0) ||
  2347. (unsigned)sr >= CHAR_BIT * sizeof(word) ||
  2348. (unsigned)sr >= 8u * SizeOfWord)
  2349. {
  2350. //error("exprval(): Invalid shift count\n");
  2351. warning("Shift count out of range\n");
  2352. // truncate the count, so the assembler doesn't get an invalid count
  2353. sr &= SizeOfWord * 8 - 1;
  2354. *psr = sr;
  2355. stack[idx][1] = sr;
  2356. }
  2357. }
  2358. word divCheckAndCalc(word tok, word* psl, word sr, word Unsigned, word ConstExpr[2])
  2359. {
  2360. word div0 = 0;
  2361. word sl = *psl;
  2362. word int_min = INT_MIN;
  2363. if (!ConstExpr[1])
  2364. return !div0;
  2365. if (Unsigned)
  2366. {
  2367. sl = (word)truncUint(sl);
  2368. sr = (word)truncUint(sr);
  2369. }
  2370. else
  2371. {
  2372. sl = truncInt(sl);
  2373. sr = truncInt(sr);
  2374. }
  2375. if (sr == 0)
  2376. {
  2377. div0 = 1;
  2378. }
  2379. else if (!ConstExpr[0])
  2380. {
  2381. return !div0;
  2382. }
  2383. else if (!Unsigned && ((sl == int_min && sr == -1) || division(sl , sr) != truncInt(division(sl , sr))))
  2384. {
  2385. div0 = 1;
  2386. }
  2387. else
  2388. {
  2389. if (Unsigned)
  2390. {
  2391. if (tok == '/')
  2392. sl = (word)((unsigned)division(sl , sr));
  2393. else
  2394. sl = (word)((unsigned)modulo(sl , sr));
  2395. }
  2396. else
  2397. {
  2398. // TBD!!! C89 gives freedom in how exactly division of negative integers
  2399. // can be implemented w.r.t. rounding and w.r.t. the sign of the remainder.
  2400. // A stricter, C99-conforming implementation, non-dependent on the
  2401. // compiler used to compile Smaller C is needed.
  2402. if (tok == '/')
  2403. sl = division(sl, sr);
  2404. else
  2405. sl = modulo(sl, sr);
  2406. }
  2407. *psl = sl;
  2408. }
  2409. if (div0)
  2410. warning("Division by 0 or division overflow\n");
  2411. return !div0;
  2412. }
  2413. void promoteType(word* ExprTypeSynPtr, word* TheOtherExprTypeSynPtr)
  2414. {
  2415. // Integer promotion to signed int or unsigned int from smaller types
  2416. // (all kinds of char and short). Promotion to unsigned int occurs
  2417. // only if the other operand (of a binary operator) is already an
  2418. // unsigned int. Effectively, this promotion to unsigned int performs
  2419. // usual arithmetic conversion for integers.
  2420. if (*ExprTypeSynPtr >= 0)
  2421. {
  2422. // chars must be promoted to ints in expressions as the very first thing
  2423. switch (SyntaxStack0[*ExprTypeSynPtr])
  2424. {
  2425. case tokChar:
  2426. case tokShort:
  2427. case tokUShort:
  2428. case tokSChar:
  2429. case tokUChar:
  2430. *ExprTypeSynPtr = SymIntSynPtr;
  2431. }
  2432. if (*TheOtherExprTypeSynPtr >= 0)
  2433. {
  2434. // ints must be converted to unsigned ints if they are used in binary
  2435. // operators whose other operand is unsigned int (except <<,>>,<<=,>>=)
  2436. if (SyntaxStack0[*ExprTypeSynPtr] == tokInt &&
  2437. SyntaxStack0[*TheOtherExprTypeSynPtr] == tokUnsigned)
  2438. *ExprTypeSynPtr = SymUintSynPtr;
  2439. }
  2440. }
  2441. }
  2442. word GetFxnInfo(word ExprTypeSynPtr, word* MinParams, word* MaxParams, word* ReturnExprTypeSynPtr, word* FirstParamSynPtr)
  2443. {
  2444. *MaxParams = *MinParams = 0;
  2445. if (ExprTypeSynPtr < 0)
  2446. {
  2447. ExprTypeSynPtr = -ExprTypeSynPtr;
  2448. }
  2449. else
  2450. {
  2451. while (SyntaxStack0[ExprTypeSynPtr] == tokIdent || SyntaxStack0[ExprTypeSynPtr] == tokLocalOfs)
  2452. ExprTypeSynPtr++;
  2453. if (SyntaxStack0[ExprTypeSynPtr] == '*')
  2454. ExprTypeSynPtr++;
  2455. }
  2456. if (SyntaxStack0[ExprTypeSynPtr] != '(')
  2457. return 0;
  2458. // DONE: return syntax pointer to the function's return type
  2459. // Count params
  2460. ExprTypeSynPtr++;
  2461. if (FirstParamSynPtr)
  2462. *FirstParamSynPtr = ExprTypeSynPtr;
  2463. if (SyntaxStack0[ExprTypeSynPtr] == ')')
  2464. {
  2465. // "fxn()": unspecified parameters, so, there can be any number of them
  2466. *MaxParams = 32767; // INT_MAX;
  2467. *ReturnExprTypeSynPtr = ExprTypeSynPtr + 1;
  2468. return 1;
  2469. }
  2470. if (SyntaxStack0[ExprTypeSynPtr + 1] == tokVoid)
  2471. {
  2472. // "fxn(void)": 0 parameters
  2473. *ReturnExprTypeSynPtr = ExprTypeSynPtr + 3;
  2474. return 1;
  2475. }
  2476. for (;;)
  2477. {
  2478. word tok = SyntaxStack0[ExprTypeSynPtr];
  2479. if (tok == tokIdent)
  2480. {
  2481. if (SyntaxStack0[ExprTypeSynPtr + 1] != tokEllipsis)
  2482. {
  2483. ++*MinParams;
  2484. ++*MaxParams;
  2485. }
  2486. else
  2487. {
  2488. *MaxParams = 32767; // INT_MAX;
  2489. }
  2490. }
  2491. else if (tok == '(')
  2492. {
  2493. // skip parameters in parameters
  2494. word c = 1;
  2495. while (c && ExprTypeSynPtr < SyntaxStackCnt)
  2496. {
  2497. tok = SyntaxStack0[++ExprTypeSynPtr];
  2498. c += (tok == '(') - (tok == ')');
  2499. }
  2500. }
  2501. else if (tok == ')')
  2502. {
  2503. ExprTypeSynPtr++;
  2504. break;
  2505. }
  2506. ExprTypeSynPtr++;
  2507. }
  2508. // get the function's return type
  2509. *ReturnExprTypeSynPtr = ExprTypeSynPtr;
  2510. return 1;
  2511. }
  2512. void simplifyConstExpr(word val, word isConst, word* ExprTypeSynPtr, word top, word bottom)
  2513. {
  2514. // If non-const, nothing to do.
  2515. // If const and already a number behind the scenes, nothing to do
  2516. // (val must not differ from the number!).
  2517. if (!isConst || stack[top][0] == tokNumInt || stack[top][0] == tokNumUint)
  2518. return;
  2519. // Const, but not a number yet. Reduce to a number equal val.
  2520. if (SyntaxStack0[*ExprTypeSynPtr] == tokUnsigned)
  2521. stack[top][0] = tokNumUint;
  2522. else
  2523. stack[top][0] = tokNumInt;
  2524. stack[top][1] = val;
  2525. del(bottom, top - bottom);
  2526. }
  2527. word AllocLocal(unsigned size)
  2528. {
  2529. // Let's calculate variable's relative on-stack location
  2530. word oldOfs = CurFxnLocalOfs;
  2531. // Note: local vars are word-aligned on the stack
  2532. CurFxnLocalOfs = (word)((CurFxnLocalOfs - size) & ~(SizeOfWord - 1u));
  2533. if (CurFxnLocalOfs >= oldOfs ||
  2534. CurFxnLocalOfs != truncInt(CurFxnLocalOfs) ||
  2535. (unsigned int)CurFxnLocalOfs < (unsigned int) (-GenMaxLocalsSize()))
  2536. //error("AllocLocal(): Local variables take too much space\n");
  2537. {
  2538. //printf("a");
  2539. errorVarSize();
  2540. }
  2541. if (CurFxnMinLocalOfs > CurFxnLocalOfs)
  2542. CurFxnMinLocalOfs = CurFxnLocalOfs;
  2543. return CurFxnLocalOfs;
  2544. }
  2545. // DONE: sizeof(type)
  2546. // DONE: "sizeof expr"
  2547. // DONE: constant expressions
  2548. // DONE: collapse constant subexpressions into constants
  2549. word exprval(word* idx, word* ExprTypeSynPtr, word* ConstExpr)
  2550. {
  2551. word tok;
  2552. word s;
  2553. word RightExprTypeSynPtr;
  2554. word oldIdxRight;
  2555. word oldSpRight;
  2556. word constExpr[3];
  2557. if (*idx < 0)
  2558. //error("exprval(): idx < 0\n");
  2559. errorInternal(5);
  2560. tok = stack[*idx][0];
  2561. s = stack[*idx][1];
  2562. --*idx;
  2563. oldIdxRight = *idx;
  2564. oldSpRight = sp;
  2565. switch (tok)
  2566. {
  2567. // Constants
  2568. case tokNumInt:
  2569. // return the constant's type: int
  2570. *ExprTypeSynPtr = SymIntSynPtr;
  2571. *ConstExpr = 1;
  2572. break;
  2573. case tokNumUint:
  2574. // return the constant's type: unsigned int
  2575. *ExprTypeSynPtr = SymUintSynPtr;
  2576. *ConstExpr = 1;
  2577. break;
  2578. // Identifiers
  2579. case tokIdent:
  2580. {
  2581. // DONE: support __func__
  2582. char* ident = IdentTable + s;
  2583. word synPtr, type;
  2584. {
  2585. synPtr = FindSymbol(ident);
  2586. // "Rename" static vars in function scope
  2587. if (synPtr >= 0 && synPtr + 1 < SyntaxStackCnt && SyntaxStack0[synPtr + 1] == tokIdent)
  2588. {
  2589. s = stack[*idx + 1][1] = SyntaxStack1[++synPtr];
  2590. ident = IdentTable + s;
  2591. }
  2592. }
  2593. if (synPtr < 0)
  2594. {
  2595. if ((*idx + 2 >= sp) || stack[*idx + 2][0] != ')')
  2596. {
  2597. printf("Undeclared identifier ");
  2598. error(ident);
  2599. }
  2600. else
  2601. {
  2602. // silent this warning for now, since it seems to trigger false positives
  2603. //printf("Call to undeclared function ");
  2604. //warning(ident);
  2605. // Implicitly declare "extern int ident();"
  2606. PushSyntax2(tokIdent, s);
  2607. PushSyntax('(');
  2608. PushSyntax(')');
  2609. PushSyntax(tokInt);
  2610. synPtr = FindSymbol(ident);
  2611. }
  2612. }
  2613. // DONE: this declaration is actually a type cast
  2614. if (!strncmp(IdentTable + SyntaxStack1[synPtr], "(something", sizeof "(something)" - 1 - 1))
  2615. {
  2616. word castSize;
  2617. if (SyntaxStack0[++synPtr] == tokLocalOfs) // TBD!!! is this really needed???
  2618. synPtr++;
  2619. s = exprval(idx, ExprTypeSynPtr, ConstExpr);
  2620. // can't cast void or structure/union to anything (except void)
  2621. if (*ExprTypeSynPtr >= 0 &&
  2622. (SyntaxStack0[*ExprTypeSynPtr] == tokVoid ||
  2623. SyntaxStack0[*ExprTypeSynPtr] == tokStructPtr) &&
  2624. SyntaxStack0[synPtr] != tokVoid)
  2625. errorOpType();
  2626. // can't cast to function, array or structure/union
  2627. if (SyntaxStack0[synPtr] == '(' ||
  2628. SyntaxStack0[synPtr] == '[' ||
  2629. SyntaxStack0[synPtr] == tokStructPtr)
  2630. errorOpType();
  2631. // will try to propagate constants through casts
  2632. if (!*ConstExpr &&
  2633. (stack[oldIdxRight - (oldSpRight - sp)][0] == tokNumInt ||
  2634. stack[oldIdxRight - (oldSpRight - sp)][0] == tokNumUint))
  2635. {
  2636. s = stack[oldIdxRight - (oldSpRight - sp)][1];
  2637. *ConstExpr = 1;
  2638. }
  2639. castSize = GetDeclSize(synPtr, 1); // 0 for cast to void
  2640. // insertion of tokUChar, tokSChar and tokUnaryPlus transforms
  2641. // lvalues (values formed by dereferences) into rvalues
  2642. // (by hiding the dereferences), just as casts should do
  2643. switch (castSize)
  2644. {
  2645. case 1:
  2646. // cast to unsigned char
  2647. stack[oldIdxRight + 1 - (oldSpRight - sp)][0] = tokUChar;
  2648. s &= 0xFFu;
  2649. break;
  2650. case -1:
  2651. // cast to signed char
  2652. stack[oldIdxRight + 1 - (oldSpRight - sp)][0] = tokSChar;
  2653. if ((s &= 0xFFu) >= 0x80)
  2654. s -= 0x100;
  2655. break;
  2656. default:
  2657. if (castSize && castSize != SizeOfWord)
  2658. {
  2659. // cast not to void and not to word-sized type (int/unsigned/pointer/float)
  2660. if (castSize == 2)
  2661. {
  2662. // cast to unsigned short
  2663. stack[oldIdxRight + 1 - (oldSpRight - sp)][0] = tokUShort;
  2664. s &= 0xFFFFu;
  2665. }
  2666. else
  2667. {
  2668. // cast to signed short
  2669. stack[oldIdxRight + 1 - (oldSpRight - sp)][0] = tokShort;
  2670. if ((s &= 0xFFFFu) >= 0x8000)
  2671. s -= 0x10000;
  2672. }
  2673. }
  2674. else // fallthrough
  2675. {
  2676. // cast to void or word-sized type (int/unsigned/pointer/float)
  2677. if (stack[oldIdxRight - (oldSpRight - sp)][0] == tokUnaryStar)
  2678. // hide the dereference
  2679. stack[oldIdxRight + 1 - (oldSpRight - sp)][0] = tokUnaryPlus;
  2680. }
  2681. break;
  2682. }
  2683. if (*ConstExpr)
  2684. stack[oldIdxRight - (oldSpRight - sp)][1] = s;
  2685. *ExprTypeSynPtr = synPtr;
  2686. simplifyConstExpr(s, *ConstExpr, ExprTypeSynPtr, oldIdxRight + 1 - (oldSpRight - sp), *idx + 1);
  2687. if (!*ConstExpr && stack[oldIdxRight + 1 - (oldSpRight - sp)][0] == tokIdent)
  2688. // nothing to hide, remove the cast
  2689. del(oldIdxRight + 1 - (oldSpRight - sp), 1);
  2690. switch (SyntaxStack0[synPtr])
  2691. {
  2692. case tokChar:
  2693. case tokSChar:
  2694. case tokUChar:
  2695. case tokShort:
  2696. case tokUShort:
  2697. case tokInt:
  2698. case tokUnsigned:
  2699. break;
  2700. default:
  2701. // only numeric types can be const
  2702. *ConstExpr = 0;
  2703. break;
  2704. }
  2705. break;
  2706. }
  2707. // Finally, not __func__, not enum, not cast.
  2708. type = SymType(synPtr);
  2709. if (type == SymLocalVar || type == SymLocalArr)
  2710. {
  2711. // replace local variables/arrays with their local addresses
  2712. // (global variables/arrays' addresses are their names)
  2713. stack[*idx + 1][0] = tokLocalOfs;
  2714. stack[*idx + 1][1] = SyntaxStack1[synPtr + 1];
  2715. }
  2716. if (type == SymLocalVar || type == SymGlobalVar)
  2717. {
  2718. // add implicit dereferences for local/global variables
  2719. ins2(*idx + 2, tokUnaryStar, GetDeclSize(synPtr, 1));
  2720. }
  2721. // return the identifier's type
  2722. while (SyntaxStack0[synPtr] == tokIdent || SyntaxStack0[synPtr] == tokLocalOfs)
  2723. synPtr++;
  2724. *ExprTypeSynPtr = synPtr;
  2725. }
  2726. *ConstExpr = 0;
  2727. break;
  2728. // sizeof operator
  2729. case tokSizeof:
  2730. exprval(idx, ExprTypeSynPtr, ConstExpr);
  2731. s = GetDeclSize(*ExprTypeSynPtr, 0);
  2732. if (s == 0)
  2733. error("sizeof of incomplete type\n");
  2734. // replace sizeof with its numeric value
  2735. stack[oldIdxRight + 1 - (oldSpRight - sp)][0] = tokNumUint;
  2736. stack[oldIdxRight + 1 - (oldSpRight - sp)][1] = s;
  2737. // remove the sizeof's subexpression
  2738. del(*idx + 1, oldIdxRight - (oldSpRight - sp) - *idx);
  2739. *ExprTypeSynPtr = SymUintSynPtr;
  2740. *ConstExpr = 1;
  2741. break;
  2742. // Address unary operator
  2743. case tokUnaryAnd:
  2744. exprval(idx, ExprTypeSynPtr, ConstExpr);
  2745. if (*ExprTypeSynPtr >= 0 &&
  2746. (SyntaxStack0[*ExprTypeSynPtr] == '[' || SyntaxStack0[*ExprTypeSynPtr] == '('))
  2747. {
  2748. // convert an array into a pointer to the array,
  2749. // convert a function into a pointer to the function,
  2750. // remove the reference
  2751. del(oldIdxRight + 1 - (oldSpRight - sp), 1);
  2752. }
  2753. else if (*ExprTypeSynPtr >= 0 &&
  2754. stack[oldIdxRight - (oldSpRight - sp)][0] == tokUnaryStar)
  2755. {
  2756. // it's an lvalue (with implicit or explicit dereference),
  2757. // convert it into its address by
  2758. // collapsing/removing the reference and the dereference
  2759. del(oldIdxRight - (oldSpRight - sp), 2);
  2760. }
  2761. else
  2762. //error("exprval(): lvalue expected after '&'\n");
  2763. errorNotLvalue();
  2764. // we cannot insert another '*' into the type to make it a pointer
  2765. // to an array/function/etc, so make the index into the type negative
  2766. *ExprTypeSynPtr = -*ExprTypeSynPtr;
  2767. *ConstExpr = 0;
  2768. break;
  2769. // Indirection unary operator
  2770. case tokUnaryStar:
  2771. exprval(idx, ExprTypeSynPtr, ConstExpr);
  2772. if (*ExprTypeSynPtr < 0 || SyntaxStack0[*ExprTypeSynPtr] == '*')
  2773. {
  2774. // type is a pointer to something,
  2775. // transform it into that something
  2776. if (*ExprTypeSynPtr < 0)
  2777. *ExprTypeSynPtr = -*ExprTypeSynPtr;
  2778. else
  2779. ++*ExprTypeSynPtr;
  2780. nonVoidTypeCheck(*ExprTypeSynPtr);
  2781. if (SyntaxStack0[*ExprTypeSynPtr] == tokStructPtr && !GetDeclSize(*ExprTypeSynPtr, 0))
  2782. // incomplete structure/union type
  2783. errorOpType();
  2784. // remove the dereference if that something is an array or a function
  2785. if (SyntaxStack0[*ExprTypeSynPtr] == '[' ||
  2786. SyntaxStack0[*ExprTypeSynPtr] == '(')
  2787. del(oldIdxRight + 1 - (oldSpRight - sp), 1);
  2788. // else attach dereference size in bytes
  2789. else
  2790. stack[oldIdxRight + 1 - (oldSpRight - sp)][1] = GetDeclSize(*ExprTypeSynPtr, 1);
  2791. }
  2792. else if (SyntaxStack0[*ExprTypeSynPtr] == '[')
  2793. {
  2794. // type is an array,
  2795. // transform it into the array's first element
  2796. // (a subarray, if type is a multidimensional array)
  2797. (*ExprTypeSynPtr) += 3;
  2798. // remove the dereference if that element is an array
  2799. if (SyntaxStack0[*ExprTypeSynPtr] == '[')
  2800. del(oldIdxRight + 1 - (oldSpRight - sp), 1);
  2801. // else attach dereference size in bytes
  2802. else
  2803. stack[oldIdxRight + 1 - (oldSpRight - sp)][1] = GetDeclSize(*ExprTypeSynPtr, 1);
  2804. }
  2805. else
  2806. //error("exprval(): pointer/array expected after '*' / before '[]'\n");
  2807. errorOpType();
  2808. *ConstExpr = 0;
  2809. break;
  2810. // Additive binary operators
  2811. case '+':
  2812. case '-':
  2813. // WRONGISH: DONE: replace prefix ++/-- with +=1/-=1
  2814. // WRONG: DONE: replace postfix ++/-- with (+=1)-1/(-=1)+1
  2815. {
  2816. word ptrmask;
  2817. word oldIdxLeft, oldSpLeft;
  2818. word sl, sr;
  2819. word incSize;
  2820. sr = exprval(idx, &RightExprTypeSynPtr, &constExpr[1]);
  2821. oldIdxLeft = *idx;
  2822. oldSpLeft = sp;
  2823. sl = exprval(idx, ExprTypeSynPtr, &constExpr[0]);
  2824. // Decay arrays to pointers to their first elements
  2825. // and ensure that the pointers are suitable for pointer arithmetic
  2826. // (not pointers to functions, sizes of pointees are known and non-zero)
  2827. decayArray(&RightExprTypeSynPtr, 1);
  2828. decayArray(ExprTypeSynPtr, 1);
  2829. // Bar void and struct/union
  2830. scalarTypeCheck(RightExprTypeSynPtr);
  2831. scalarTypeCheck(*ExprTypeSynPtr);
  2832. ptrmask = isAnyPtr(RightExprTypeSynPtr) + isAnyPtr(*ExprTypeSynPtr) * 2;
  2833. // DONE: index/subscript scaling
  2834. if (ptrmask == 1 && tok == '+') // pointer in right-hand expression
  2835. {
  2836. incSize = GetDeclSize(derefAnyPtr(RightExprTypeSynPtr), 0);
  2837. if (constExpr[0]) // integer constant in left-hand expression
  2838. {
  2839. s = (word)((unsigned)sl * incSize);
  2840. stack[oldIdxLeft - (oldSpLeft - sp)][1] = s;
  2841. // optimize a little if possible
  2842. {
  2843. word i = oldIdxRight - (oldSpRight - sp);
  2844. // Skip any type cast markers
  2845. while (stack[i][0] == tokUnaryPlus || stack[i][0] == '+')
  2846. i--;
  2847. // See if the pointer is an integer constant or a local variable offset
  2848. // and if it is, adjust it here instead of generating code for
  2849. // addition/subtraction
  2850. if (stack[i][0] == tokNumInt || stack[i][0] == tokNumUint || stack[i][0] == tokLocalOfs)
  2851. {
  2852. s = (word)((unsigned)stack[i][1] + s);
  2853. stack[i][1] = s; // TBD!!! need extra truncation?
  2854. del(oldIdxLeft - (oldSpLeft - sp), 1);
  2855. del(oldIdxRight - (oldSpRight - sp) + 1, 1);
  2856. }
  2857. }
  2858. }
  2859. else if (incSize != 1)
  2860. {
  2861. ins2(oldIdxLeft + 1 - (oldSpLeft - sp), tokNumInt, incSize);
  2862. ins(oldIdxLeft + 1 - (oldSpLeft - sp), '*');
  2863. }
  2864. *ExprTypeSynPtr = RightExprTypeSynPtr;
  2865. }
  2866. else if (ptrmask == 2) // pointer in left-hand expression
  2867. {
  2868. incSize = GetDeclSize(derefAnyPtr(*ExprTypeSynPtr), 0);
  2869. if (constExpr[1]) // integer constant in right-hand expression
  2870. {
  2871. s = (word)((unsigned)sr * incSize);
  2872. stack[oldIdxRight - (oldSpRight - sp)][1] = s;
  2873. // optimize a little if possible
  2874. {
  2875. word i = oldIdxLeft - (oldSpLeft - sp);
  2876. // Skip any type cast markers
  2877. while (stack[i][0] == tokUnaryPlus || stack[i][0] == '+')
  2878. i--;
  2879. // See if the pointer is an integer constant or a local variable offset
  2880. // and if it is, adjust it here instead of generating code for
  2881. // addition/subtraction
  2882. if (stack[i][0] == tokNumInt || stack[i][0] == tokNumUint || stack[i][0] == tokLocalOfs)
  2883. {
  2884. if (tok == '-')
  2885. s = (word)~(s - 1u);
  2886. s = (word)((unsigned)stack[i][1] + s);
  2887. stack[i][1] = s; // TBD!!! need extra truncation?
  2888. del(oldIdxRight - (oldSpRight - sp), 2);
  2889. }
  2890. }
  2891. }
  2892. else if (incSize != 1)
  2893. {
  2894. ins2(oldIdxRight + 1 - (oldSpRight - sp), tokNumInt, incSize);
  2895. ins(oldIdxRight + 1 - (oldSpRight - sp), '*');
  2896. }
  2897. }
  2898. else if (ptrmask == 3 && tok == '-') // pointers in both expressions
  2899. {
  2900. incSize = GetDeclSize(derefAnyPtr(*ExprTypeSynPtr), 0);
  2901. // TBD!!! "ptr1-ptr2": better pointer type compatibility test needed, like compatCheck()?
  2902. if (incSize != GetDeclSize(derefAnyPtr(RightExprTypeSynPtr), 0))
  2903. //error("exprval(): incompatible pointers\n");
  2904. errorOpType();
  2905. if (incSize != 1)
  2906. {
  2907. ins2(oldIdxRight + 2 - (oldSpRight - sp), tokNumInt, incSize);
  2908. ins(oldIdxRight + 2 - (oldSpRight - sp), '/');
  2909. }
  2910. *ExprTypeSynPtr = SymIntSynPtr;
  2911. }
  2912. else if (ptrmask)
  2913. //error("exprval(): invalid combination of operands for '+' or '-'\n");
  2914. errorOpType();
  2915. // Promote the result from char to int (and from int to unsigned) if necessary
  2916. promoteType(ExprTypeSynPtr, &RightExprTypeSynPtr);
  2917. *ConstExpr = constExpr[0] && constExpr[1];
  2918. {
  2919. if (tok == '+')
  2920. s = (word)((unsigned)sl + sr);
  2921. else
  2922. s = (word)((unsigned)sl - sr);
  2923. }
  2924. simplifyConstExpr(s, *ConstExpr, ExprTypeSynPtr, oldIdxRight + 1 - (oldSpRight - sp), *idx + 1);
  2925. }
  2926. break;
  2927. // Prefix/postfix increment/decrement unary operators
  2928. case tokInc:
  2929. case tokDec:
  2930. case tokPostInc:
  2931. case tokPostDec:
  2932. {
  2933. word incSize = 1;
  2934. word inc = tok == tokInc || tok == tokPostInc;
  2935. word post = tok == tokPostInc || tok == tokPostDec;
  2936. word opSize;
  2937. exprval(idx, ExprTypeSynPtr, ConstExpr);
  2938. lvalueCheck(*ExprTypeSynPtr, oldIdxRight - (oldSpRight - sp));
  2939. // if it's a pointer, ensure that it's suitable for pointer arithmetic
  2940. // (not pointer to function, pointee size is known and non-zero)
  2941. decayArray(ExprTypeSynPtr, 1); // no actual decay here, just a type check
  2942. // Bar void and struct/union
  2943. scalarTypeCheck(*ExprTypeSynPtr);
  2944. // "remove" the lvalue dereference as we don't need
  2945. // to read the value while forgetting its location.
  2946. // We need to keep the lvalue location.
  2947. // Remember the operand size.
  2948. opSize = stack[oldIdxRight - (oldSpRight - sp)][1];
  2949. del(oldIdxRight - (oldSpRight - sp), 1);
  2950. if (isAnyPtr(*ExprTypeSynPtr))
  2951. incSize = GetDeclSize(derefAnyPtr(*ExprTypeSynPtr), 0);
  2952. if (incSize == 1)
  2953. {
  2954. // store the operand size in the operator
  2955. stack[oldIdxRight + 1 - (oldSpRight - sp)][1] = opSize;
  2956. }
  2957. else
  2958. {
  2959. // replace ++/-- with "postfix" +=/-= incSize when incSize != 1
  2960. stack[oldIdxRight + 1 - (oldSpRight - sp)][0] =
  2961. inc ? (post ? tokPostAdd : tokAssignAdd) :
  2962. (post ? tokPostSub : tokAssignSub);
  2963. // store the operand size in the operator
  2964. stack[oldIdxRight + 1 - (oldSpRight - sp)][1] = opSize;
  2965. ins2(oldIdxRight + 1 - (oldSpRight - sp), tokNumInt, incSize);
  2966. }
  2967. *ConstExpr = 0;
  2968. }
  2969. break;
  2970. // Simple assignment binary operator
  2971. case '=':
  2972. {
  2973. word oldIdxLeft, oldSpLeft;
  2974. word opSize;
  2975. word structs;
  2976. exprval(idx, &RightExprTypeSynPtr, &constExpr[1]);
  2977. oldIdxLeft = *idx;
  2978. oldSpLeft = sp;
  2979. exprval(idx, ExprTypeSynPtr, &constExpr[0]);
  2980. lvalueCheck(*ExprTypeSynPtr, oldIdxLeft - (oldSpLeft - sp));
  2981. nonVoidTypeCheck(RightExprTypeSynPtr);
  2982. nonVoidTypeCheck(*ExprTypeSynPtr);
  2983. structs = (*ExprTypeSynPtr >= 0 && SyntaxStack0[*ExprTypeSynPtr] == tokStructPtr) * 2 +
  2984. (RightExprTypeSynPtr >= 0 && SyntaxStack0[RightExprTypeSynPtr] == tokStructPtr);
  2985. if (structs)
  2986. {
  2987. word sz;
  2988. if (structs != 3 ||
  2989. SyntaxStack1[RightExprTypeSynPtr] != SyntaxStack1[*ExprTypeSynPtr])
  2990. errorOpType();
  2991. // TBD??? (a = b) should be an rvalue and so &(a = b) and (&(a = b))->c shouldn't be
  2992. // allowed, while (a = b).c should be allowed.
  2993. // transform "*psleft = *psright" into "*fxn(sizeof *psright, psright, psleft)"
  2994. /*
  2995. if (stack[oldIdxLeft - (oldSpLeft - sp)][0] != tokUnaryStar ||
  2996. stack[oldIdxRight - (oldSpRight - sp)][0] != tokUnaryStar)
  2997. errorInternal(18);
  2998. */
  2999. stack[oldIdxLeft - (oldSpLeft - sp)][0] = ','; // replace '*' with ','
  3000. stack[oldIdxRight - (oldSpRight - sp)][0] = ','; // replace '*' with ','
  3001. sz = GetDeclSize(RightExprTypeSynPtr, 0);
  3002. stack[oldIdxRight + 1 - (oldSpRight - sp)][0] = tokNumUint; // replace '=' with "sizeof *psright"
  3003. stack[oldIdxRight + 1 - (oldSpRight - sp)][1] = sz;
  3004. ins(oldIdxRight + 2 - (oldSpRight - sp), ',');
  3005. if (!StructCpyLabel)
  3006. StructCpyLabel = LabelCnt++;
  3007. ins2(oldIdxRight + 2 - (oldSpRight - sp), tokIdent, AddNumericIdent(StructCpyLabel));
  3008. ins2(oldIdxRight + 2 - (oldSpRight - sp), ')', SizeOfWord * 3);
  3009. ins2(oldIdxRight + 2 - (oldSpRight - sp), tokUnaryStar, 0); // use 0 deref size to drop meaningless dereferences
  3010. ins2(*idx + 1, '(', SizeOfWord * 3);
  3011. }
  3012. else
  3013. {
  3014. // "remove" the lvalue dereference as we don't need
  3015. // to read the value while forgetting its location.
  3016. // We need to keep the lvalue location.
  3017. // Remember the operand size.
  3018. opSize = stack[oldIdxLeft - (oldSpLeft - sp)][1];
  3019. // store the operand size in the operator
  3020. stack[oldIdxRight + 1 - (oldSpRight - sp)][1] = opSize;
  3021. del(oldIdxLeft - (oldSpLeft - sp), 1);
  3022. }
  3023. *ConstExpr = 0;
  3024. }
  3025. break;
  3026. // DONE: other assignment operators
  3027. // Arithmetic and bitwise unary operators
  3028. case '~':
  3029. case tokUnaryPlus:
  3030. case tokUnaryMinus:
  3031. s = exprval(idx, ExprTypeSynPtr, ConstExpr);
  3032. numericTypeCheck(*ExprTypeSynPtr);
  3033. promoteType(ExprTypeSynPtr, ExprTypeSynPtr);
  3034. switch (tok)
  3035. {
  3036. case '~':
  3037. s = ~s;
  3038. break;
  3039. case tokUnaryPlus:
  3040. break;
  3041. case tokUnaryMinus:
  3042. {
  3043. s = (word)~(s - 1u);
  3044. }
  3045. break;
  3046. }
  3047. simplifyConstExpr(s, *ConstExpr, ExprTypeSynPtr, oldIdxRight + 1 - (oldSpRight - sp), *idx + 1);
  3048. break;
  3049. // Arithmetic and bitwise binary operators
  3050. case '*':
  3051. case '/':
  3052. case '%':
  3053. case tokLShift:
  3054. case tokRShift:
  3055. case '&':
  3056. case '^':
  3057. case '|':
  3058. {
  3059. word sr, sl;
  3060. word Unsigned;
  3061. sr = exprval(idx, &RightExprTypeSynPtr, &constExpr[1]);
  3062. sl = exprval(idx, ExprTypeSynPtr, &constExpr[0]);
  3063. numericTypeCheck(RightExprTypeSynPtr);
  3064. numericTypeCheck(*ExprTypeSynPtr);
  3065. *ConstExpr = constExpr[0] && constExpr[1];
  3066. Unsigned = SyntaxStack0[*ExprTypeSynPtr] == tokUnsigned || SyntaxStack0[RightExprTypeSynPtr] == tokUnsigned;
  3067. {
  3068. switch (tok)
  3069. {
  3070. // DONE: check for division overflows
  3071. case '/':
  3072. case '%':
  3073. *ConstExpr &= divCheckAndCalc(tok, &sl, sr, Unsigned, constExpr);
  3074. if (Unsigned)
  3075. {
  3076. if (tok == '/')
  3077. stack[oldIdxRight + 1 - (oldSpRight - sp)][0] = tokUDiv;
  3078. else
  3079. stack[oldIdxRight + 1 - (oldSpRight - sp)][0] = tokUMod;
  3080. }
  3081. break;
  3082. case '*':
  3083. sl = (word)((unsigned)sl * sr);
  3084. break;
  3085. case tokLShift:
  3086. case tokRShift:
  3087. if (constExpr[1])
  3088. {
  3089. if (SyntaxStack0[RightExprTypeSynPtr] != tokUnsigned)
  3090. sr = truncInt(sr);
  3091. else
  3092. sr = (word)truncUint(sr);
  3093. shiftCountCheck(&sr, oldIdxRight - (oldSpRight - sp), RightExprTypeSynPtr);
  3094. }
  3095. if (*ConstExpr)
  3096. {
  3097. if (tok == tokLShift)
  3098. {
  3099. // left shift is the same for signed and unsigned ints
  3100. sl = (word)((unsigned)sl << sr);
  3101. }
  3102. else
  3103. {
  3104. if (SyntaxStack0[*ExprTypeSynPtr] == tokUnsigned)
  3105. {
  3106. // right shift for unsigned ints
  3107. sl = (word)(truncUint(sl) >> sr);
  3108. }
  3109. else if (sr)
  3110. {
  3111. // right shift for signed ints is arithmetic, sign-bit-preserving
  3112. // don't depend on the compiler's implementation, do it "manually"
  3113. sl = truncInt(sl);
  3114. sl = (word)((truncUint(sl) >> sr) |
  3115. ((sl < 0) * (~0u << (8 * SizeOfWord - sr))));
  3116. }
  3117. }
  3118. }
  3119. if (SyntaxStack0[*ExprTypeSynPtr] == tokUnsigned && tok == tokRShift)
  3120. stack[oldIdxRight + 1 - (oldSpRight - sp)][0] = tokURShift;
  3121. // ignore RightExprTypeSynPtr for the purpose of promotion/conversion of the result of <</>>
  3122. RightExprTypeSynPtr = SymIntSynPtr;
  3123. break;
  3124. case '&': sl &= sr; break;
  3125. case '^': sl ^= sr; break;
  3126. case '|': sl |= sr; break;
  3127. }
  3128. s = sl;
  3129. }
  3130. promoteType(ExprTypeSynPtr, &RightExprTypeSynPtr);
  3131. simplifyConstExpr(s, *ConstExpr, ExprTypeSynPtr, oldIdxRight + 1 - (oldSpRight - sp), *idx + 1);
  3132. }
  3133. break;
  3134. // Relational and equality binary operators
  3135. // DONE: add (sub)tokens for unsigned >, >=, <, <= for pointers
  3136. case '<':
  3137. case '>':
  3138. case tokLEQ:
  3139. case tokGEQ:
  3140. case tokEQ:
  3141. case tokNEQ:
  3142. {
  3143. word ptrmask;
  3144. word sr, sl;
  3145. sr = exprval(idx, &RightExprTypeSynPtr, &constExpr[1]);
  3146. sl = exprval(idx, ExprTypeSynPtr, &constExpr[0]);
  3147. // Bar void and struct/union
  3148. scalarTypeCheck(RightExprTypeSynPtr);
  3149. scalarTypeCheck(*ExprTypeSynPtr);
  3150. ptrmask = isAnyPtr(RightExprTypeSynPtr) + isAnyPtr(*ExprTypeSynPtr) * 2;
  3151. // TBD??? stricter type checks???
  3152. if (tok != tokEQ && tok != tokNEQ)
  3153. {
  3154. // Disallow >, <, >=, <= between a pointer and a number
  3155. if (ptrmask == 1 || ptrmask == 2)
  3156. //error("exprval(): Invalid/unsupported combination of compared operands\n");
  3157. errorOpType();
  3158. // Disallow >, <, >=, <= with pointers to functions
  3159. if (((ptrmask & 1) && SyntaxStack0[derefAnyPtr(RightExprTypeSynPtr)] == '(') ||
  3160. ((ptrmask & 2) && SyntaxStack0[derefAnyPtr(*ExprTypeSynPtr)] == '('))
  3161. errorOpType();
  3162. }
  3163. else
  3164. {
  3165. // Disallow == and != between a pointer and a number other than constant 0 (AKA NULL)
  3166. if ((ptrmask == 1 && !(constExpr[0] && !truncInt(sl))) ||
  3167. (ptrmask == 2 && !(constExpr[1] && !truncInt(sr))))
  3168. errorOpType();
  3169. }
  3170. *ConstExpr = constExpr[0] && constExpr[1];
  3171. {
  3172. word Unsigned = isUint(*ExprTypeSynPtr) || isUint(RightExprTypeSynPtr);
  3173. if (*ConstExpr)
  3174. {
  3175. if (!Unsigned)
  3176. {
  3177. sl = truncInt(sl);
  3178. sr = truncInt(sr);
  3179. switch (tok)
  3180. {
  3181. case '<': sl = sl < sr; break;
  3182. case '>': sl = sl > sr; break;
  3183. case tokLEQ: sl = sl <= sr; break;
  3184. case tokGEQ: sl = sl >= sr; break;
  3185. case tokEQ: sl = sl == sr; break;
  3186. case tokNEQ: sl = sl != sr; break;
  3187. }
  3188. }
  3189. else
  3190. {
  3191. sl = (word)truncUint(sl);
  3192. sr = (word)truncUint(sr);
  3193. switch (tok)
  3194. {
  3195. case '<': sl = (unsigned)sl < (unsigned)sr; break;
  3196. case '>': sl = (unsigned)sl > (unsigned)sr; break;
  3197. case tokLEQ: sl = (unsigned)sl <= (unsigned)sr; break;
  3198. case tokGEQ: sl = (unsigned)sl >= (unsigned)sr; break;
  3199. case tokEQ: sl = sl == sr; break;
  3200. case tokNEQ: sl = sl != sr; break;
  3201. }
  3202. }
  3203. }
  3204. if (ptrmask || Unsigned)
  3205. {
  3206. // Pointer comparison should be unsigned
  3207. word t = tok;
  3208. switch (tok)
  3209. {
  3210. case '<': t = tokULess; break;
  3211. case '>': t = tokUGreater; break;
  3212. case tokLEQ: t = tokULEQ; break;
  3213. case tokGEQ: t = tokUGEQ; break;
  3214. }
  3215. stack[oldIdxRight + 1 - (oldSpRight - sp)][0] = t;
  3216. }
  3217. }
  3218. s = sl;
  3219. *ExprTypeSynPtr = SymIntSynPtr;
  3220. simplifyConstExpr(s, *ConstExpr, ExprTypeSynPtr, oldIdxRight + 1 - (oldSpRight - sp), *idx + 1);
  3221. }
  3222. break;
  3223. // implicit pseudo-conversion to _Bool of operands of && and ||
  3224. case tok_Bool:
  3225. s = exprval(idx, ExprTypeSynPtr, ConstExpr);
  3226. // Bar void and struct/union
  3227. scalarTypeCheck(*ExprTypeSynPtr);
  3228. {
  3229. s = truncInt(s) != 0;
  3230. }
  3231. *ExprTypeSynPtr = SymIntSynPtr;
  3232. simplifyConstExpr(s, *ConstExpr, ExprTypeSynPtr, oldIdxRight + 1 - (oldSpRight - sp), *idx + 1);
  3233. break;
  3234. // Logical binary operators
  3235. case tokLogAnd: // DONE: short-circuit
  3236. case tokLogOr: // DONE: short-circuit
  3237. {
  3238. word sr, sl;
  3239. // DONE: think of pushing a special short-circuit (jump-to) token
  3240. // to skip the rhs operand evaluation in && and ||
  3241. // DONE: add implicit "casts to _Bool" of && and || operands,
  3242. // do the same for control statements of if() while() and for(;;).
  3243. word sc = LabelCnt++;
  3244. // tag the logical operator as a numbered short-circuit jump target
  3245. stack[*idx + 1][1] = sc;
  3246. // insert "!= 0" for right-hand operand
  3247. switch (stack[*idx][0])
  3248. {
  3249. case '<':
  3250. case tokULess:
  3251. case '>':
  3252. case tokUGreater:
  3253. case tokLEQ:
  3254. case tokULEQ:
  3255. case tokGEQ:
  3256. case tokUGEQ:
  3257. case tokEQ:
  3258. case tokNEQ:
  3259. break;
  3260. default:
  3261. ins(++*idx, tok_Bool);
  3262. break;
  3263. }
  3264. sr = exprval(idx, &RightExprTypeSynPtr, &constExpr[1]);
  3265. // insert a reference to the short-circuit jump target
  3266. if (tok == tokLogAnd)
  3267. ins2(++*idx, tokShortCirc, sc);
  3268. else
  3269. ins2(++*idx, tokShortCirc, -sc);
  3270. // insert "!= 0" for left-hand operand
  3271. switch (stack[*idx - 1][0])
  3272. {
  3273. case '<':
  3274. case tokULess:
  3275. case '>':
  3276. case tokUGreater:
  3277. case tokLEQ:
  3278. case tokULEQ:
  3279. case tokGEQ:
  3280. case tokUGEQ:
  3281. case tokEQ:
  3282. case tokNEQ:
  3283. --*idx;
  3284. break;
  3285. default:
  3286. ins(*idx, tok_Bool);
  3287. break;
  3288. }
  3289. sl = exprval(idx, ExprTypeSynPtr, &constExpr[0]);
  3290. if (tok == tokLogAnd)
  3291. s = sl && sr;
  3292. else
  3293. s = sl || sr;
  3294. *ExprTypeSynPtr = SymIntSynPtr;
  3295. *ConstExpr = constExpr[0] && constExpr[1];
  3296. if (constExpr[0])
  3297. {
  3298. if (tok == tokLogAnd)
  3299. {
  3300. if (!sl)
  3301. *ConstExpr = 1, s = 0;
  3302. // TBD??? else can drop LHS expression
  3303. }
  3304. else
  3305. {
  3306. if (sl)
  3307. *ConstExpr = s = 1;
  3308. // TBD??? else can drop LHS expression
  3309. }
  3310. }
  3311. simplifyConstExpr(s, *ConstExpr, ExprTypeSynPtr, oldIdxRight + 1 - (oldSpRight - sp), *idx + 1);
  3312. }
  3313. break;
  3314. // Function call
  3315. case ')':
  3316. {
  3317. word tmpSynPtr, c;
  3318. word minParams, maxParams;
  3319. word firstParamSynPtr;
  3320. word oldIdx, oldSp;
  3321. exprval(idx, ExprTypeSynPtr, ConstExpr);
  3322. if (!GetFxnInfo(*ExprTypeSynPtr, &minParams, &maxParams, ExprTypeSynPtr, &firstParamSynPtr))
  3323. //error("exprval(): function or function pointer expected\n");
  3324. errorOpType();
  3325. // DONE: validate the number of function arguments
  3326. // DONE: warnings on int<->pointer substitution in params/args
  3327. // evaluate function arguments
  3328. c = 0;
  3329. while (stack[*idx][0] != '(')
  3330. {
  3331. word ptrmask;
  3332. // add a comma after the first (last to be pushed) argument,
  3333. // so all arguments can be pushed whenever a comma is encountered
  3334. if (!c)
  3335. ins(*idx + 1, ',');
  3336. oldIdx = *idx;
  3337. oldSp = sp;
  3338. (void)oldIdx;
  3339. (void)oldSp;
  3340. exprval(idx, &tmpSynPtr, ConstExpr);
  3341. //error("exprval(): function arguments cannot be of type 'void'\n");
  3342. if (c >= maxParams)
  3343. error("Too many function arguments\n");
  3344. // Find the type of the formal parameter in the function declaration
  3345. if (c < minParams)
  3346. {
  3347. word t;
  3348. while ((t = SyntaxStack0[firstParamSynPtr]) != tokIdent)
  3349. {
  3350. if (t == '(')
  3351. {
  3352. // skip parameters in parameters
  3353. word c = 1;
  3354. while (c)
  3355. {
  3356. t = SyntaxStack0[++firstParamSynPtr];
  3357. c += (t == '(') - (t == ')');
  3358. }
  3359. }
  3360. firstParamSynPtr++;
  3361. }
  3362. firstParamSynPtr++;
  3363. }
  3364. else
  3365. {
  3366. firstParamSynPtr = SymVoidSynPtr;
  3367. }
  3368. ptrmask = isAnyPtr(firstParamSynPtr) * 2 + isAnyPtr(tmpSynPtr);
  3369. (void)ptrmask;
  3370. // Bar void and struct/union
  3371. scalarTypeCheck(tmpSynPtr);
  3372. // if there's a formal parameter for this argument, check the types
  3373. if (c < minParams)
  3374. {
  3375. }
  3376. c++;
  3377. if (stack[*idx][0] == ',')
  3378. --*idx;
  3379. }
  3380. --*idx;
  3381. if (c < minParams)
  3382. error("Too few function arguments\n");
  3383. // store the cumulative argument size in the function call operators
  3384. {
  3385. word i = oldIdxRight + 1 - (oldSpRight - sp);
  3386. stack[1 + *idx][1] = stack[i][1] = c * SizeOfWord;
  3387. }
  3388. *ConstExpr = 0;
  3389. }
  3390. break;
  3391. // Binary comma operator
  3392. case tokComma:
  3393. {
  3394. word oldIdxLeft, oldSpLeft;
  3395. word retStruct = 0;
  3396. s = exprval(idx, &RightExprTypeSynPtr, &constExpr[1]);
  3397. oldIdxLeft = *idx;
  3398. oldSpLeft = sp;
  3399. // Signify uselessness of the result of the left operand's value
  3400. ins(*idx + 1, tokVoid);
  3401. exprval(idx, ExprTypeSynPtr, &constExpr[0]);
  3402. *ConstExpr = constExpr[0] && constExpr[1];
  3403. *ExprTypeSynPtr = RightExprTypeSynPtr;
  3404. retStruct = RightExprTypeSynPtr >= 0 && SyntaxStack0[RightExprTypeSynPtr] == tokStructPtr;
  3405. if (*ConstExpr)
  3406. {
  3407. // both subexprs are const, remove both and comma
  3408. simplifyConstExpr(s, *ConstExpr, ExprTypeSynPtr, oldIdxRight + 1 - (oldSpRight - sp), *idx + 1);
  3409. }
  3410. else if (constExpr[0])
  3411. {
  3412. // only left subexpr is const, remove it
  3413. del(*idx + 1, oldIdxLeft - (oldSpLeft - sp) - *idx);
  3414. if (!retStruct)
  3415. // Ensure non-lvalue-ness of the result by changing comma to unary plus
  3416. // and thus hiding dereference, if any
  3417. stack[oldIdxRight + 1 - (oldSpRight - sp)][0] = tokUnaryPlus;
  3418. else
  3419. // However, (something, struct).member should still be allowed,
  3420. // so, comma needs to produce lvalue
  3421. del(oldIdxRight + 1 - (oldSpRight - sp), 1);
  3422. }
  3423. else if (retStruct)
  3424. {
  3425. // However, (something, struct).member should still be allowed,
  3426. // so, comma needs to produce lvalue. Swap comma and structure dereference.
  3427. word i = oldIdxRight + 1 - (oldSpRight - sp);
  3428. stack[i][0] = tokUnaryStar;
  3429. stack[i][1] = stack[i - 1][1];
  3430. stack[i - 1][0] = tokComma;
  3431. }
  3432. }
  3433. break;
  3434. // Compound assignment operators
  3435. case tokAssignMul: case tokAssignDiv: case tokAssignMod:
  3436. case tokAssignAdd: case tokAssignSub:
  3437. case tokAssignLSh: case tokAssignRSh:
  3438. case tokAssignAnd: case tokAssignXor: case tokAssignOr:
  3439. {
  3440. word ptrmask;
  3441. word oldIdxLeft, oldSpLeft;
  3442. word incSize;
  3443. word opSize;
  3444. word Unsigned;
  3445. word sr = exprval(idx, &RightExprTypeSynPtr, &constExpr[1]);
  3446. oldIdxLeft = *idx;
  3447. oldSpLeft = sp;
  3448. exprval(idx, ExprTypeSynPtr, &constExpr[0]);
  3449. lvalueCheck(*ExprTypeSynPtr, oldIdxLeft - (oldSpLeft - sp));
  3450. // if it's a pointer, ensure that it's suitable for pointer arithmetic
  3451. // (not pointer to function, pointee size is known and non-zero)
  3452. decayArray(ExprTypeSynPtr, 1); // no actual decay here, just a type check
  3453. // Bar void and struct/union
  3454. scalarTypeCheck(RightExprTypeSynPtr);
  3455. scalarTypeCheck(*ExprTypeSynPtr);
  3456. // "remove" the lvalue dereference as we don't need
  3457. // to read the value while forgetting its location.
  3458. // We need to keep the lvalue location.
  3459. // Remember the operand size.
  3460. opSize = stack[oldIdxLeft - (oldSpLeft - sp)][1];
  3461. // store the operand size in the operator
  3462. stack[oldIdxRight + 1 - (oldSpRight - sp)][1] = opSize;
  3463. del(oldIdxLeft - (oldSpLeft - sp), 1);
  3464. ptrmask = isAnyPtr(*ExprTypeSynPtr) * 2 + isAnyPtr(RightExprTypeSynPtr);
  3465. Unsigned = isUint(*ExprTypeSynPtr) * 2 + isUint(RightExprTypeSynPtr);
  3466. if (tok != tokAssignAdd && tok != tokAssignSub)
  3467. {
  3468. if (ptrmask)
  3469. //error("exprval(): invalid combination of operands for %s\n", GetTokenName(tok));
  3470. errorOpType();
  3471. }
  3472. else
  3473. {
  3474. // No pointer to the right of += and -=
  3475. if (ptrmask & 1)
  3476. //error("exprval(): invalid combination of operands for %s\n", GetTokenName(tok));
  3477. errorOpType();
  3478. }
  3479. if (tok == tokAssignLSh || tok == tokAssignRSh)
  3480. {
  3481. if (constExpr[1])
  3482. {
  3483. if (Unsigned & 1)
  3484. sr = (word)truncUint(sr);
  3485. else
  3486. sr = truncInt(sr);
  3487. shiftCountCheck(&sr, oldIdxRight - (oldSpRight - sp), RightExprTypeSynPtr);
  3488. }
  3489. }
  3490. if (tok == tokAssignDiv || tok == tokAssignMod)
  3491. {
  3492. word t, sl = 0;
  3493. if (tok == tokAssignDiv)
  3494. t = '/';
  3495. else
  3496. t = '%';
  3497. divCheckAndCalc(t, &sl, sr, 1, constExpr);
  3498. }
  3499. // TBD??? replace +=/-= with prefix ++/-- if incSize == 1
  3500. if (ptrmask == 2) // left-hand expression
  3501. {
  3502. incSize = GetDeclSize(derefAnyPtr(*ExprTypeSynPtr), 0);
  3503. if (constExpr[1])
  3504. {
  3505. word t = (word)(stack[oldIdxRight - (oldSpRight - sp)][1] * (unsigned)incSize);
  3506. stack[oldIdxRight - (oldSpRight - sp)][1] = t;
  3507. }
  3508. else if (incSize != 1)
  3509. {
  3510. ins2(oldIdxRight + 1 - (oldSpRight - sp), tokNumInt, incSize);
  3511. ins(oldIdxRight + 1 - (oldSpRight - sp), '*');
  3512. }
  3513. }
  3514. else if (Unsigned)
  3515. {
  3516. word t = tok;
  3517. switch (tok)
  3518. {
  3519. case tokAssignDiv: t = tokAssignUDiv; break;
  3520. case tokAssignMod: t = tokAssignUMod; break;
  3521. case tokAssignRSh:
  3522. if (Unsigned & 2)
  3523. t = tokAssignURSh;
  3524. break;
  3525. }
  3526. stack[oldIdxRight + 1 - (oldSpRight - sp)][0] = t;
  3527. }
  3528. *ConstExpr = 0;
  3529. }
  3530. break;
  3531. // Ternary/conditional operator
  3532. case '?':
  3533. {
  3534. word oldIdxLeft, oldSpLeft;
  3535. word oldIdxCond, oldSpCond;
  3536. word sr, sl, smid;
  3537. word condTypeSynPtr;
  3538. word sc = (LabelCnt += 2) - 2;
  3539. word structs;
  3540. // "exprL ? exprMID : exprR" appears on the stack as
  3541. // "exprL exprR exprMID ?"
  3542. // label at the end of ?:
  3543. stack[*idx + 1][0] = tokLogAnd; // piggyback on && for CG (ugly, but simple)
  3544. stack[*idx + 1][1] = sc + 1;
  3545. smid = exprval(idx, ExprTypeSynPtr, &constExpr[1]);
  3546. oldIdxLeft = *idx;
  3547. oldSpLeft = sp;
  3548. sr = exprval(idx, &RightExprTypeSynPtr, &constExpr[2]);
  3549. decayArray(&RightExprTypeSynPtr, 0);
  3550. decayArray(ExprTypeSynPtr, 0);
  3551. promoteType(&RightExprTypeSynPtr, ExprTypeSynPtr);
  3552. promoteType(ExprTypeSynPtr, &RightExprTypeSynPtr);
  3553. structs = (*ExprTypeSynPtr >= 0 && SyntaxStack0[*ExprTypeSynPtr] == tokStructPtr) * 2 +
  3554. (RightExprTypeSynPtr >= 0 && SyntaxStack0[RightExprTypeSynPtr] == tokStructPtr);
  3555. // TBD??? move struct/union-related checks into compatChecks()
  3556. if (structs)
  3557. {
  3558. if (structs != 3 ||
  3559. SyntaxStack1[RightExprTypeSynPtr] != SyntaxStack1[*ExprTypeSynPtr])
  3560. errorOpType();
  3561. // transform "cond ? a : b" into "*(cond ? &a : &b)"
  3562. /*
  3563. if (stack[oldIdxLeft - (oldSpLeft - sp)][0] != tokUnaryStar ||
  3564. stack[oldIdxRight - (oldSpRight - sp)][0] != tokUnaryStar)
  3565. errorInternal(19);
  3566. */
  3567. del(oldIdxLeft - (oldSpLeft - sp), 1); // delete '*'
  3568. del(oldIdxRight - (oldSpRight - sp), 1); // delete '*'
  3569. oldSpLeft--;
  3570. // '*' will be inserted at the end
  3571. }
  3572. else
  3573. {
  3574. compatCheck(ExprTypeSynPtr,
  3575. RightExprTypeSynPtr,
  3576. &constExpr[1],
  3577. oldIdxRight - (oldSpRight - sp),
  3578. oldIdxLeft - (oldSpLeft - sp));
  3579. }
  3580. // label at the start of exprMID
  3581. ins2(oldIdxLeft + 1 - (oldSpLeft - sp), tokLogAnd, sc); // piggyback on && for CG (ugly, but simple)
  3582. // jump from the end of exprR over exprMID to the end of ?:
  3583. ins2(oldIdxLeft - (oldSpLeft - sp), tokGoto, sc + 1);
  3584. // jump to exprMID if exprL is non-zero
  3585. ins2(*idx + 1, tokShortCirc, -sc);
  3586. oldIdxCond = *idx;
  3587. oldSpCond = sp;
  3588. sl = exprval(idx, &condTypeSynPtr, &constExpr[0]);
  3589. // Bar void and struct/union
  3590. scalarTypeCheck(condTypeSynPtr);
  3591. *ConstExpr = s = 0;
  3592. if (constExpr[0])
  3593. {
  3594. word c1 = 0, c2 = 0;
  3595. // Stack now: exprL tokShortCirc exprR tokGoto tokLogAnd exprMID ?/tokLogAnd
  3596. if (
  3597. (truncUint(sl) != 0))
  3598. {
  3599. if (constExpr[1])
  3600. {
  3601. *ConstExpr = 1, s = smid;
  3602. }
  3603. else
  3604. {
  3605. // Drop exprL and exprR subexpressions
  3606. c1 = oldIdxLeft - (oldSpLeft - sp) - *idx; // includes tokShortCirc, tokGoto, tokLogAnd
  3607. c2 = 1; // include '?'/tokLogAnd
  3608. }
  3609. }
  3610. else
  3611. {
  3612. if (constExpr[2])
  3613. {
  3614. *ConstExpr = 1, s = sr;
  3615. }
  3616. else
  3617. {
  3618. // Drop exprL and exprMID subexpressions
  3619. c1 = oldIdxCond - (oldSpCond - sp) - *idx + 1; // includes tokShortCirc
  3620. c2 = (oldIdxRight - (oldSpRight - sp)) -
  3621. (oldIdxLeft - (oldSpLeft - sp)) + 3; // includes tokGoto, tokLogAnd, '?'/tokLogAnd
  3622. }
  3623. }
  3624. if (c1)
  3625. {
  3626. word pos = oldIdxRight - (oldSpRight - sp) + 2 - c2;
  3627. if (!structs && stack[pos - 1][0] == tokUnaryStar)
  3628. stack[pos++][0] = tokUnaryPlus, c2--; // ensure non-lvalue-ness by hiding the dereference
  3629. del(pos, c2);
  3630. del(*idx + 1, c1);
  3631. }
  3632. }
  3633. // finish transforming "cond ? a : b" into "*(cond ? &a : &b)", insert '*'
  3634. if (structs)
  3635. ins2(oldIdxRight + 2 - (oldSpRight - sp), tokUnaryStar, 0); // use 0 deref size to drop meaningless dereferences
  3636. simplifyConstExpr(s, *ConstExpr, ExprTypeSynPtr, oldIdxRight + 1 - (oldSpRight - sp), *idx + 1);
  3637. }
  3638. break;
  3639. // Postfix indirect structure/union member selection operator
  3640. case tokArrow:
  3641. {
  3642. word member, i = 0, j = 0, c = 1, ofs = 0;
  3643. stack[*idx + 1][0] = '+'; // replace -> with +
  3644. member = stack[*idx][1]; // keep the member name, it will be replaced with member offset
  3645. stack[*idx][0] = tokNumInt;
  3646. --*idx;
  3647. exprval(idx, ExprTypeSynPtr, ConstExpr);
  3648. if (!isAnyPtr(*ExprTypeSynPtr) ||
  3649. SyntaxStack0[i = derefAnyPtr(*ExprTypeSynPtr)] != tokStructPtr)
  3650. error("Pointer to or structure or union expected\n");
  3651. i = SyntaxStack1[i];
  3652. if (i + 2 > SyntaxStackCnt ||
  3653. (SyntaxStack0[i] != tokStruct && SyntaxStack0[i] != tokUnion) ||
  3654. SyntaxStack0[i + 1] != tokTag)
  3655. errorInternal(20);
  3656. if (!GetDeclSize(i, 0))
  3657. // incomplete structure/union type
  3658. errorOpType();
  3659. i += 5; // step inside the {} body of the struct/union
  3660. while (c)
  3661. {
  3662. word t = SyntaxStack0[i];
  3663. c += (t == '(') - (t == ')') + (t == '{') - (t == '}');
  3664. if (c == 1 &&
  3665. t == tokMemberIdent && SyntaxStack1[i] == member &&
  3666. SyntaxStack0[i + 1] == tokLocalOfs)
  3667. {
  3668. j = i;
  3669. ofs = SyntaxStack1[i + 1];
  3670. break;
  3671. }
  3672. i++;
  3673. }
  3674. if (!j)
  3675. {
  3676. printf("Undefined structure or union member ");
  3677. error(IdentTable + member);
  3678. }
  3679. j += 2;
  3680. // we cannot insert another '*' into the type to make it a pointer,
  3681. // so make the index into the type negative
  3682. *ExprTypeSynPtr = -j; // type: pointer to member's type
  3683. stack[oldIdxRight - (oldSpRight - sp)][1] = ofs; // member offset within structure/union
  3684. // optimize a little, if possible
  3685. {
  3686. word i = oldIdxRight - (oldSpRight - sp) - 1;
  3687. // Skip any type cast markers
  3688. while (stack[i][0] == tokUnaryPlus)
  3689. i--;
  3690. // See if the pointer is an integer constant or a local variable offset
  3691. // and if it is, adjust it here instead of generating code for
  3692. // addition/subtraction
  3693. if (stack[i][0] == tokNumInt || stack[i][0] == tokNumUint || stack[i][0] == tokLocalOfs)
  3694. {
  3695. stack[i][1] = (word)((unsigned)stack[i][1] + ofs); // TBD!!! need extra truncation?
  3696. del(oldIdxRight - (oldSpRight - sp), 2);
  3697. }
  3698. }
  3699. *ConstExpr = 0;
  3700. }
  3701. break;
  3702. default:
  3703. //error("exprval(): Unexpected token %s\n", GetTokenName(tok));
  3704. errorInternal(21);
  3705. }
  3706. return s;
  3707. }
  3708. word ParseExpr(word tok, word* GotUnary, word* ExprTypeSynPtr, word* ConstExpr, word* ConstVal, word option, word option2)
  3709. {
  3710. word identFirst = tok == tokIdent;
  3711. *ConstVal = *ConstExpr = 0;
  3712. *ExprTypeSynPtr = SymVoidSynPtr;
  3713. if (!ExprLevel++)
  3714. {
  3715. opsp = sp = 0;
  3716. }
  3717. if (option == '=')
  3718. push2(tokIdent, option2);
  3719. tok = expr(tok, GotUnary, option == ',' || option == '=');
  3720. if (tok == tokEof || strchr(",;:)]}", tok) == NULL)
  3721. //error("ParseExpr(): Unexpected token %s\n", GetTokenName(tok));
  3722. errorUnexpectedToken(tok);
  3723. if (option == '=')
  3724. {
  3725. push('=');
  3726. }
  3727. else if (option == tokGotoLabel && identFirst && tok == ':' && *GotUnary && sp == 1 && stack[sp - 1][0] == tokIdent)
  3728. {
  3729. // This is a label.
  3730. ExprLevel--;
  3731. return tokGotoLabel;
  3732. }
  3733. if (*GotUnary)
  3734. {
  3735. word j;
  3736. // Do this twice so we can see the stack before
  3737. // and after manipulations
  3738. for (j = 0; j < 2; j++)
  3739. {
  3740. if (doAnnotations)
  3741. {
  3742. word i;
  3743. GenStartCommentLine();
  3744. if (j) printf2("Expanded");
  3745. else printf2("RPN'ized");
  3746. printf2(" expression: \"");
  3747. for (i = 0; i < sp; i++)
  3748. {
  3749. word tok = stack[i][0];
  3750. switch (tok)
  3751. {
  3752. case tokNumInt:
  3753. printd2(truncInt(stack[i][1]));
  3754. break;
  3755. case tokNumUint:
  3756. printd2(truncUint(stack[i][1]));
  3757. break;
  3758. case tokIdent:
  3759. {
  3760. char* p = IdentTable + stack[i][1];
  3761. if (isdigit(*p))
  3762. printf2("L");
  3763. printf2(p);
  3764. }
  3765. break;
  3766. case tokShortCirc:
  3767. if (stack[i][1] >= 0)
  3768. {
  3769. printf2("[sh&&->");
  3770. printd2(stack[i][1]);
  3771. printf2("]");
  3772. }
  3773. else
  3774. {
  3775. printf2("[sh||->");
  3776. printd2(-stack[i][1]);
  3777. printf2("]");
  3778. }
  3779. break;
  3780. case tokLocalOfs:
  3781. printf2("(@");
  3782. printd2(truncInt(stack[i][1]));
  3783. printf2(")");
  3784. break;
  3785. case tokUnaryStar:
  3786. if (j)
  3787. {
  3788. printf2("*(");
  3789. printd2(stack[i][1]);
  3790. printf2(")");
  3791. }
  3792. else printf2("*u");
  3793. break;
  3794. case '(': case ',':
  3795. if (!j)
  3796. {
  3797. char* ctmp = " ";
  3798. ctmp[0] = tok;
  3799. printf2(ctmp);
  3800. }
  3801. // else printf2("\b");
  3802. break;
  3803. case ')':
  3804. if (j) printf2("(");
  3805. char* ctmp = " ";
  3806. ctmp[0] = tok;
  3807. printf2(ctmp);
  3808. if (j) printd2(stack[i][1]);
  3809. break;
  3810. default:
  3811. printf2(GetTokenName(tok));
  3812. if (j)
  3813. {
  3814. switch (tok)
  3815. {
  3816. case tokLogOr: case tokLogAnd:
  3817. printf2("[");
  3818. printd2(stack[i][1]);
  3819. printf2("]");
  3820. break;
  3821. case '=':
  3822. case tokInc: case tokDec:
  3823. case tokPostInc: case tokPostDec:
  3824. case tokAssignAdd: case tokAssignSub:
  3825. case tokPostAdd: case tokPostSub:
  3826. case tokAssignMul:
  3827. case tokAssignDiv: case tokAssignMod:
  3828. case tokAssignUDiv: case tokAssignUMod:
  3829. case tokAssignLSh: case tokAssignRSh: case tokAssignURSh:
  3830. case tokAssignAnd: case tokAssignXor: case tokAssignOr:
  3831. printf2("(");
  3832. printd2(stack[i][1]);
  3833. printf2(")");
  3834. break;
  3835. }
  3836. }
  3837. break;
  3838. }
  3839. printf2(" ");
  3840. }
  3841. printf2("\"\n");
  3842. }
  3843. if (!j)
  3844. {
  3845. word idx = sp - 1;
  3846. *ConstVal = exprval(&idx, ExprTypeSynPtr, ConstExpr);
  3847. // remove the unneeded unary +'s that have served their cast-substitute purpose
  3848. // also remove dereferences of size 0 (dereferences of pointers to structures)
  3849. for (idx = sp - 1; idx >= 0; idx--)
  3850. if (stack[idx][0] == tokUnaryPlus ||
  3851. (stack[idx][0] == tokUnaryStar && !stack[idx][1]))
  3852. del(idx, 1);
  3853. }
  3854. else if (*ConstExpr)
  3855. {
  3856. if (doAnnotations)
  3857. {
  3858. GenStartCommentLine();
  3859. switch (SyntaxStack0[*ExprTypeSynPtr])
  3860. {
  3861. case tokChar:
  3862. case tokSChar:
  3863. case tokUChar:
  3864. case tokShort:
  3865. case tokUShort:
  3866. case tokInt:
  3867. printf2("Expression value: ");
  3868. printd2(truncInt(*ConstVal));
  3869. printf2("\n");
  3870. break;
  3871. default:
  3872. case tokUnsigned:
  3873. printf2("Expression value: ");
  3874. printd2(truncUint(*ConstVal));
  3875. printf2("\n");
  3876. break;
  3877. }
  3878. }
  3879. }
  3880. }
  3881. }
  3882. ExprLevel--;
  3883. return tok;
  3884. }
  3885. // smc.c code
  3886. // Equivalent to puts() but outputs to OutFile.
  3887. word puts2(char* s)
  3888. {
  3889. word res;
  3890. if (!OutFile)
  3891. return 0;
  3892. // Turbo C++ 1.01's fputs() returns EOF if s is empty, which is wrong.
  3893. // Hence the workaround.
  3894. fputs(OutFile, s);
  3895. res = fputc(OutFile, '\n');
  3896. return res;
  3897. }
  3898. // Print string to outfile
  3899. word printf2(char* sToWrite)
  3900. {
  3901. if (!OutFile)
  3902. {
  3903. printf("COULD NOT WRITE TO OUT!");
  3904. return 0;
  3905. }
  3906. // TODO: escape handling
  3907. word res = fputs(OutFile, sToWrite);
  3908. return res;
  3909. }
  3910. // Print decimal to outfile
  3911. word printd2(word dToWrite)
  3912. {
  3913. if (!OutFile)
  3914. return 0;
  3915. char buf[32];
  3916. // handle negative numbers
  3917. if (dToWrite < 0)
  3918. {
  3919. fputc(OutFile, '-');
  3920. dToWrite = -dToWrite;
  3921. }
  3922. itoa(dToWrite, buf);
  3923. word res = fputs(OutFile, buf);
  3924. return res;
  3925. }
  3926. void error(char* strToPrint)
  3927. {
  3928. word i, fidx = FileCnt - 1 + !FileCnt;
  3929. for (i = 0; i < FileCnt; i++)
  3930. if (Files[i])
  3931. fclose(Files[i]);
  3932. /*
  3933. puts2("");
  3934. DumpSynDecls();
  3935. DumpMacroTable();
  3936. DumpIdentTable();
  3937. */
  3938. // using stdout implicitly instead of stderr explicitly because:
  3939. // - stderr can be a macro and it's unknown if standard headers
  3940. // aren't included (which is the case when SmallerC is compiled
  3941. // with itself and linked with some other compiler's standard
  3942. // libraries)
  3943. // - output to stderr can interfere/overlap with buffered
  3944. // output to stdout and the result may literally look ugly
  3945. //GenStartCommentLine(); printf2("Compilation failed.\n");
  3946. if (OutFile)
  3947. fclose(OutFile);
  3948. printf("Error in ");
  3949. printf(FileNames[fidx]);
  3950. printf(" at ");
  3951. printd(LineNo);
  3952. printf(":");
  3953. printd(LinePos);
  3954. printf("\n");
  3955. printf(strToPrint);
  3956. printf("\n");
  3957. exit(EXIT_FAILURE);
  3958. }
  3959. void warning(char* strToPrint)
  3960. {
  3961. word fidx = FileCnt - 1 + !FileCnt;
  3962. warnCnt++;
  3963. if (!warnings)
  3964. return;
  3965. //printf("Warning in \"%s\" (%d:%d)\n", FileNames[fidx], LineNo, LinePos);
  3966. printf("warning.");
  3967. printf(strToPrint);
  3968. }
  3969. void errorFile(char* n)
  3970. {
  3971. printf("Unable to open, read, write or close file ");
  3972. error(n);
  3973. }
  3974. void errorFileName(void)
  3975. {
  3976. error("Invalid or too long file name or path name\n");
  3977. }
  3978. void errorInternal(word n)
  3979. {
  3980. printd(n);
  3981. error(" internal error\n");
  3982. }
  3983. void errorChrStr(void)
  3984. {
  3985. error("Invalid or unsupported character constant or string literal\n");
  3986. }
  3987. void errorStrLen(void)
  3988. {
  3989. error("String literal too long\n");
  3990. }
  3991. void errorUnexpectedToken(word tok)
  3992. {
  3993. printf("Unexpected token ");
  3994. error((tok == tokIdent) ? TokenIdentName : GetTokenName(tok));
  3995. }
  3996. void errorDirective(void)
  3997. {
  3998. error("Invalid or unsupported preprocessor directive\n");
  3999. }
  4000. void errorCtrlOutOfScope(void)
  4001. {
  4002. error("break, continue, case or default in wrong scope\n");
  4003. }
  4004. void errorDecl(void)
  4005. {
  4006. error("Invalid or unsupported declaration\n");
  4007. }
  4008. void errorTagRedef(word ident)
  4009. {
  4010. printf("Redefinition of type tagged ");
  4011. printd(IdentTable + ident);
  4012. error("\n");
  4013. }
  4014. void errorVarSize(void)
  4015. {
  4016. error("Variable(s) take(s) too much space\n");
  4017. }
  4018. void errorInit(void)
  4019. {
  4020. error("Invalid or unsupported initialization\n");
  4021. }
  4022. void errorUnexpectedVoid(void)
  4023. {
  4024. error("Unexpected declaration or expression of type void\n");
  4025. }
  4026. void errorOpType(void)
  4027. {
  4028. error("Unexpected operand type\n");
  4029. }
  4030. void errorNotLvalue(void)
  4031. {
  4032. error("lvalue expected\n");
  4033. }
  4034. void errorNotConst(void)
  4035. {
  4036. error("Non-constant expression\n");
  4037. }
  4038. void errorLongExpr(void)
  4039. {
  4040. error("Expression too long\n");
  4041. }
  4042. word tsd[] =
  4043. {
  4044. tokVoid, tokChar, tokInt,
  4045. tokSigned, tokUnsigned, tokShort,
  4046. tokStruct, tokUnion,
  4047. };
  4048. word TokenStartsDeclaration(word t, word params)
  4049. {
  4050. unsigned i;
  4051. for (i = 0; i < division(sizeof tsd, sizeof tsd[0]); i++)
  4052. if (tsd[i] == t)
  4053. return 1;
  4054. return
  4055. (SizeOfWord != 2 && t == tokLong) ||
  4056. (!params && (t == tokExtern ||
  4057. t == tokStatic));
  4058. }
  4059. void PushSyntax2(word t, word v)
  4060. {
  4061. if (SyntaxStackCnt >= SYNTAX_STACK_MAX)
  4062. error("Symbol table exhausted\n");
  4063. SyntaxStack0[SyntaxStackCnt] = t;
  4064. SyntaxStack1[SyntaxStackCnt++] = v;
  4065. }
  4066. void PushSyntax(word t)
  4067. {
  4068. PushSyntax2(t, 0);
  4069. }
  4070. void InsertSyntax2(word pos, word t, word v)
  4071. {
  4072. if (SyntaxStackCnt >= SYNTAX_STACK_MAX)
  4073. error("Symbol table exhausted\n");
  4074. memmove(&SyntaxStack0[pos + 1],
  4075. &SyntaxStack0[pos],
  4076. sizeof(SyntaxStack0[0]) * (SyntaxStackCnt - pos));
  4077. memmove(&SyntaxStack1[pos + 1],
  4078. &SyntaxStack1[pos],
  4079. sizeof(SyntaxStack1[0]) * (SyntaxStackCnt - pos));
  4080. SyntaxStack0[pos] = t;
  4081. SyntaxStack1[pos] = v;
  4082. SyntaxStackCnt++;
  4083. }
  4084. void InsertSyntax(word pos, word t)
  4085. {
  4086. InsertSyntax2(pos, t, 0);
  4087. }
  4088. void DeleteSyntax(word pos, word cnt)
  4089. {
  4090. memmove(&SyntaxStack0[pos],
  4091. &SyntaxStack0[pos + cnt],
  4092. sizeof(SyntaxStack0[0]) * (SyntaxStackCnt - (pos + cnt)));
  4093. memmove(&SyntaxStack1[pos],
  4094. &SyntaxStack1[pos + cnt],
  4095. sizeof(SyntaxStack1[0]) * (SyntaxStackCnt - (pos + cnt)));
  4096. SyntaxStackCnt -= cnt;
  4097. }
  4098. word FindSymbol(char* s)
  4099. {
  4100. word i;
  4101. // TBD!!! return declaration scope number so
  4102. // redeclarations can be reported if occur in the same scope.
  4103. // TBD??? Also, I could first use FindIdent() and then just look for the
  4104. // index into IdentTable[] instead of doing strcmp()
  4105. for (i = SyntaxStackCnt - 1; i >= 0; i--)
  4106. {
  4107. word t = SyntaxStack0[i];
  4108. if (t == tokIdent &&
  4109. !strcmp(IdentTable + SyntaxStack1[i], s))
  4110. {
  4111. return i;
  4112. }
  4113. if (t == ')')
  4114. {
  4115. // Skip over the function params
  4116. word c = -1;
  4117. while (c)
  4118. {
  4119. t = SyntaxStack0[--i];
  4120. c += (t == '(') - (t == ')');
  4121. }
  4122. }
  4123. }
  4124. return -1;
  4125. }
  4126. word SymType(word SynPtr)
  4127. {
  4128. word local = 0;
  4129. if (SyntaxStack0[SynPtr] == tokIdent)
  4130. SynPtr++;
  4131. if ((local = SyntaxStack0[SynPtr] == tokLocalOfs) != 0)
  4132. SynPtr++;
  4133. switch (SyntaxStack0[SynPtr])
  4134. {
  4135. case '(':
  4136. return SymFxn;
  4137. case '[':
  4138. if (local)
  4139. return SymLocalArr;
  4140. return SymGlobalArr;
  4141. default:
  4142. if (local)
  4143. return SymLocalVar;
  4144. return SymGlobalVar;
  4145. }
  4146. }
  4147. word FindTaggedDecl(char* s, word start, word* CurScope)
  4148. {
  4149. word i;
  4150. *CurScope = 1;
  4151. for (i = start; i >= 0; i--)
  4152. {
  4153. word t = SyntaxStack0[i];
  4154. if (t == tokTag &&
  4155. !strcmp(IdentTable + SyntaxStack1[i], s))
  4156. {
  4157. return i - 1;
  4158. }
  4159. else if (t == ')')
  4160. {
  4161. // Skip over the function params
  4162. word c = -1;
  4163. while (c)
  4164. {
  4165. t = SyntaxStack0[--i];
  4166. c += (t == '(') - (t == ')');
  4167. }
  4168. }
  4169. else if (t == '#')
  4170. {
  4171. // the scope has changed to the outer scope
  4172. *CurScope = 0;
  4173. }
  4174. }
  4175. return -1;
  4176. }
  4177. word GetDeclSize(word SyntaxPtr, word SizeForDeref)
  4178. {
  4179. word i;
  4180. unsigned size = 1;
  4181. word arr = 0;
  4182. if (SyntaxPtr < 0) // pointer?
  4183. return SizeOfWord;
  4184. for (i = SyntaxPtr; i < SyntaxStackCnt; i++)
  4185. {
  4186. word tok = SyntaxStack0[i];
  4187. switch (tok)
  4188. {
  4189. case tokIdent: // skip leading identifiers, if any
  4190. case tokLocalOfs: // skip local var offset, too
  4191. break;
  4192. case tokChar:
  4193. case tokSChar:
  4194. if (!arr && ((tok == tokSChar) || CharIsSigned) && SizeForDeref)
  4195. return -1; // 1 byte, needing sign extension when converted to int/unsigned int
  4196. // fallthrough
  4197. case tokUChar:
  4198. return (word)size;
  4199. case tokShort:
  4200. if (!arr && SizeForDeref)
  4201. return -2; // 2 bytes, needing sign extension when converted to int/unsigned int
  4202. // fallthrough
  4203. case tokUShort:
  4204. //if (size * 2 / 2 != size)
  4205. //error("Variable too big\n");
  4206. // errorVarSize();
  4207. size *= 2;
  4208. if (size != truncUint(size))
  4209. //error("Variable too big\n");
  4210. {
  4211. //printf("b");
  4212. errorVarSize();
  4213. }
  4214. return (word)size;
  4215. case tokInt:
  4216. case tokUnsigned:
  4217. case '*':
  4218. case '(': // size of fxn = size of ptr for now
  4219. //if (size * SizeOfWord / SizeOfWord != size)
  4220. //error("Variable too big\n");
  4221. //errorVarSize();
  4222. size *= SizeOfWord;
  4223. if (size != truncUint(size))
  4224. //error("Variable too big\n");
  4225. {
  4226. //printf("c");
  4227. errorVarSize();
  4228. }
  4229. return (word)size;
  4230. case '[':
  4231. if (SyntaxStack0[i + 1] != tokNumInt && SyntaxStack0[i + 1] != tokNumUint)
  4232. errorInternal(11);
  4233. //if (SyntaxStack1[i + 1] &&
  4234. //size * SyntaxStack1[i + 1] / SyntaxStack1[i + 1] != size)
  4235. //error("Variable too big\n");
  4236. //errorVarSize();
  4237. size *= SyntaxStack1[i + 1];
  4238. if (size != truncUint(size))
  4239. //error("Variable too big\n");
  4240. {
  4241. //printf("d");
  4242. errorVarSize();
  4243. }
  4244. i += 2;
  4245. arr = 1;
  4246. break;
  4247. case tokStructPtr:
  4248. // follow the "type pointer"
  4249. i = SyntaxStack1[i] - 1;
  4250. break;
  4251. case tokStruct:
  4252. case tokUnion:
  4253. if (i + 2 < SyntaxStackCnt && SyntaxStack0[i + 2] == tokSizeof && !SizeForDeref)
  4254. {
  4255. unsigned s = SyntaxStack1[i + 2];
  4256. //if (s && size * s / s != size)
  4257. // errorVarSize();
  4258. size *= s;
  4259. if (size != truncUint(size))
  4260. {
  4261. //printf("d");
  4262. errorVarSize();
  4263. }
  4264. return (word)size;
  4265. }
  4266. return 0;
  4267. case tokVoid:
  4268. return 0;
  4269. default:
  4270. errorInternal(12);
  4271. }
  4272. }
  4273. errorInternal(13);
  4274. return 0;
  4275. }
  4276. word GetDeclAlignment(word SyntaxPtr)
  4277. {
  4278. word i;
  4279. if (SyntaxPtr < 0) // pointer?
  4280. return SizeOfWord;
  4281. for (i = SyntaxPtr; i < SyntaxStackCnt; i++)
  4282. {
  4283. word tok = SyntaxStack0[i];
  4284. switch (tok)
  4285. {
  4286. case tokIdent: // skip leading identifiers, if any
  4287. case tokLocalOfs: // skip local var offset, too
  4288. break;
  4289. case tokChar:
  4290. case tokSChar:
  4291. case tokUChar:
  4292. return 1;
  4293. case tokShort:
  4294. case tokUShort:
  4295. return 2;
  4296. case tokInt:
  4297. case tokUnsigned:
  4298. case '*':
  4299. case '(':
  4300. return SizeOfWord;
  4301. case '[':
  4302. if (SyntaxStack0[i + 1] != tokNumInt && SyntaxStack0[i + 1] != tokNumUint)
  4303. errorInternal(15);
  4304. i += 2;
  4305. break;
  4306. case tokStructPtr:
  4307. // follow the "type pointer"
  4308. i = SyntaxStack1[i] - 1;
  4309. break;
  4310. case tokStruct:
  4311. case tokUnion:
  4312. if (i + 3 < SyntaxStackCnt && SyntaxStack0[i + 2] == tokSizeof)
  4313. {
  4314. return SyntaxStack1[i + 3];
  4315. }
  4316. return 1;
  4317. case tokVoid:
  4318. return 1;
  4319. default:
  4320. errorInternal(16);
  4321. }
  4322. }
  4323. errorInternal(17);
  4324. return 0;
  4325. }
  4326. void DumpDecl(word SyntaxPtr, word IsParam)
  4327. {
  4328. word i;
  4329. word icnt = 0;
  4330. if (SyntaxPtr < 0)
  4331. return;
  4332. for (i = SyntaxPtr; i < SyntaxStackCnt; i++)
  4333. {
  4334. word tok = SyntaxStack0[i];
  4335. word v = SyntaxStack1[i];
  4336. switch (tok)
  4337. {
  4338. case tokLocalOfs:
  4339. printf2("(@");
  4340. printd2(truncInt(v));
  4341. printf2(") : ");
  4342. break;
  4343. case tokIdent:
  4344. if (++icnt > 1 && !IsParam) // show at most one declaration, except params
  4345. return;
  4346. GenStartCommentLine();
  4347. if (ParseLevel == 0)
  4348. printf2("glb ");
  4349. else if (IsParam)
  4350. printf2("prm ");
  4351. else
  4352. printf2("loc ");
  4353. {
  4354. word j;
  4355. for (j = 0; j < ParseLevel * 4; j++)
  4356. printf2(" ");
  4357. }
  4358. if (IsParam && !strcmp(IdentTable + v, "<something>") && (i + 1 < SyntaxStackCnt))
  4359. {
  4360. if (SyntaxStack0[i + 1] == tokEllipsis)
  4361. continue;
  4362. }
  4363. printf2(IdentTable + v);
  4364. printf2(" : ");
  4365. if (!IsParam && (i + 1 < SyntaxStackCnt) && SyntaxStack0[i + 1] == tokIdent)
  4366. {
  4367. // renamed local static variable
  4368. GenPrintLabel(IdentTable + SyntaxStack1[++i]);
  4369. printf2(" : ");
  4370. }
  4371. break;
  4372. case '[':
  4373. printf2("[");
  4374. break;
  4375. case tokNumInt:
  4376. printd2(truncInt(v));
  4377. break;
  4378. case tokNumUint:
  4379. printd2(truncUint(v));
  4380. break;
  4381. case ']':
  4382. printf2("] ");
  4383. break;
  4384. case '(':
  4385. {
  4386. word noparams;
  4387. // Skip over the params to the base type
  4388. word j = ++i, c = 1;
  4389. while (c)
  4390. {
  4391. word t = SyntaxStack0[j++];
  4392. c += (t == '(') - (t == ')');
  4393. }
  4394. noparams = (i + 1 == j) || (SyntaxStack0[i + 1] == tokVoid);
  4395. printf2("(");
  4396. // Print the params (recursively)
  4397. if (noparams)
  4398. {
  4399. // Don't recurse if it's "fxn()" or "fxn(void)"
  4400. if (i + 1 != j)
  4401. printf2("void");
  4402. }
  4403. else
  4404. {
  4405. puts2("");
  4406. ParseLevel++;
  4407. DumpDecl(i, 1);
  4408. ParseLevel--;
  4409. }
  4410. // Continue normally
  4411. i = j - 1;
  4412. if (!noparams)
  4413. {
  4414. GenStartCommentLine();
  4415. printf2(" ");
  4416. {
  4417. word j;
  4418. for (j = 0; j < ParseLevel * 4; j++)
  4419. printf2(" ");
  4420. }
  4421. }
  4422. printf2(") ");
  4423. }
  4424. break;
  4425. case ')': // end of param list
  4426. return;
  4427. case tokStructPtr:
  4428. DumpDecl(v, 0);
  4429. break;
  4430. default:
  4431. switch (tok)
  4432. {
  4433. case tokVoid:
  4434. case tokChar:
  4435. case tokSChar:
  4436. case tokUChar:
  4437. case tokShort:
  4438. case tokUShort:
  4439. case tokInt:
  4440. case tokUnsigned:
  4441. case tokEllipsis:
  4442. printf2(GetTokenName(tok));
  4443. printf2("\n");
  4444. break;
  4445. default:
  4446. printf2(GetTokenName(tok));
  4447. printf2(" ");
  4448. break;
  4449. case tokTag:
  4450. printf2(IdentTable + v);
  4451. printf2("\n");
  4452. return;
  4453. }
  4454. break;
  4455. }
  4456. }
  4457. }
  4458. void DumpSynDecls(void)
  4459. {
  4460. word used = SyntaxStackCnt * (sizeof SyntaxStack0[0] + sizeof SyntaxStack1[0]);
  4461. word total = SYNTAX_STACK_MAX * (sizeof SyntaxStack0[0] + sizeof SyntaxStack1[0]);
  4462. puts2("");
  4463. GenStartCommentLine(); printf2("Syntax/declaration table/stack:\n");
  4464. GenStartCommentLine();
  4465. printf2("Bytes used: ");
  4466. printd2(used);
  4467. printf2("/");
  4468. printd2(total);
  4469. printf2("\n\n");
  4470. }
  4471. word ParseArrayDimension(word AllowEmptyDimension)
  4472. {
  4473. word tok;
  4474. word gotUnary, synPtr, constExpr, exprVal;
  4475. unsigned exprValU;
  4476. word oldssp, oldesp, undoIdents;
  4477. tok = GetToken();
  4478. // DONE: support arbitrary constant expressions
  4479. oldssp = SyntaxStackCnt;
  4480. oldesp = sp;
  4481. undoIdents = IdentTableLen;
  4482. tok = ParseExpr(tok, &gotUnary, &synPtr, &constExpr, &exprVal, 0, 0);
  4483. IdentTableLen = undoIdents; // remove all temporary identifier names from e.g. "sizeof"
  4484. SyntaxStackCnt = oldssp; // undo any temporary declarations from e.g. "sizeof" in the expression
  4485. sp = oldesp;
  4486. if (tok != ']')
  4487. //error("ParseArrayDimension(): Unsupported or invalid array dimension (token %s)\n", GetTokenName(tok));
  4488. errorUnexpectedToken(tok);
  4489. if (!gotUnary)
  4490. {
  4491. if (!AllowEmptyDimension)
  4492. //error("ParseArrayDimension(): missing array dimension\n");
  4493. errorUnexpectedToken(tok);
  4494. // Empty dimension is dimension of 0
  4495. exprVal = 0;
  4496. }
  4497. else
  4498. {
  4499. if (!constExpr)
  4500. //error("ParseArrayDimension(): non-constant array dimension\n");
  4501. errorNotConst();
  4502. exprValU = truncUint(exprVal);
  4503. exprVal = truncInt(exprVal);
  4504. promoteType(&synPtr, &synPtr);
  4505. anyIntTypeCheck(synPtr);
  4506. if ((SyntaxStack0[synPtr] == tokInt && exprVal < 1) || (SyntaxStack0[synPtr] == tokUnsigned && exprValU < 1))
  4507. error("Array dimension less than 1\n");
  4508. exprVal = (word)exprValU;
  4509. }
  4510. PushSyntax2(tokNumUint, exprVal);
  4511. return tok;
  4512. }
  4513. void ParseFxnParams(word tok);
  4514. static word BrkCntTargetFxn[2];
  4515. word ParseBlock(word BrkCntTarget[2], word casesIdx);
  4516. void AddFxnParamSymbols(word SyntaxPtr);
  4517. void CheckRedecl(word lastSyntaxPtr);
  4518. word ParseBase(word tok, word base[2])
  4519. {
  4520. word valid = 1;
  4521. base[1] = 0;
  4522. switch (tok)
  4523. {
  4524. case tokVoid:
  4525. *base = tok;
  4526. tok = GetToken();
  4527. break;
  4528. case tokChar:
  4529. case tokInt:
  4530. case tokShort:
  4531. case tokLong:
  4532. case tokSigned:
  4533. case tokUnsigned:
  4534. {
  4535. word allowedMask = 0x7F; // double:0x40 unsigned:0x20 signed:0x10 long:0x08 int:0x04 short:0x02 char:0x01
  4536. word typeMask = 0;
  4537. word tokMask, disallowedMask;
  4538. lcont:
  4539. switch (tok)
  4540. {
  4541. case tokChar:
  4542. tokMask = 0x01; disallowedMask = 0x4E; break; // disallows double, long, int, short
  4543. case tokShort:
  4544. tokMask = 0x02; disallowedMask = 0x49; break; // disallows double, long, char
  4545. case tokInt:
  4546. tokMask = 0x04; disallowedMask = 0x41; break; // disallows double, char
  4547. case tokLong:
  4548. tokMask = 0x08; disallowedMask = 0x03; break; // disallows short, char
  4549. case tokSigned:
  4550. tokMask = 0x10; disallowedMask = 0x60; break; // disallows double, unsigned
  4551. case tokUnsigned:
  4552. tokMask = 0x20; disallowedMask = 0x50; break; // disallows double, signed
  4553. default:
  4554. tokMask = disallowedMask = 0; break;
  4555. }
  4556. if (allowedMask & tokMask)
  4557. {
  4558. typeMask |= tokMask;
  4559. allowedMask &= ~(disallowedMask | tokMask);
  4560. tok = GetToken();
  4561. goto lcont;
  4562. }
  4563. switch (typeMask)
  4564. {
  4565. case 0x01: typeMask = tokChar; break;
  4566. case 0x11: typeMask = tokSChar; break;
  4567. case 0x21: typeMask = tokUChar; break;
  4568. case 0x02: case 0x12: case 0x06: case 0x16: typeMask = tokShort; break;
  4569. case 0x22: case 0x26: typeMask = tokUShort; break;
  4570. case 0x04: case 0x10: case 0x14: typeMask = tokInt; break;
  4571. case 0x20: case 0x24: typeMask = tokUnsigned; break;
  4572. case 0x08: case 0x18: case 0x0C: case 0x1C: typeMask = tokLong; break;
  4573. case 0x28: case 0x2C: typeMask = tokULong; break;
  4574. default:
  4575. errorDecl();
  4576. }
  4577. *base = typeMask;
  4578. }
  4579. break;
  4580. case tokStruct:
  4581. case tokUnion:
  4582. {
  4583. word structType = tok;
  4584. word empty = 1;
  4585. word typePtr = SyntaxStackCnt;
  4586. word gotTag = 0, tagIdent = 0, declPtr = -1, curScope = 0;
  4587. tok = GetToken();
  4588. if (tok == tokIdent)
  4589. {
  4590. // this is a structure/union/enum tag
  4591. gotTag = 1;
  4592. declPtr = FindTaggedDecl(TokenIdentName, SyntaxStackCnt - 1, &curScope);
  4593. tagIdent = AddIdent(TokenIdentName);
  4594. if (declPtr >= 0)
  4595. {
  4596. // Within the same scope we can't declare more than one union, structure or enum
  4597. // with the same tag.
  4598. // There's one common tag namespace for structures, unions and enumerations.
  4599. if (curScope && SyntaxStack0[declPtr] != structType)
  4600. errorTagRedef(tagIdent);
  4601. }
  4602. else if (ParamLevel)
  4603. {
  4604. // new structure/union/enum declarations aren't supported in function parameters
  4605. errorDecl();
  4606. }
  4607. tok = GetToken();
  4608. }
  4609. else
  4610. {
  4611. // structure/union/enum declarations aren't supported in expressions
  4612. if (ExprLevel)
  4613. errorDecl();
  4614. PushSyntax(structType);
  4615. PushSyntax2(tokTag, AddIdent("<something>"));
  4616. }
  4617. if (tok == '{')
  4618. {
  4619. unsigned structInfo[4], sz, alignment, tmp;
  4620. // new structure/union/enum declarations aren't supported in expressions and function parameters
  4621. if (ExprLevel || ParamLevel)
  4622. errorDecl();
  4623. if (gotTag)
  4624. {
  4625. // Cannot redefine a tagged structure/union/enum within the same scope
  4626. if (declPtr >= 0 &&
  4627. curScope &&
  4628. ((declPtr + 2 < SyntaxStackCnt && SyntaxStack0[declPtr + 2] == tokSizeof)
  4629. ))
  4630. errorTagRedef(tagIdent);
  4631. PushSyntax(structType);
  4632. PushSyntax2(tokTag, tagIdent);
  4633. }
  4634. {
  4635. structInfo[0] = structType;
  4636. structInfo[1] = 1; // initial member alignment
  4637. structInfo[2] = 0; // initial member offset
  4638. structInfo[3] = 0; // initial max member size (for unions)
  4639. PushSyntax(tokSizeof); // 0 = initial structure/union size, to be updated
  4640. PushSyntax2(tokSizeof, 1); // 1 = initial structure/union alignment, to be updated
  4641. PushSyntax('{');
  4642. tok = GetToken();
  4643. while (tok != '}')
  4644. {
  4645. if (!TokenStartsDeclaration(tok, 1))
  4646. errorUnexpectedToken(tok);
  4647. tok = ParseDecl(tok, structInfo, 0, 0);
  4648. empty = 0;
  4649. }
  4650. if (empty)
  4651. errorUnexpectedToken('}');
  4652. PushSyntax('}');
  4653. // Update structure/union alignment
  4654. alignment = structInfo[1];
  4655. SyntaxStack1[typePtr + 3] = alignment;
  4656. // Update structure/union size and include trailing padding if needed
  4657. sz = structInfo[2] + structInfo[3];
  4658. tmp = sz;
  4659. sz = (sz + alignment - 1) & ~(alignment - 1);
  4660. if (sz < tmp || sz != truncUint(sz))
  4661. {
  4662. //printf("e");
  4663. errorVarSize();
  4664. }
  4665. SyntaxStack1[typePtr + 2] = (word)sz;
  4666. tok = GetToken();
  4667. }
  4668. }
  4669. else
  4670. {
  4671. if (gotTag)
  4672. {
  4673. if (declPtr >= 0 &&
  4674. SyntaxStack0[declPtr] == structType)
  4675. {
  4676. base[0] = tokStructPtr;
  4677. base[1] = declPtr;
  4678. return tok;
  4679. }
  4680. PushSyntax(structType);
  4681. PushSyntax2(tokTag, tagIdent);
  4682. empty = 0;
  4683. }
  4684. }
  4685. if (empty)
  4686. errorDecl();
  4687. base[0] = tokStructPtr;
  4688. base[1] = typePtr;
  4689. // If we've just defined a structure/union and there are
  4690. // preceding references to this tag within this scope,
  4691. // IOW references to an incomplete type, complete the
  4692. // type in the references
  4693. if (gotTag && SyntaxStack0[SyntaxStackCnt - 1] == '}')
  4694. {
  4695. word i;
  4696. for (i = SyntaxStackCnt - 1; i >= 0; i--)
  4697. if (SyntaxStack0[i] == tokStructPtr)
  4698. {
  4699. word j = SyntaxStack1[i];
  4700. if (SyntaxStack1[j + 1] == tagIdent && !GetDeclSize(i, 0))
  4701. SyntaxStack1[i] = typePtr;
  4702. }
  4703. else if (SyntaxStack0[i] == '#')
  4704. {
  4705. // reached the beginning of the current scope
  4706. break;
  4707. }
  4708. }
  4709. }
  4710. break;
  4711. default:
  4712. valid = 0;
  4713. break;
  4714. }
  4715. if (SizeOfWord == 2 &&
  4716. (*base == tokLong || *base == tokULong))
  4717. valid = 0;
  4718. // to simplify matters, treat long and unsigned long as aliases for int and unsigned int
  4719. // in 32-bit and huge mode(l)s
  4720. if (*base == tokLong)
  4721. *base = tokInt;
  4722. if (*base == tokULong)
  4723. *base = tokUnsigned;
  4724. if (SizeOfWord == 2)
  4725. {
  4726. // to simplify matters, treat short and unsigned short as aliases for int and unsigned int
  4727. // in 16-bit mode
  4728. if (*base == tokShort)
  4729. *base = tokInt;
  4730. if (*base == tokUShort)
  4731. *base = tokUnsigned;
  4732. }
  4733. // TBD!!! review/test this fxn
  4734. // if (!valid || !tok || !(strchr("*([,)", tok) || tok == tokIdent))
  4735. if (!valid | !tok)
  4736. //error("ParseBase(): Invalid or unsupported type\n");
  4737. error("Invalid or unsupported type\n");
  4738. return tok;
  4739. }
  4740. /*
  4741. base * name [] -> name : [] * base
  4742. base *2 (*1 name []1) []2 -> name : []1 *1 []2 *2 base
  4743. base *3 (*2 (*1 name []1) []2) []3 -> name : []1 *1 []2 *2 []3 *3 base
  4744. */
  4745. word ParseDerived(word tok)
  4746. {
  4747. word stars = 0;
  4748. word params = 0;
  4749. while (tok == '*')
  4750. {
  4751. stars++;
  4752. tok = GetToken();
  4753. }
  4754. if (tok == '(')
  4755. {
  4756. tok = GetToken();
  4757. if (tok != ')' && !TokenStartsDeclaration(tok, 1))
  4758. {
  4759. tok = ParseDerived(tok);
  4760. if (tok != ')')
  4761. //error("ParseDerived(): ')' expected\n");
  4762. errorUnexpectedToken(tok);
  4763. tok = GetToken();
  4764. }
  4765. else
  4766. {
  4767. params = 1;
  4768. }
  4769. }
  4770. else if (tok == tokIdent)
  4771. {
  4772. PushSyntax2(tok, AddIdent(TokenIdentName));
  4773. tok = GetToken();
  4774. }
  4775. else
  4776. {
  4777. PushSyntax2(tokIdent, AddIdent("<something>"));
  4778. }
  4779. if (params | (tok == '('))
  4780. {
  4781. word t = SyntaxStack0[SyntaxStackCnt - 1];
  4782. if ((t == ')') | (t == ']'))
  4783. errorUnexpectedToken('('); // array of functions or function returning function
  4784. if (!params)
  4785. tok = GetToken();
  4786. else
  4787. PushSyntax2(tokIdent, AddIdent("<something>"));
  4788. PushSyntax('(');
  4789. ParseLevel++;
  4790. ParamLevel++;
  4791. ParseFxnParams(tok);
  4792. ParamLevel--;
  4793. ParseLevel--;
  4794. PushSyntax(')');
  4795. tok = GetToken();
  4796. }
  4797. else if (tok == '[')
  4798. {
  4799. // DONE!!! allow the first [] without the dimension in function parameters
  4800. word allowEmptyDimension = 1;
  4801. if (SyntaxStack0[SyntaxStackCnt - 1] == ')')
  4802. errorUnexpectedToken('['); // function returning array
  4803. while (tok == '[')
  4804. {
  4805. word oldsp = SyntaxStackCnt;
  4806. PushSyntax(tokVoid); // prevent cases like "int arr[arr];" and "int arr[arr[0]];"
  4807. PushSyntax(tok);
  4808. tok = ParseArrayDimension(allowEmptyDimension);
  4809. if (tok != ']')
  4810. //error("ParseDerived(): ']' expected\n");
  4811. errorUnexpectedToken(tok);
  4812. PushSyntax(']');
  4813. tok = GetToken();
  4814. DeleteSyntax(oldsp, 1);
  4815. allowEmptyDimension = 0;
  4816. }
  4817. }
  4818. while (stars--)
  4819. PushSyntax('*');
  4820. if (!tok || !strchr(",;{=)", tok))
  4821. //error("ParseDerived(): unexpected token %s\n", GetTokenName(tok));
  4822. errorUnexpectedToken(tok);
  4823. return tok;
  4824. }
  4825. void PushBase(word base[2])
  4826. {
  4827. {
  4828. PushSyntax2(base[0], base[1]);
  4829. }
  4830. // Cannot have array of void
  4831. if (SyntaxStack0[SyntaxStackCnt - 1] == tokVoid &&
  4832. SyntaxStack0[SyntaxStackCnt - 2] == ']')
  4833. errorUnexpectedVoid();
  4834. }
  4835. word InitScalar(word synPtr, word tok);
  4836. word InitArray(word synPtr, word tok);
  4837. word InitStruct(word synPtr, word tok);
  4838. word InitVar(word synPtr, word tok)
  4839. {
  4840. word p = synPtr, t;
  4841. word undoIdents = IdentTableLen;
  4842. while ((t = SyntaxStack0[p]), (t == tokIdent) | (t == tokLocalOfs))
  4843. p++;
  4844. switch (t)
  4845. {
  4846. case '[':
  4847. // Initializers for aggregates must be enclosed in braces,
  4848. // except for arrays of char initialized with string literals,
  4849. // in which case braces are optional
  4850. if (tok != '{')
  4851. {
  4852. t = SyntaxStack0[p + 3];
  4853. if (((tok != tokLitStr) | ((t != tokChar) & (t != tokUChar) & (t != tokSChar)))
  4854. )
  4855. errorUnexpectedToken(tok);
  4856. }
  4857. tok = InitArray(p, tok);
  4858. break;
  4859. case tokStructPtr:
  4860. // Initializers for aggregates must be enclosed in braces
  4861. if (tok != '{')
  4862. errorUnexpectedToken(tok);
  4863. tok = InitStruct(p, tok);
  4864. break;
  4865. default:
  4866. tok = InitScalar(p, tok);
  4867. break;
  4868. }
  4869. if (!strchr(",;", tok))
  4870. errorUnexpectedToken(tok);
  4871. IdentTableLen = undoIdents; // remove all temporary identifier names from e.g. "sizeof" or "str"
  4872. return tok;
  4873. }
  4874. word InitScalar(word synPtr, word tok)
  4875. {
  4876. unsigned elementSz = GetDeclSize(synPtr, 0);
  4877. word gotUnary, synPtr2, constExpr, exprVal;
  4878. word oldssp = SyntaxStackCnt;
  4879. word undoIdents = IdentTableLen;
  4880. word ttop;
  4881. word braces = 0;
  4882. // Initializers for scalars can be optionally enclosed in braces
  4883. if (tok == '{')
  4884. {
  4885. braces = 1;
  4886. tok = GetToken();
  4887. }
  4888. tok = ParseExpr(tok, &gotUnary, &synPtr2, &constExpr, &exprVal, ',', 0);
  4889. if (!gotUnary)
  4890. errorUnexpectedToken(tok);
  4891. if (braces)
  4892. {
  4893. if (tok != '}')
  4894. errorUnexpectedToken(tok);
  4895. tok = GetToken();
  4896. }
  4897. // Bar void and struct/union
  4898. scalarTypeCheck(synPtr2);
  4899. ttop = stack[sp - 1][0];
  4900. if (ttop == tokNumInt || ttop == tokNumUint)
  4901. {
  4902. word val = stack[sp - 1][1];
  4903. // TBD??? truncate values for types smaller than int (e.g. char and short),
  4904. // so they are always in range for the assembler?
  4905. GenIntData(elementSz, val);
  4906. }
  4907. else if (elementSz == (unsigned)SizeOfWord)
  4908. {
  4909. if (ttop == tokIdent)
  4910. {
  4911. GenAddrData(elementSz, IdentTable + stack[sp - 1][1], 0);
  4912. }
  4913. else if (ttop == '+' || ttop == '-')
  4914. {
  4915. word tleft = stack[sp - 3][0];
  4916. word tright = stack[sp - 2][0];
  4917. if (tleft == tokIdent &&
  4918. (tright == tokNumInt || tright == tokNumUint))
  4919. {
  4920. GenAddrData(elementSz, IdentTable + stack[sp - 3][1], (ttop == '+') ? stack[sp - 2][1] : -stack[sp - 2][1]);
  4921. }
  4922. else if (ttop == '+' &&
  4923. tright == tokIdent &&
  4924. (tleft == tokNumInt || tleft == tokNumUint))
  4925. {
  4926. GenAddrData(elementSz, IdentTable + stack[sp - 2][1], stack[sp - 3][1]);
  4927. }
  4928. else
  4929. errorNotConst();
  4930. }
  4931. else
  4932. errorNotConst();
  4933. // Defer storage of string literal data (if any) until the end.
  4934. // This will let us generate the contiguous array of pointers to
  4935. // string literals unperturbed by the string literal data
  4936. // (e.g. "char* colors[] = { "red", "green", "blue" };").
  4937. }
  4938. else
  4939. //error("ParseDecl(): cannot initialize a global variable with a non-constant expression\n");
  4940. errorNotConst();
  4941. IdentTableLen = undoIdents; // remove all temporary identifier names from e.g. "sizeof" or "str"
  4942. SyntaxStackCnt = oldssp; // undo any temporary declarations from e.g. "sizeof" or "str" in the expression
  4943. return tok;
  4944. }
  4945. word InitArray(word synPtr, word tok)
  4946. {
  4947. word elementTypePtr = synPtr + 3;
  4948. word elementType = SyntaxStack0[elementTypePtr];
  4949. unsigned elementSz = GetDeclSize(elementTypePtr, 0);
  4950. word braces = 0;
  4951. unsigned elementCnt = 0;
  4952. unsigned elementsRequired = SyntaxStack1[synPtr + 1];
  4953. word arrOfChar = (elementType == tokChar) | (elementType == tokUChar) | (elementType == tokSChar);
  4954. if (tok == '{')
  4955. {
  4956. braces = 1;
  4957. tok = GetToken();
  4958. }
  4959. if ((arrOfChar & (tok == tokLitStr))
  4960. )
  4961. {
  4962. word ltok = tok;
  4963. unsigned sz = 0;
  4964. // this is 'someArray[someCountIfAny] = "some string"' or
  4965. // 'someArray[someCountIfAny] = { "some string" }'
  4966. do
  4967. {
  4968. GetString('"', 0, 'd');
  4969. if (sz + TokenStringSize < sz ||
  4970. sz + TokenStringSize >= truncUint(-1))
  4971. errorStrLen();
  4972. sz += TokenStringSize;
  4973. elementCnt += TokenStringLen;
  4974. tok = GetToken();
  4975. } while (tok == ltok); // concatenate adjacent string literals
  4976. if (elementsRequired && elementCnt > elementsRequired)
  4977. errorStrLen();
  4978. if (elementCnt < elementsRequired)
  4979. GenZeroData(elementsRequired - elementCnt, 0);
  4980. if (!elementsRequired)
  4981. GenZeroData(elementSz, 0), elementCnt++;
  4982. if (braces)
  4983. {
  4984. if (tok != '}')
  4985. errorUnexpectedToken(tok);
  4986. tok = GetToken();
  4987. }
  4988. }
  4989. else
  4990. {
  4991. while (tok != '}')
  4992. {
  4993. if (elementType == '[')
  4994. {
  4995. tok = InitArray(elementTypePtr, tok);
  4996. }
  4997. else if (elementType == tokStructPtr)
  4998. {
  4999. tok = InitStruct(elementTypePtr, tok);
  5000. }
  5001. else
  5002. {
  5003. tok = InitScalar(elementTypePtr, tok);
  5004. }
  5005. // Last element?
  5006. if (++elementCnt >= elementsRequired && elementsRequired)
  5007. {
  5008. if (braces & (tok == ','))
  5009. tok = GetToken();
  5010. break;
  5011. }
  5012. if (tok == ',')
  5013. tok = GetToken();
  5014. else if (tok != '}')
  5015. errorUnexpectedToken(tok);
  5016. }
  5017. if (braces)
  5018. {
  5019. if ((!elementCnt) | (tok != '}'))
  5020. errorUnexpectedToken(tok);
  5021. tok = GetToken();
  5022. }
  5023. if (elementCnt < elementsRequired)
  5024. GenZeroData((elementsRequired - elementCnt) * elementSz, 0);
  5025. }
  5026. // Store the element count if it's an incomplete array
  5027. if (!elementsRequired)
  5028. SyntaxStack1[synPtr + 1] = elementCnt;
  5029. return tok;
  5030. }
  5031. word InitStruct(word synPtr, word tok)
  5032. {
  5033. word isUnion;
  5034. unsigned size, ofs = 0;
  5035. word braces = 0;
  5036. word c = 1;
  5037. synPtr = SyntaxStack1[synPtr];
  5038. isUnion = SyntaxStack0[synPtr++] == tokUnion;
  5039. size = SyntaxStack1[++synPtr];
  5040. synPtr += 3; // step inside the {} body of the struct/union
  5041. if (tok == '{')
  5042. {
  5043. braces = 1;
  5044. tok = GetToken();
  5045. }
  5046. // Find the first member
  5047. while (c)
  5048. {
  5049. word t = SyntaxStack0[synPtr];
  5050. c += (t == '(') - (t == ')') + (t == '{') - (t == '}');
  5051. if (c == 1 && t == tokMemberIdent)
  5052. break;
  5053. synPtr++;
  5054. }
  5055. while (tok != '}')
  5056. {
  5057. word c = 1;
  5058. word elementTypePtr, elementType;
  5059. unsigned elementOfs, elementSz;
  5060. elementOfs = SyntaxStack1[++synPtr];
  5061. elementTypePtr = ++synPtr;
  5062. elementType = SyntaxStack0[elementTypePtr];
  5063. elementSz = GetDeclSize(elementTypePtr, 0);
  5064. // Alignment
  5065. if (ofs < elementOfs)
  5066. GenZeroData(elementOfs - ofs, 0);
  5067. if (elementType == '[')
  5068. {
  5069. tok = InitArray(elementTypePtr, tok);
  5070. }
  5071. else if (elementType == tokStructPtr)
  5072. {
  5073. tok = InitStruct(elementTypePtr, tok);
  5074. }
  5075. else
  5076. {
  5077. tok = InitScalar(elementTypePtr, tok);
  5078. }
  5079. ofs = elementOfs + elementSz;
  5080. // Find the next member or the closing brace
  5081. while (c)
  5082. {
  5083. word t = SyntaxStack0[synPtr];
  5084. c += (t == '(') - (t == ')') + (t == '{') - (t == '}');
  5085. if (c == 1 && t == tokMemberIdent)
  5086. break;
  5087. synPtr++;
  5088. }
  5089. // Last member?
  5090. // Only one member (first) is initialized in unions explicitly
  5091. if ((!c) | isUnion)
  5092. {
  5093. if (braces & (tok == ','))
  5094. tok = GetToken();
  5095. break;
  5096. }
  5097. if (tok == ',')
  5098. tok = GetToken();
  5099. else if (tok != '}')
  5100. errorUnexpectedToken(tok);
  5101. }
  5102. if (braces)
  5103. {
  5104. if ((!ofs) | (tok != '}'))
  5105. errorUnexpectedToken(tok);
  5106. tok = GetToken();
  5107. }
  5108. // Implicit initialization of the rest and trailing padding
  5109. if (ofs < size)
  5110. GenZeroData(size - ofs, 0);
  5111. return tok;
  5112. }
  5113. word compatCheck2(word lastSyntaxPtr, word i)
  5114. {
  5115. word res = 0;
  5116. word c = 0;
  5117. word t;
  5118. for (;;)
  5119. {
  5120. t = SyntaxStack0[lastSyntaxPtr];
  5121. if (t != SyntaxStack0[i])
  5122. {
  5123. if (SyntaxStack0[i] == ')' && SyntaxStack0[i - 1] == '(')
  5124. {
  5125. // Complete a previously incomplete parameter specification
  5126. word c1 = 1;
  5127. // Skip over the function params
  5128. do
  5129. {
  5130. t = SyntaxStack0[lastSyntaxPtr++];
  5131. c1 += (t == '(') - (t == ')');
  5132. } while (c1);
  5133. lastSyntaxPtr--;
  5134. }
  5135. else if (t == ')' &&
  5136. SyntaxStack0[i - 1] == '(' && SyntaxStack0[i] == tokIdent &&
  5137. SyntaxStack0[i + 1] == tokVoid && SyntaxStack0[i + 2] == ')')
  5138. {
  5139. // As an exception allow foo(void) to be redeclared as foo()
  5140. // since this happens very often in code.
  5141. // This weakens our redeclaration checks, however. Warn about it.
  5142. i += 2;
  5143. warning("Redeclaration from no parameters to unspecified parameters.\n");
  5144. }
  5145. else
  5146. goto lend;
  5147. }
  5148. if (t != tokIdent &&
  5149. SyntaxStack1[lastSyntaxPtr] != SyntaxStack1[i])
  5150. {
  5151. if (SyntaxStack0[lastSyntaxPtr - 1] == '[')
  5152. {
  5153. // Complete an incomplete array dimension or check for dimension mismatch
  5154. if (SyntaxStack1[lastSyntaxPtr] == 0)
  5155. SyntaxStack1[lastSyntaxPtr] = SyntaxStack1[i];
  5156. else if (SyntaxStack1[i])
  5157. goto lend;
  5158. }
  5159. else
  5160. goto lend;
  5161. }
  5162. c += (t == '(') - (t == ')') + (t == '[') - (t == ']');
  5163. if (!c)
  5164. {
  5165. switch (t)
  5166. {
  5167. case tokVoid:
  5168. case tokChar: case tokSChar: case tokUChar:
  5169. case tokShort: case tokUShort:
  5170. case tokInt: case tokUnsigned:
  5171. case tokStructPtr:
  5172. goto lok;
  5173. }
  5174. }
  5175. lastSyntaxPtr++;
  5176. i++;
  5177. }
  5178. lok:
  5179. res = 1;
  5180. lend:
  5181. return res;
  5182. }
  5183. void CheckRedecl(word lastSyntaxPtr)
  5184. {
  5185. word tid, id, external = 0;
  5186. word i;
  5187. word curScopeOnly;
  5188. word level = ParseLevel;
  5189. tid = SyntaxStack0[lastSyntaxPtr];
  5190. id = SyntaxStack1[lastSyntaxPtr];
  5191. switch (tid)
  5192. {
  5193. case tokIdent:
  5194. switch (SyntaxStack0[lastSyntaxPtr + 1])
  5195. {
  5196. default:
  5197. external = 1;
  5198. // fallthrough
  5199. case tokLocalOfs: // block-scope auto
  5200. case tokIdent: // block-scope static
  5201. ;
  5202. }
  5203. // fallthrough
  5204. case tokTypedef:
  5205. break;
  5206. case tokMemberIdent:
  5207. {
  5208. word c = 1;
  5209. i = lastSyntaxPtr - 1;
  5210. do
  5211. {
  5212. word t = SyntaxStack0[i];
  5213. c -= (t == '(') - (t == ')') + (t == '{') - (t == '}');
  5214. if (c == 1 &&
  5215. t == tokMemberIdent && SyntaxStack1[i] == id &&
  5216. SyntaxStack0[i + 1] == tokLocalOfs)
  5217. errorRedecl(IdentTable + id);
  5218. i--;
  5219. } while (c);
  5220. }
  5221. return;
  5222. default:
  5223. errorInternal(23);
  5224. }
  5225. // limit search to current scope for typedef and enum,
  5226. // ditto for non-external declarations
  5227. curScopeOnly = tid != tokIdent || !external;
  5228. for (i = lastSyntaxPtr - 1; i >= 0; i--)
  5229. {
  5230. word t = SyntaxStack0[i];
  5231. switch (t)
  5232. {
  5233. case ')':
  5234. {
  5235. // Skip over the function params
  5236. word c = -1;
  5237. while (c)
  5238. {
  5239. t = SyntaxStack0[--i];
  5240. c += (t == '(') - (t == ')');
  5241. }
  5242. }
  5243. break;
  5244. case '#':
  5245. // the scope has changed to the outer scope
  5246. if (curScopeOnly)
  5247. return;
  5248. level--;
  5249. break;
  5250. case tokTypedef:
  5251. case tokIdent:
  5252. if (SyntaxStack1[i] == id)
  5253. {
  5254. if (level == ParseLevel)
  5255. {
  5256. // block scope:
  5257. // can differentiate between auto(tokLocalOfs), static(tokIdent),
  5258. // extern/proto(nothing) in SyntaxStack*[], hence dup checks and
  5259. // type match checks needed here
  5260. // file scope:
  5261. // can't differentiate between static(nothing), extern(nothing),
  5262. // neither(nothing) in SyntaxStack*[], but duplicate definitions
  5263. // are taken care of (in CG), hence only type match checks needed
  5264. // here
  5265. if (level) // block scope: check for bad dups
  5266. {
  5267. switch (SyntaxStack0[i + 1])
  5268. {
  5269. case tokLocalOfs: // block-scope auto
  5270. case tokIdent: // block-scope static
  5271. // auto and static can't be redefined in block scope
  5272. errorRedecl(IdentTable + id);
  5273. default:
  5274. // extern can't be redefined as non-extern in block scope
  5275. if (!external)
  5276. errorRedecl(IdentTable + id);
  5277. }
  5278. // extern/proto type match check follows
  5279. }
  5280. if (compatCheck2(lastSyntaxPtr, i))
  5281. return;
  5282. errorRedecl(IdentTable + id);
  5283. }
  5284. else // elseof if (level == ParseLevel)
  5285. {
  5286. // The new decl is extern/proto.
  5287. // Ignore typedef and enum
  5288. if (t == tokIdent)
  5289. {
  5290. switch (SyntaxStack0[i + 1])
  5291. {
  5292. case tokLocalOfs: // block-scope auto
  5293. case tokIdent: // block-scope static
  5294. // Ignore auto and static
  5295. break;
  5296. default:
  5297. // extern/proto
  5298. if (compatCheck2(lastSyntaxPtr, i))
  5299. return;
  5300. errorRedecl(IdentTable + id);
  5301. }
  5302. }
  5303. }
  5304. } // endof if (SyntaxStack1[i] == id)
  5305. break;
  5306. } // endof switch (t)
  5307. } // endof for (i = lastSyntaxPtr - 1; i >= 0; i--)
  5308. }
  5309. // DONE: support extern
  5310. // DONE: support static
  5311. // DONE: support basic initialization
  5312. // DONE: support simple non-array initializations with string literals
  5313. // DONE: support basic 1-d array initialization
  5314. // DONE: global/static data allocations
  5315. word ParseDecl(word tok, unsigned structInfo[4], word cast, word label)
  5316. {
  5317. word base[2];
  5318. word lastSyntaxPtr;
  5319. word external = tok == tokExtern;
  5320. word Static = tok == tokStatic;
  5321. (void)label;
  5322. if (external |
  5323. Static)
  5324. {
  5325. tok = GetToken();
  5326. if (!TokenStartsDeclaration(tok, 1))
  5327. //error("ParseDecl(): unexpected token %s\n", GetTokenName(tok));
  5328. // Implicit int (as in "extern x; static y;") isn't supported
  5329. errorUnexpectedToken(tok);
  5330. }
  5331. tok = ParseBase(tok, base);
  5332. for (;;)
  5333. {
  5334. lastSyntaxPtr = SyntaxStackCnt;
  5335. /* derived type */
  5336. tok = ParseDerived(tok);
  5337. /* base type */
  5338. PushBase(base);
  5339. if ((tok && strchr(",;{=", tok)) || (tok == ')' && ExprLevel))
  5340. {
  5341. word isLocal = 0, isGlobal = 0, isFxn, isStruct, isArray, isIncompleteArr;
  5342. unsigned alignment = 0;
  5343. word staticLabel = 0;
  5344. // Disallow void variables
  5345. if (SyntaxStack0[SyntaxStackCnt - 1] == tokVoid)
  5346. {
  5347. if (SyntaxStack0[SyntaxStackCnt - 2] == tokIdent &&
  5348. !(cast
  5349. ))
  5350. //error("ParseDecl(): Cannot declare a variable ('%s') of type 'void'\n", IdentTable + SyntaxStack1[lastSyntaxPtr]);
  5351. errorUnexpectedVoid();
  5352. }
  5353. isFxn = SyntaxStack0[lastSyntaxPtr + 1] == '(';
  5354. isArray = SyntaxStack0[lastSyntaxPtr + 1] == '[';
  5355. isIncompleteArr = isArray && SyntaxStack1[lastSyntaxPtr + 2] == 0;
  5356. isStruct = SyntaxStack0[lastSyntaxPtr + 1] == tokStructPtr;
  5357. if (!(ExprLevel || structInfo) &&
  5358. !(external |
  5359. Static) &&
  5360. !strcmp(IdentTable + SyntaxStack1[lastSyntaxPtr], "<something>") &&
  5361. tok == ';')
  5362. {
  5363. if (isStruct)
  5364. {
  5365. // This is either an incomplete tagged structure/union declaration, e.g. "struct sometag;",
  5366. // or a tagged complete structure/union declaration, e.g. "struct sometag { ... };", without an instance variable,
  5367. // or an untagged complete structure/union declaration, e.g. "struct { ... };", without an instance variable
  5368. word declPtr, curScope;
  5369. word j = SyntaxStack1[lastSyntaxPtr + 1];
  5370. if (j + 2 < SyntaxStackCnt &&
  5371. IdentTable[SyntaxStack1[j + 1]] == '<' && // without tag
  5372. SyntaxStack0[j + 2] == tokSizeof) // but with the {} "body"
  5373. errorDecl();
  5374. // If a structure/union with this tag has been declared in an outer scope,
  5375. // this new declaration should override it
  5376. declPtr = FindTaggedDecl(IdentTable + SyntaxStack1[j + 1], lastSyntaxPtr - 1, &curScope);
  5377. if (declPtr >= 0 && !curScope)
  5378. {
  5379. // If that's the case, unbind this declaration from the old declaration
  5380. // and make it a new incomplete declaration
  5381. PushSyntax(SyntaxStack0[j]); // tokStruct or tokUnion
  5382. PushSyntax2(tokTag, SyntaxStack1[j + 1]);
  5383. SyntaxStack1[lastSyntaxPtr + 1] = SyntaxStackCnt - 2;
  5384. }
  5385. return GetToken();
  5386. }
  5387. }
  5388. // Structure/union members can't be initialized nor be functions nor
  5389. // be incompletely typed arrays inside structure/union declarations
  5390. if (structInfo && ((tok == '=') | isFxn | (tok == '{') | isIncompleteArr))
  5391. errorDecl();
  5392. // Error conditions in declarations(/definitions/initializations):
  5393. // Legend:
  5394. // + error
  5395. // - no error
  5396. //
  5397. // file scope fxn fxn {} var arr[] arr[]...[] arr[incomplete] arr[incomplete]...[]
  5398. // - - - - - + +
  5399. // file scope fxn= var= arr[]= arr[]...[]= arr[incomplete]= arr[incomplete]...[]=
  5400. // + - - + - +
  5401. // file scope extern fxn fxn {} var arr[] arr[]...[] arr[incomplete] arr[incomplete]...[]
  5402. // - - - - - - -
  5403. // file scope extern fxn= var= arr[]= arr[]...[]= arr[incomplete]= arr[incomplete]...[]=
  5404. // + + + + + +
  5405. // file scope static fxn fxn {} var arr[] arr[]...[] arr[incomplete] arr[incomplete]...[]
  5406. // - - - - - + +
  5407. // file scope static fxn= var= arr[]= arr[]...[]= arr[incomplete]= arr[incomplete]...[]=
  5408. // + - - + - +
  5409. // fxn scope fxn fxn {} var arr[] arr[]...[] arr[incomplete] arr[incomplete]...[]
  5410. // - + - - - + +
  5411. // fxn scope fxn= var= arr[]= arr[]...[]= arr[incomplete]= arr[incomplete]...[]=
  5412. // + - + + + +
  5413. // fxn scope extern fxn fxn {} var arr[] arr[]...[] arr[incomplete] arr[incomplete]...[]
  5414. // - + - - - - -
  5415. // fxn scope extern fxn= var= arr[]= arr[]...[]= arr[incomplete]= arr[incomplete]...[]=
  5416. // + + + + + +
  5417. // fxn scope static fxn fxn {} var arr[] arr[]...[] arr[incomplete] arr[incomplete]...[]
  5418. // + + + + + + +
  5419. // fxn scope static fxn= var= arr[]= arr[]...[]= arr[incomplete]= arr[incomplete]...[]=
  5420. // + + + + + +
  5421. if (isFxn & (tok == '='))
  5422. //error("ParseDecl(): cannot initialize a function\n");
  5423. errorInit();
  5424. if ((isFxn & (tok == '{')) && ParseLevel)
  5425. //error("ParseDecl(): cannot define a nested function\n");
  5426. errorDecl();
  5427. if ((isFxn & Static) && ParseLevel)
  5428. //error("ParseDecl(): cannot declare a static function in this scope\n");
  5429. errorDecl();
  5430. if (external & (tok == '='))
  5431. //error("ParseDecl(): cannot initialize an external variable\n");
  5432. errorInit();
  5433. if (isIncompleteArr & !(external |
  5434. (tok == '=')))
  5435. //error("ParseDecl(): cannot define an array of incomplete type\n");
  5436. errorDecl();
  5437. // TBD!!! de-uglify
  5438. if (!strcmp(IdentTable + SyntaxStack1[lastSyntaxPtr], "<something>"))
  5439. {
  5440. // Disallow nameless variables, prototypes, structure/union members and typedefs.
  5441. if (structInfo ||
  5442. !ExprLevel)
  5443. error("Identifier expected in declaration\n");
  5444. }
  5445. else
  5446. {
  5447. // Disallow named variables and prototypes in sizeof(typedecl) and (typedecl).
  5448. if (ExprLevel && !structInfo)
  5449. error("Identifier unexpected in declaration\n");
  5450. }
  5451. if (!isFxn
  5452. )
  5453. {
  5454. // This is a variable or a variable (member) in a struct/union declaration
  5455. word sz = GetDeclSize(lastSyntaxPtr, 0);
  5456. if (!((sz | isIncompleteArr) || ExprLevel)) // incomplete type
  5457. errorDecl(); // TBD!!! different error when struct/union tag is not found
  5458. if (isArray && !GetDeclSize(lastSyntaxPtr + 4, 0))
  5459. // incomplete type of array element (e.g. struct/union)
  5460. errorDecl();
  5461. alignment = GetDeclAlignment(lastSyntaxPtr);
  5462. if (structInfo)
  5463. {
  5464. // It's a variable (member) in a struct/union declaration
  5465. unsigned tmp;
  5466. unsigned newAlignment = alignment;
  5467. // Update structure/union alignment
  5468. if (structInfo[1] < newAlignment)
  5469. structInfo[1] = newAlignment;
  5470. // Align structure member
  5471. tmp = structInfo[2];
  5472. structInfo[2] = (structInfo[2] + newAlignment - 1) & ~(newAlignment - 1);
  5473. if (structInfo[2] < tmp || structInfo[2] != truncUint(structInfo[2]))
  5474. {
  5475. //printf("f");
  5476. errorVarSize();
  5477. }
  5478. // Change tokIdent to tokMemberIdent and insert a local var offset token
  5479. SyntaxStack0[lastSyntaxPtr] = tokMemberIdent;
  5480. InsertSyntax2(lastSyntaxPtr + 1, tokLocalOfs, (word)structInfo[2]);
  5481. // Advance member offset for structures, keep it zero for unions
  5482. if (structInfo[0] == tokStruct)
  5483. {
  5484. tmp = structInfo[2];
  5485. structInfo[2] += sz;
  5486. if (structInfo[2] < tmp || structInfo[2] != truncUint(structInfo[2]))
  5487. {
  5488. //printf("g");
  5489. errorVarSize();
  5490. }
  5491. }
  5492. // Update max member size for unions
  5493. else if (structInfo[3] < (unsigned)sz)
  5494. {
  5495. structInfo[3] = sz;
  5496. }
  5497. }
  5498. else if (ParseLevel && !((external | Static) || ExprLevel))
  5499. {
  5500. // It's a local variable
  5501. isLocal = 1;
  5502. // Defer size calculation until initialization
  5503. // Insert a local var offset token, the offset is to be updated
  5504. InsertSyntax2(lastSyntaxPtr + 1, tokLocalOfs, 0);
  5505. }
  5506. else if (!ExprLevel)
  5507. {
  5508. // It's a global variable (external, static or neither)
  5509. isGlobal = 1;
  5510. if (Static && ParseLevel)
  5511. {
  5512. // It's a static variable in function scope, "rename" it by providing
  5513. // an alternative unique numeric identifier right next to it and use it
  5514. staticLabel = LabelCnt++;
  5515. InsertSyntax2(lastSyntaxPtr + 1, tokIdent, AddNumericIdent(staticLabel));
  5516. }
  5517. }
  5518. }
  5519. // If it's a type declaration in a sizeof(typedecl) expression or
  5520. // in an expression with a cast, e.g. (typedecl)expr, we're done
  5521. if (ExprLevel && !structInfo)
  5522. {
  5523. if (doAnnotations)
  5524. {
  5525. DumpDecl(lastSyntaxPtr, 0);
  5526. }
  5527. return tok;
  5528. }
  5529. if (isLocal | isGlobal)
  5530. {
  5531. word hasInit = tok == '=';
  5532. word needsGlobalInit = isGlobal & !external;
  5533. word sz = GetDeclSize(lastSyntaxPtr, 0);
  5534. word initLabel = 0;
  5535. word bss = (!hasInit) & UseBss;
  5536. if (doAnnotations)
  5537. {
  5538. if (isGlobal)
  5539. DumpDecl(lastSyntaxPtr, 0);
  5540. }
  5541. if (hasInit)
  5542. {
  5543. tok = GetToken();
  5544. }
  5545. if (isLocal & hasInit)
  5546. needsGlobalInit = isArray | (isStruct & (tok == '{'));
  5547. if (needsGlobalInit)
  5548. {
  5549. char** oldHeaderFooter = CurHeaderFooter;
  5550. if (oldHeaderFooter)
  5551. puts2(oldHeaderFooter[1]);
  5552. CurHeaderFooter = bss ? BssHeaderFooter : DataHeaderFooter;
  5553. puts2(CurHeaderFooter[0]);
  5554. // DONE: imperfect condition for alignment
  5555. if (alignment != 1)
  5556. GenWordAlignment(bss);
  5557. if (isGlobal)
  5558. {
  5559. if (Static && ParseLevel)
  5560. GenNumLabel(staticLabel);
  5561. else
  5562. GenLabel(IdentTable + SyntaxStack1[lastSyntaxPtr], Static);
  5563. }
  5564. else
  5565. {
  5566. // Generate numeric labels for global initializers of local vars
  5567. GenNumLabel(initLabel = LabelCnt++);
  5568. }
  5569. // Generate global initializers
  5570. if (hasInit)
  5571. {
  5572. if (doAnnotations)
  5573. {
  5574. if (isGlobal)
  5575. {
  5576. GenStartCommentLine(); printf2("=\n");
  5577. }
  5578. }
  5579. tok = InitVar(lastSyntaxPtr, tok);
  5580. // Update the size in case it's an incomplete array
  5581. sz = GetDeclSize(lastSyntaxPtr, 0);
  5582. }
  5583. else
  5584. {
  5585. GenZeroData(sz, bss);
  5586. }
  5587. puts2(CurHeaderFooter[1]);
  5588. if (oldHeaderFooter)
  5589. puts2(oldHeaderFooter[0]);
  5590. CurHeaderFooter = oldHeaderFooter;
  5591. }
  5592. if (isLocal)
  5593. {
  5594. // Now that the size of the local is certainly known,
  5595. // update its offset in the offset token
  5596. SyntaxStack1[lastSyntaxPtr + 1] = AllocLocal(sz);
  5597. if (doAnnotations)
  5598. {
  5599. DumpDecl(lastSyntaxPtr, 0);
  5600. }
  5601. }
  5602. // Copy global initializers into local vars
  5603. if (isLocal & needsGlobalInit)
  5604. {
  5605. if (doAnnotations)
  5606. {
  5607. GenStartCommentLine(); printf2("=\n");
  5608. }
  5609. if (!StructCpyLabel)
  5610. StructCpyLabel = LabelCnt++;
  5611. sp = 0;
  5612. push2('(', SizeOfWord * 3);
  5613. push2(tokLocalOfs, SyntaxStack1[lastSyntaxPtr + 1]);
  5614. push(',');
  5615. push2(tokIdent, AddNumericIdent(initLabel));
  5616. push(',');
  5617. push2(tokNumUint, sz);
  5618. push(',');
  5619. push2(tokIdent, AddNumericIdent(StructCpyLabel));
  5620. push2(')', SizeOfWord * 3);
  5621. GenExpr();
  5622. }
  5623. // Initialize local vars with expressions
  5624. else if (hasInit & !needsGlobalInit)
  5625. {
  5626. word gotUnary, synPtr, constExpr, exprVal;
  5627. word brace = 0;
  5628. // Initializers for scalars can be optionally enclosed in braces
  5629. if ((!isStruct) & (tok == '{'))
  5630. {
  5631. brace = 1;
  5632. tok = GetToken();
  5633. }
  5634. // ParseExpr() will transform the initializer expression into an assignment expression here
  5635. tok = ParseExpr(tok, &gotUnary, &synPtr, &constExpr, &exprVal, '=', SyntaxStack1[lastSyntaxPtr]);
  5636. if (!gotUnary)
  5637. errorUnexpectedToken(tok);
  5638. if (brace)
  5639. {
  5640. if (tok != '}')
  5641. errorUnexpectedToken(tok);
  5642. tok = GetToken();
  5643. }
  5644. if (!isStruct)
  5645. {
  5646. // This is a special case for initialization of integers smaller than int.
  5647. // Since a local integer variable always takes as much space as a whole int,
  5648. // we can optimize code generation a bit by storing the initializer as an int.
  5649. // This is an old accidental optimization and I preserve it for now.
  5650. // Note, this implies a little-endian CPU.
  5651. stack[sp - 1][1] = SizeOfWord;
  5652. }
  5653. // Storage of string literal data from the initializing expression
  5654. // occurs here.
  5655. GenExpr();
  5656. }
  5657. }
  5658. else if (tok == '{')
  5659. {
  5660. // It's a function body. Let's add function parameters as
  5661. // local variables to the symbol table and parse the body.
  5662. word undoSymbolsPtr = SyntaxStackCnt;
  5663. word undoIdents = IdentTableLen;
  5664. word i;
  5665. word endLabel = 0;
  5666. if (doAnnotations)
  5667. {
  5668. DumpDecl(lastSyntaxPtr, 0);
  5669. }
  5670. CurFxnName = IdentTable + SyntaxStack1[lastSyntaxPtr];
  5671. IsMain = !strcmp(CurFxnName, "main");
  5672. gotoLabCnt = 0;
  5673. if (verbose)
  5674. {
  5675. printf(CurFxnName);
  5676. printf("()\n");
  5677. }
  5678. ParseLevel++;
  5679. GetFxnInfo(lastSyntaxPtr, &CurFxnParamCntMin, &CurFxnParamCntMax, &CurFxnReturnExprTypeSynPtr, NULL); // get return type
  5680. CurHeaderFooter = CodeHeaderFooter;
  5681. puts2(CurHeaderFooter[0]);
  5682. //BDOS_PrintlnConsole(CurFxnName);
  5683. //printf2("; put the function label here:\n");
  5684. GenLabel(CurFxnName, Static);
  5685. GenFxnProlog();
  5686. CurFxnEpilogLabel = LabelCnt++;
  5687. // A new scope begins before the function parameters
  5688. PushSyntax('#');
  5689. AddFxnParamSymbols(lastSyntaxPtr);
  5690. // The block doesn't begin yet another new scope.
  5691. // This is to catch redeclarations of the function parameters.
  5692. tok = ParseBlock(BrkCntTargetFxn, 0);
  5693. ParseLevel--;
  5694. if (tok != '}')
  5695. //error("ParseDecl(): '}' expected\n");
  5696. errorUnexpectedToken(tok);
  5697. for (i = 0; i < gotoLabCnt; i++)
  5698. if (gotoLabStat[i] == 2)
  5699. {
  5700. printf("Undeclared label ");
  5701. error(IdentTable + gotoLabels[i][0]);
  5702. }
  5703. // DONE: if execution of main() reaches here, before the epilog (i.e. without using return),
  5704. // main() should return 0.
  5705. if (IsMain)
  5706. {
  5707. sp = 0;
  5708. push(tokNumInt);
  5709. push(tokReturn); // value produced by generated code is used
  5710. GenExpr();
  5711. }
  5712. GenNumLabel(CurFxnEpilogLabel);
  5713. GenFxnEpilog();
  5714. if (GenFxnSizeNeeded())
  5715. GenNumLabel(endLabel = LabelCnt++);
  5716. puts2(CurHeaderFooter[1]);
  5717. CurHeaderFooter = NULL;
  5718. if (GenFxnSizeNeeded())
  5719. GenRecordFxnSize(CurFxnName, endLabel);
  5720. CurFxnName = NULL;
  5721. IdentTableLen = undoIdents; // remove all identifier names
  5722. SyntaxStackCnt = undoSymbolsPtr; // remove all params and locals
  5723. SyntaxStack1[SymFuncPtr] = DummyIdent;
  5724. }
  5725. else if (isFxn)
  5726. {
  5727. if (doAnnotations)
  5728. {
  5729. // function prototype
  5730. DumpDecl(lastSyntaxPtr, 0);
  5731. }
  5732. }
  5733. CheckRedecl(lastSyntaxPtr);
  5734. if ((tok == ';') | (tok == '}'))
  5735. break;
  5736. tok = GetToken();
  5737. continue;
  5738. }
  5739. //error("ParseDecl(): unexpected token %s\n", GetTokenName(tok));
  5740. errorUnexpectedToken(tok);
  5741. }
  5742. tok = GetToken();
  5743. return tok;
  5744. }
  5745. void ParseFxnParams(word tok)
  5746. {
  5747. word base[2];
  5748. word lastSyntaxPtr;
  5749. word cnt = 0;
  5750. word ellCnt = 0;
  5751. for (;;)
  5752. {
  5753. lastSyntaxPtr = SyntaxStackCnt;
  5754. if (tok == ')') /* unspecified params */
  5755. break;
  5756. if (!TokenStartsDeclaration(tok, 1))
  5757. {
  5758. if (tok == tokEllipsis)
  5759. {
  5760. // "..." cannot be the first parameter and
  5761. // it can be only one
  5762. if (!cnt || ellCnt)
  5763. //error("ParseFxnParams(): '...' unexpected here\n");
  5764. errorUnexpectedToken(tok);
  5765. ellCnt++;
  5766. }
  5767. else
  5768. //error("ParseFxnParams(): Unexpected token %s\n", GetTokenName(tok));
  5769. errorUnexpectedToken(tok);
  5770. base[0] = tok; // "..."
  5771. base[1] = 0;
  5772. PushSyntax2(tokIdent, AddIdent("<something>"));
  5773. tok = GetToken();
  5774. }
  5775. else
  5776. {
  5777. if (ellCnt)
  5778. //error("ParseFxnParams(): '...' must be the last in the parameter list\n");
  5779. errorUnexpectedToken(tok);
  5780. /* base type */
  5781. tok = ParseBase(tok, base);
  5782. /* derived type */
  5783. tok = ParseDerived(tok);
  5784. }
  5785. /* base type */
  5786. PushBase(base);
  5787. /* Decay arrays to pointers */
  5788. lastSyntaxPtr++; /* skip name */
  5789. if (SyntaxStack0[lastSyntaxPtr] == '[')
  5790. {
  5791. word t;
  5792. DeleteSyntax(lastSyntaxPtr, 1);
  5793. t = SyntaxStack0[lastSyntaxPtr];
  5794. if (t == tokNumInt || t == tokNumUint)
  5795. DeleteSyntax(lastSyntaxPtr, 1);
  5796. SyntaxStack0[lastSyntaxPtr] = '*';
  5797. }
  5798. /* "(Un)decay" functions to function pointers */
  5799. else if (SyntaxStack0[lastSyntaxPtr] == '(')
  5800. {
  5801. InsertSyntax(lastSyntaxPtr, '*');
  5802. }
  5803. lastSyntaxPtr--; /* "unskip" name */
  5804. cnt++;
  5805. if (tok == ')' || tok == ',')
  5806. {
  5807. word t = SyntaxStack0[SyntaxStackCnt - 2];
  5808. if (SyntaxStack0[SyntaxStackCnt - 1] == tokVoid)
  5809. {
  5810. // Disallow void variables. TBD!!! de-uglify
  5811. if (t == tokIdent &&
  5812. !(!strcmp(IdentTable + SyntaxStack1[SyntaxStackCnt - 2], "<something>") &&
  5813. cnt == 1 && tok == ')'))
  5814. //error("ParseFxnParams(): Cannot declare a variable ('%s') of type 'void'\n", IdentTable + SyntaxStack1[lastSyntaxPtr]);
  5815. errorUnexpectedVoid();
  5816. }
  5817. if (tok == ')')
  5818. break;
  5819. tok = GetToken();
  5820. continue;
  5821. }
  5822. //error("ParseFxnParams(): Unexpected token %s\n", GetTokenName(tok));
  5823. errorUnexpectedToken(tok);
  5824. }
  5825. }
  5826. void AddFxnParamSymbols(word SyntaxPtr)
  5827. {
  5828. word i;
  5829. unsigned paramOfs = 2 * SizeOfWord; // ret addr, xbp
  5830. if (SyntaxPtr < 0 ||
  5831. SyntaxPtr > SyntaxStackCnt - 3 ||
  5832. SyntaxStack0[SyntaxPtr] != tokIdent ||
  5833. SyntaxStack0[SyntaxPtr + 1] != '(')
  5834. //error("Internal error: AddFxnParamSymbols(): Invalid input\n");
  5835. errorInternal(6);
  5836. CurFxnSyntaxPtr = SyntaxPtr;
  5837. CurFxnLocalOfs = 0;
  5838. CurFxnMinLocalOfs = 0;
  5839. SyntaxPtr += 2; // skip "ident("
  5840. for (i = SyntaxPtr; i < SyntaxStackCnt; i++)
  5841. {
  5842. word tok = SyntaxStack0[i];
  5843. if (tok == tokIdent)
  5844. {
  5845. unsigned sz;
  5846. word paramPtr;
  5847. if (i + 1 >= SyntaxStackCnt)
  5848. //error("Internal error: AddFxnParamSymbols(): Invalid input\n");
  5849. errorInternal(7);
  5850. if (SyntaxStack0[i + 1] == tokVoid) // "ident(void)" = no params
  5851. break;
  5852. if (SyntaxStack0[i + 1] == tokEllipsis) // "ident(something,...)" = no more params
  5853. break;
  5854. // Make sure the parameter is not an incomplete structure
  5855. sz = GetDeclSize(i, 0);
  5856. if (sz == 0)
  5857. //error("Internal error: AddFxnParamSymbols(): GetDeclSize() = 0\n");
  5858. //errorInternal(8);
  5859. errorDecl();
  5860. // Let's calculate this parameter's relative on-stack location
  5861. paramPtr = SyntaxStackCnt;
  5862. PushSyntax2(SyntaxStack0[i], SyntaxStack1[i]);
  5863. PushSyntax2(tokLocalOfs, paramOfs);
  5864. if (sz + SizeOfWord - 1 < sz)
  5865. {
  5866. //printf("h");
  5867. errorVarSize();
  5868. }
  5869. sz = (sz + SizeOfWord - 1) & ~(SizeOfWord - 1u);
  5870. if (paramOfs + sz < paramOfs)
  5871. {
  5872. //printf("i");
  5873. errorVarSize();
  5874. }
  5875. paramOfs += sz;
  5876. if (paramOfs > (unsigned)GenMaxLocalsSize())
  5877. {
  5878. //printf("j");
  5879. errorVarSize();
  5880. }
  5881. // Duplicate this parameter in the symbol table
  5882. i++;
  5883. while (i < SyntaxStackCnt)
  5884. {
  5885. tok = SyntaxStack0[i];
  5886. if (tok == tokIdent || tok == ')')
  5887. {
  5888. if (doAnnotations)
  5889. {
  5890. DumpDecl(paramPtr, 0);
  5891. }
  5892. if (IdentTable[SyntaxStack1[paramPtr]] == '<')
  5893. error("Parameter name expected\n");
  5894. CheckRedecl(paramPtr);
  5895. i--;
  5896. break;
  5897. }
  5898. else if (tok == '(')
  5899. {
  5900. word c = 1;
  5901. i++;
  5902. PushSyntax(tok);
  5903. while (c && i < SyntaxStackCnt)
  5904. {
  5905. tok = SyntaxStack0[i];
  5906. c += (tok == '(') - (tok == ')');
  5907. PushSyntax2(SyntaxStack0[i], SyntaxStack1[i]);
  5908. i++;
  5909. }
  5910. }
  5911. else
  5912. {
  5913. PushSyntax2(SyntaxStack0[i], SyntaxStack1[i]);
  5914. i++;
  5915. }
  5916. }
  5917. }
  5918. else if (tok == ')') // endof "ident(" ... ")"
  5919. break;
  5920. else
  5921. //error("Internal error: AddFxnParamSymbols(): Unexpected token %s\n", GetTokenName(tok));
  5922. errorInternal(9);
  5923. }
  5924. }
  5925. word ParseStatement(word tok, word BrkCntTarget[2], word casesIdx)
  5926. {
  5927. /*
  5928. labeled statements:
  5929. + ident : statement
  5930. + case const-expr : statement
  5931. + default : statement
  5932. compound statement:
  5933. + { declaration(s)/statement(s)-opt }
  5934. expression statement:
  5935. + expression-opt ;
  5936. selection statements:
  5937. + if ( expression ) statement
  5938. + if ( expression ) statement else statement
  5939. + switch ( expression ) { statement(s)-opt }
  5940. iteration statements:
  5941. + while ( expression ) statement
  5942. + do statement while ( expression ) ;
  5943. + for ( expression-opt ; expression-opt ; expression-opt ) statement
  5944. jump statements:
  5945. + goto ident ;
  5946. + continue ;
  5947. + break ;
  5948. + return expression-opt ;
  5949. */
  5950. word gotUnary, synPtr, constExpr, exprVal;
  5951. word brkCntTarget[2];
  5952. word statementNeeded;
  5953. do
  5954. {
  5955. statementNeeded = 0;
  5956. if (tok == ';')
  5957. {
  5958. tok = GetToken();
  5959. }
  5960. else if (tok == '{')
  5961. {
  5962. // A new {} block begins in the function body
  5963. word undoSymbolsPtr = SyntaxStackCnt;
  5964. word undoLocalOfs = CurFxnLocalOfs;
  5965. word undoIdents = IdentTableLen;
  5966. if (doAnnotations)
  5967. {
  5968. GenStartCommentLine(); printf2("{\n");
  5969. }
  5970. ParseLevel++;
  5971. tok = ParseBlock(BrkCntTarget, casesIdx);
  5972. ParseLevel--;
  5973. if (tok != '}')
  5974. //error("ParseStatement(): '}' expected. Unexpected token %s\n", GetTokenName(tok));
  5975. errorUnexpectedToken(tok);
  5976. UndoNonLabelIdents(undoIdents); // remove all identifier names, except those of labels
  5977. SyntaxStackCnt = undoSymbolsPtr; // remove all params and locals
  5978. CurFxnLocalOfs = undoLocalOfs; // destroy on-stack local variables
  5979. if (doAnnotations)
  5980. {
  5981. GenStartCommentLine(); printf2("}\n");
  5982. }
  5983. tok = GetToken();
  5984. }
  5985. else if (tok == tokReturn)
  5986. {
  5987. // DONE: functions returning void vs non-void
  5988. word retVoid = CurFxnReturnExprTypeSynPtr >= 0 &&
  5989. SyntaxStack0[CurFxnReturnExprTypeSynPtr] == tokVoid;
  5990. if (doAnnotations)
  5991. {
  5992. GenStartCommentLine(); printf2("return\n");
  5993. }
  5994. tok = GetToken();
  5995. if (tok == ';')
  5996. {
  5997. gotUnary = 0;
  5998. if (!retVoid)
  5999. //error("ParseStatement(): missing return value\n");
  6000. errorUnexpectedToken(tok);
  6001. }
  6002. else
  6003. {
  6004. if (retVoid)
  6005. //error("Error: ParseStatement(): cannot return a value from a function returning 'void'\n");
  6006. errorUnexpectedToken(tok);
  6007. if ((tok = ParseExpr(tok, &gotUnary, &synPtr, &constExpr, &exprVal, 0, 0)) != ';')
  6008. //error("ParseStatement(): ';' expected\n");
  6009. errorUnexpectedToken(tok);
  6010. if (gotUnary)
  6011. //error("ParseStatement(): cannot return a value of type 'void'\n");
  6012. // Bar void
  6013. nonVoidTypeCheck(synPtr);
  6014. }
  6015. if (gotUnary)
  6016. {
  6017. decayArray(&synPtr, 0);
  6018. {
  6019. word castSize = GetDeclSize(CurFxnReturnExprTypeSynPtr, 1);
  6020. // If return value (per function declaration) is a scalar type smaller than machine word,
  6021. // properly zero- or sign-extend the returned value to machine word size.
  6022. // TBD??? Move this cast to the caller?
  6023. if (castSize != SizeOfWord && castSize != GetDeclSize(synPtr, 1))
  6024. {
  6025. if (constExpr)
  6026. {
  6027. switch (castSize)
  6028. {
  6029. case 1:
  6030. exprVal &= 0xFFu;
  6031. break;
  6032. case -1:
  6033. if ((exprVal &= 0xFFu) >= 0x80)
  6034. exprVal -= 0x100;
  6035. break;
  6036. case 2:
  6037. exprVal &= 0xFFFFu;
  6038. break;
  6039. case -2:
  6040. if ((exprVal &= 0xFFFFu) >= 0x8000)
  6041. exprVal -= 0x10000;
  6042. break;
  6043. }
  6044. }
  6045. else
  6046. {
  6047. switch (castSize)
  6048. {
  6049. case 1:
  6050. push(tokUChar);
  6051. break;
  6052. case -1:
  6053. push(tokSChar);
  6054. break;
  6055. case 2:
  6056. push(tokUShort);
  6057. break;
  6058. case -2:
  6059. push(tokShort);
  6060. break;
  6061. }
  6062. }
  6063. }
  6064. }
  6065. if (constExpr)
  6066. stack[0][1] = exprVal;
  6067. push(tokReturn); // value produced by generated code is used
  6068. GenExpr();
  6069. }
  6070. tok = GetToken();
  6071. // If this return is the last statement in the function, the epilogue immediately
  6072. // follows and there's no need to jump to it.
  6073. if (!(tok == '}' && ParseLevel == 1 && !IsMain))
  6074. GenJumpUncond(CurFxnEpilogLabel);
  6075. }
  6076. else if (tok == tokWhile)
  6077. {
  6078. word labelBefore = LabelCnt++;
  6079. word labelAfter = LabelCnt++;
  6080. word forever = 0;
  6081. if (doAnnotations)
  6082. {
  6083. GenStartCommentLine(); printf2("while\n");
  6084. }
  6085. tok = GetToken();
  6086. if (tok != '(')
  6087. //error("ParseStatement(): '(' expected after 'while'\n");
  6088. errorUnexpectedToken(tok);
  6089. tok = GetToken();
  6090. if ((tok = ParseExpr(tok, &gotUnary, &synPtr, &constExpr, &exprVal, 0, 0)) != ')')
  6091. //error("ParseStatement(): ')' expected after 'while ( expression'\n");
  6092. errorUnexpectedToken(tok);
  6093. if (!gotUnary)
  6094. //error("ParseStatement(): expression expected in 'while ( expression )'\n");
  6095. errorUnexpectedToken(tok);
  6096. // DONE: void control expressions
  6097. //error("ParseStatement(): unexpected 'void' expression in 'while ( expression )'\n");
  6098. // Bar void and struct/union
  6099. scalarTypeCheck(synPtr);
  6100. GenNumLabel(labelBefore);
  6101. if (constExpr)
  6102. {
  6103. // Special cases for while(0) and while(1)
  6104. if (!(forever = truncInt(exprVal)))
  6105. GenJumpUncond(labelAfter);
  6106. }
  6107. else
  6108. {
  6109. switch (stack[sp - 1][0])
  6110. {
  6111. case '<':
  6112. case '>':
  6113. case tokEQ:
  6114. case tokNEQ:
  6115. case tokLEQ:
  6116. case tokGEQ:
  6117. case tokULess:
  6118. case tokUGreater:
  6119. case tokULEQ:
  6120. case tokUGEQ:
  6121. push2(tokIfNot, labelAfter);
  6122. GenExpr();
  6123. break;
  6124. default:
  6125. push(tokReturn); // value produced by generated code is used
  6126. GenExpr();
  6127. GenJumpIfZero(labelAfter);
  6128. break;
  6129. }
  6130. }
  6131. tok = GetToken();
  6132. brkCntTarget[0] = labelAfter; // break target
  6133. brkCntTarget[1] = labelBefore; // continue target
  6134. tok = ParseStatement(tok, brkCntTarget, casesIdx);
  6135. // Special case for while(0)
  6136. if (!(constExpr && !forever))
  6137. GenJumpUncond(labelBefore);
  6138. GenNumLabel(labelAfter);
  6139. }
  6140. else if (tok == tokDo)
  6141. {
  6142. word labelBefore = LabelCnt++;
  6143. word labelWhile = LabelCnt++;
  6144. word labelAfter = LabelCnt++;
  6145. if (doAnnotations)
  6146. {
  6147. GenStartCommentLine(); printf2("do\n");
  6148. }
  6149. GenNumLabel(labelBefore);
  6150. tok = GetToken();
  6151. brkCntTarget[0] = labelAfter; // break target
  6152. brkCntTarget[1] = labelWhile; // continue target
  6153. tok = ParseStatement(tok, brkCntTarget, casesIdx);
  6154. if (tok != tokWhile)
  6155. //error("ParseStatement(): 'while' expected after 'do statement'\n");
  6156. errorUnexpectedToken(tok);
  6157. if (doAnnotations)
  6158. {
  6159. GenStartCommentLine(); printf2("while\n");
  6160. }
  6161. tok = GetToken();
  6162. if (tok != '(')
  6163. //error("ParseStatement(): '(' expected after 'while'\n");
  6164. errorUnexpectedToken(tok);
  6165. tok = GetToken();
  6166. if ((tok = ParseExpr(tok, &gotUnary, &synPtr, &constExpr, &exprVal, 0, 0)) != ')')
  6167. //error("ParseStatement(): ')' expected after 'while ( expression'\n");
  6168. errorUnexpectedToken(tok);
  6169. if (!gotUnary)
  6170. //error("ParseStatement(): expression expected in 'while ( expression )'\n");
  6171. errorUnexpectedToken(tok);
  6172. tok = GetToken();
  6173. if (tok != ';')
  6174. //error("ParseStatement(): ';' expected after 'do statement while ( expression )'\n");
  6175. errorUnexpectedToken(tok);
  6176. // DONE: void control expressions
  6177. //error("ParseStatement(): unexpected 'void' expression in 'while ( expression )'\n");
  6178. // Bar void and struct/union
  6179. scalarTypeCheck(synPtr);
  6180. GenNumLabel(labelWhile);
  6181. if (constExpr)
  6182. {
  6183. // Special cases for while(0) and while(1)
  6184. if (truncInt(exprVal))
  6185. GenJumpUncond(labelBefore);
  6186. }
  6187. else
  6188. {
  6189. switch (stack[sp - 1][0])
  6190. {
  6191. case '<':
  6192. case '>':
  6193. case tokEQ:
  6194. case tokNEQ:
  6195. case tokLEQ:
  6196. case tokGEQ:
  6197. case tokULess:
  6198. case tokUGreater:
  6199. case tokULEQ:
  6200. case tokUGEQ:
  6201. push2(tokIf, labelBefore);
  6202. GenExpr();
  6203. break;
  6204. default:
  6205. push(tokReturn); // value produced by generated code is used
  6206. GenExpr();
  6207. GenJumpIfNotZero(labelBefore);
  6208. break;
  6209. }
  6210. }
  6211. GenNumLabel(labelAfter);
  6212. tok = GetToken();
  6213. }
  6214. else if (tok == tokIf)
  6215. {
  6216. word labelAfterIf = LabelCnt++;
  6217. word labelAfterElse = LabelCnt++;
  6218. if (doAnnotations)
  6219. {
  6220. GenStartCommentLine(); printf2("if\n");
  6221. }
  6222. tok = GetToken();
  6223. if (tok != '(')
  6224. //error("ParseStatement(): '(' expected after 'if'\n");
  6225. errorUnexpectedToken(tok);
  6226. tok = GetToken();
  6227. if ((tok = ParseExpr(tok, &gotUnary, &synPtr, &constExpr, &exprVal, 0, 0)) != ')')
  6228. //error("ParseStatement(): ')' expected after 'if ( expression'\n");
  6229. errorUnexpectedToken(tok);
  6230. if (!gotUnary)
  6231. //error("ParseStatement(): expression expected in 'if ( expression )'\n");
  6232. errorUnexpectedToken(tok);
  6233. // DONE: void control expressions
  6234. //error("ParseStatement(): unexpected 'void' expression in 'if ( expression )'\n");
  6235. // Bar void and struct/union
  6236. scalarTypeCheck(synPtr);
  6237. if (constExpr)
  6238. {
  6239. // Special cases for if(0) and if(1)
  6240. if (!truncInt(exprVal))
  6241. GenJumpUncond(labelAfterIf);
  6242. }
  6243. else
  6244. {
  6245. switch (stack[sp - 1][0])
  6246. {
  6247. case '<':
  6248. case '>':
  6249. case tokEQ:
  6250. case tokNEQ:
  6251. case tokLEQ:
  6252. case tokGEQ:
  6253. case tokULess:
  6254. case tokUGreater:
  6255. case tokULEQ:
  6256. case tokUGEQ:
  6257. push2(tokIfNot, labelAfterIf);
  6258. GenExpr();
  6259. break;
  6260. default:
  6261. push(tokReturn); // value produced by generated code is used
  6262. GenExpr();
  6263. GenJumpIfZero(labelAfterIf);
  6264. break;
  6265. }
  6266. }
  6267. tok = GetToken();
  6268. tok = ParseStatement(tok, BrkCntTarget, casesIdx);
  6269. // DONE: else
  6270. if (tok == tokElse)
  6271. {
  6272. GenJumpUncond(labelAfterElse);
  6273. GenNumLabel(labelAfterIf);
  6274. if (doAnnotations)
  6275. {
  6276. GenStartCommentLine(); printf2("else\n");
  6277. }
  6278. tok = GetToken();
  6279. tok = ParseStatement(tok, BrkCntTarget, casesIdx);
  6280. GenNumLabel(labelAfterElse);
  6281. }
  6282. else
  6283. {
  6284. GenNumLabel(labelAfterIf);
  6285. }
  6286. }
  6287. else if (tok == tokFor)
  6288. {
  6289. word labelBefore = LabelCnt++;
  6290. word labelExpr3 = LabelCnt++;
  6291. word labelBody = LabelCnt++;
  6292. word labelAfter = LabelCnt++;
  6293. word cond = -1;
  6294. static word expr3Stack[STACK_SIZE >> 1][2];
  6295. static word expr3Sp;
  6296. if (doAnnotations)
  6297. {
  6298. GenStartCommentLine(); printf2("for\n");
  6299. }
  6300. tok = GetToken();
  6301. if (tok != '(')
  6302. //error("ParseStatement(): '(' expected after 'for'\n");
  6303. errorUnexpectedToken(tok);
  6304. tok = GetToken();
  6305. {
  6306. if ((tok = ParseExpr(tok, &gotUnary, &synPtr, &constExpr, &exprVal, 0, 0)) != ';')
  6307. //error("ParseStatement(): ';' expected after 'for ( expression'\n");
  6308. errorUnexpectedToken(tok);
  6309. if (gotUnary)
  6310. {
  6311. GenExpr();
  6312. }
  6313. tok = GetToken();
  6314. }
  6315. GenNumLabel(labelBefore);
  6316. if ((tok = ParseExpr(tok, &gotUnary, &synPtr, &constExpr, &exprVal, 0, 0)) != ';')
  6317. //error("ParseStatement(): ';' expected after 'for ( expression ; expression'\n");
  6318. errorUnexpectedToken(tok);
  6319. if (gotUnary)
  6320. {
  6321. // DONE: void control expressions
  6322. //error("ParseStatement(): unexpected 'void' expression in 'for ( ; expression ; )'\n");
  6323. // Bar void and struct/union
  6324. scalarTypeCheck(synPtr);
  6325. if (constExpr)
  6326. {
  6327. // Special cases for for(...; 0; ...) and for(...; 1; ...)
  6328. cond = truncInt(exprVal) != 0;
  6329. }
  6330. else
  6331. {
  6332. switch (stack[sp - 1][0])
  6333. {
  6334. case '<':
  6335. case '>':
  6336. case tokEQ:
  6337. case tokNEQ:
  6338. case tokLEQ:
  6339. case tokGEQ:
  6340. case tokULess:
  6341. case tokUGreater:
  6342. case tokULEQ:
  6343. case tokUGEQ:
  6344. push2(tokIfNot, labelAfter);
  6345. GenExpr();
  6346. break;
  6347. default:
  6348. push(tokReturn); // value produced by generated code is used
  6349. GenExpr();
  6350. GenJumpIfZero(labelAfter);
  6351. break;
  6352. }
  6353. }
  6354. }
  6355. else
  6356. {
  6357. // Special case for for(...; ; ...)
  6358. cond = 1;
  6359. }
  6360. if (!cond)
  6361. // Special case for for(...; 0; ...)
  6362. GenJumpUncond(labelAfter);
  6363. tok = GetToken();
  6364. if ((tok = ParseExpr(tok, &gotUnary, &synPtr, &constExpr, &exprVal, 0, 0)) != ')')
  6365. //error("ParseStatement(): ')' expected after 'for ( expression ; expression ; expression'\n");
  6366. errorUnexpectedToken(tok);
  6367. // Try to reorder expr3 with body to reduce the number of jumps, favor small expr3's
  6368. if (gotUnary && sp <= 16 && (unsigned)sp <= division(sizeof expr3Stack , sizeof expr3Stack[0]) - expr3Sp)
  6369. {
  6370. word cnt = sp;
  6371. // Stash the stack containing expr3
  6372. memcpy(expr3Stack + expr3Sp, stack, cnt * sizeof stack[0]);
  6373. expr3Sp += cnt;
  6374. // Body
  6375. tok = GetToken();
  6376. brkCntTarget[0] = labelAfter; // break target
  6377. brkCntTarget[1] = labelExpr3; // continue target
  6378. tok = ParseStatement(tok, brkCntTarget, casesIdx);
  6379. // Unstash expr3 and generate code for it
  6380. expr3Sp -= cnt;
  6381. memcpy(stack, expr3Stack + expr3Sp, cnt * sizeof stack[0]);
  6382. sp = cnt;
  6383. GenNumLabel(labelExpr3);
  6384. GenExpr();
  6385. // Special case for for(...; 0; ...)
  6386. if (cond)
  6387. GenJumpUncond(labelBefore);
  6388. }
  6389. else
  6390. {
  6391. if (gotUnary)
  6392. {
  6393. GenJumpUncond(labelBody);
  6394. // expr3
  6395. GenNumLabel(labelExpr3);
  6396. GenExpr();
  6397. GenJumpUncond(labelBefore);
  6398. GenNumLabel(labelBody);
  6399. }
  6400. // Body
  6401. tok = GetToken();
  6402. brkCntTarget[0] = labelAfter; // break target
  6403. brkCntTarget[1] = gotUnary ? labelExpr3 : (cond ? labelBefore : labelAfter); // continue target
  6404. tok = ParseStatement(tok, brkCntTarget, casesIdx);
  6405. // Special case for for(...; 0; ...)
  6406. if (brkCntTarget[1] != labelAfter)
  6407. GenJumpUncond(brkCntTarget[1]);
  6408. }
  6409. GenNumLabel(labelAfter);
  6410. }
  6411. else if (tok == tokBreak)
  6412. {
  6413. if (doAnnotations)
  6414. {
  6415. GenStartCommentLine(); printf2("break\n");
  6416. }
  6417. if ((tok = GetToken()) != ';')
  6418. //error("ParseStatement(): ';' expected\n");
  6419. errorUnexpectedToken(tok);
  6420. tok = GetToken();
  6421. if (BrkCntTarget == NULL)
  6422. //error("ParseStatement(): 'break' must be within 'while', 'for' or 'switch' statement\n");
  6423. errorCtrlOutOfScope();
  6424. GenJumpUncond(BrkCntTarget[0]);
  6425. }
  6426. else if (tok == tokCont)
  6427. {
  6428. if (doAnnotations)
  6429. {
  6430. GenStartCommentLine(); printf2("continue\n");
  6431. }
  6432. if ((tok = GetToken()) != ';')
  6433. //error("ParseStatement(): ';' expected\n");
  6434. errorUnexpectedToken(tok);
  6435. tok = GetToken();
  6436. if (BrkCntTarget == NULL || BrkCntTarget[1] == 0)
  6437. //error("ParseStatement(): 'continue' must be within 'while' or 'for' statement\n");
  6438. errorCtrlOutOfScope();
  6439. GenJumpUncond(BrkCntTarget[1]);
  6440. }
  6441. else if (tok == tokSwitch)
  6442. {
  6443. word undoCases = CasesCnt;
  6444. word brkLabel = LabelCnt++;
  6445. word lbl = LabelCnt++;
  6446. word i;
  6447. if (doAnnotations)
  6448. {
  6449. GenStartCommentLine(); printf2("switch\n");
  6450. }
  6451. tok = GetToken();
  6452. if (tok != '(')
  6453. //error("ParseStatement(): '(' expected after 'switch'\n");
  6454. errorUnexpectedToken(tok);
  6455. tok = GetToken();
  6456. if ((tok = ParseExpr(tok, &gotUnary, &synPtr, &constExpr, &exprVal, 0, 0)) != ')')
  6457. //error("ParseStatement(): ')' expected after 'switch ( expression'\n");
  6458. errorUnexpectedToken(tok);
  6459. if (!gotUnary)
  6460. //error("ParseStatement(): expression expected in 'switch ( expression )'\n");
  6461. errorUnexpectedToken(tok);
  6462. // DONE: void control expressions
  6463. //error("ParseStatement(): unexpected 'void' expression in 'switch ( expression )'\n");
  6464. anyIntTypeCheck(synPtr);
  6465. push(tokReturn); // value produced by generated code is used
  6466. GenExpr();
  6467. tok = GetToken();
  6468. // Skip the code for the cases
  6469. GenJumpUncond(lbl);
  6470. brkCntTarget[0] = brkLabel; // break target
  6471. brkCntTarget[1] = 0; // continue target
  6472. if (BrkCntTarget)
  6473. {
  6474. // Preserve the continue target
  6475. brkCntTarget[1] = BrkCntTarget[1]; // continue target
  6476. }
  6477. // Reserve a slot in the case table for the default label
  6478. AddCase(0, 0);
  6479. tok = ParseStatement(tok, brkCntTarget, CasesCnt);
  6480. // If there's no default target, will use the break target as default
  6481. if (!Cases[undoCases][1])
  6482. Cases[undoCases][1] = brkLabel;
  6483. // End of switch reached (not via break), skip conditional jumps
  6484. GenJumpUncond(brkLabel);
  6485. // Generate conditional jumps
  6486. GenNumLabel(lbl);
  6487. for (i = undoCases + 1; i < CasesCnt; i++)
  6488. {
  6489. GenJumpIfEqual(Cases[i][0], Cases[i][1]);
  6490. }
  6491. // If none of the cases matches, take the default case
  6492. if (Cases[undoCases][1] != brkLabel)
  6493. GenJumpUncond(Cases[undoCases][1]);
  6494. GenNumLabel(brkLabel); // break label
  6495. CasesCnt = undoCases;
  6496. }
  6497. else if (tok == tokCase)
  6498. {
  6499. word i;
  6500. if (doAnnotations)
  6501. {
  6502. GenStartCommentLine(); printf2("case\n");
  6503. }
  6504. if (!casesIdx)
  6505. //error("ParseStatement(): 'case' must be within 'switch' statement\n");
  6506. errorCtrlOutOfScope();
  6507. tok = GetToken();
  6508. if ((tok = ParseExpr(tok, &gotUnary, &synPtr, &constExpr, &exprVal, 0, 0)) != ':')
  6509. //error("ParseStatement(): ':' expected after 'case expression'\n");
  6510. errorUnexpectedToken(tok);
  6511. if (!gotUnary)
  6512. errorUnexpectedToken(tok);
  6513. anyIntTypeCheck(synPtr);
  6514. if (!constExpr)
  6515. //error("ParseStatement(): constant integer expression expected in 'case expression :'\n");
  6516. errorNotConst();
  6517. // Check for dups
  6518. exprVal = truncInt(exprVal);
  6519. for (i = casesIdx; i < CasesCnt; i++)
  6520. if (Cases[i][0] == exprVal)
  6521. error("Duplicate case value\n");
  6522. AddCase(exprVal, LabelCnt);
  6523. GenNumLabel(LabelCnt++); // case exprVal:
  6524. tok = GetToken();
  6525. // a statement is needed after "case:"
  6526. statementNeeded = 1;
  6527. }
  6528. else if (tok == tokDefault)
  6529. {
  6530. if (doAnnotations)
  6531. {
  6532. GenStartCommentLine(); printf2("default\n");
  6533. }
  6534. if (!casesIdx)
  6535. //error("ParseStatement(): 'default' must be within 'switch' statement\n");
  6536. errorCtrlOutOfScope();
  6537. if (Cases[casesIdx - 1][1])
  6538. //error("ParseStatement(): only one 'default' allowed in 'switch'\n");
  6539. errorUnexpectedToken(tok);
  6540. tok = GetToken();
  6541. if (tok != ':')
  6542. //error("ParseStatement(): ':' expected after 'default'\n");
  6543. errorUnexpectedToken(tok);
  6544. tok = GetToken();
  6545. GenNumLabel(Cases[casesIdx - 1][1] = LabelCnt++); // default:
  6546. // a statement is needed after "default:"
  6547. statementNeeded = 1;
  6548. }
  6549. else if (tok == tok_Asm)
  6550. {
  6551. tok = GetToken();
  6552. if (tok != '(')
  6553. //error("ParseStatement(): '(' expected after 'asm'\n");
  6554. errorUnexpectedToken(tok);
  6555. tok = GetToken();
  6556. if (tok != tokLitStr)
  6557. //error("ParseStatement(): string literal expression expected in 'asm ( expression )'\n");
  6558. errorUnexpectedToken(tok);
  6559. do
  6560. {
  6561. GetString('"', 0, 'a');
  6562. tok = GetToken();
  6563. } while (tok == tokLitStr); // concatenate adjacent string literals
  6564. printf2("\n");
  6565. if (tok != ')')
  6566. //error("ParseStatement(): ')' expected after 'asm ( expression'\n");
  6567. errorUnexpectedToken(tok);
  6568. tok = GetToken();
  6569. if (tok != ';')
  6570. //error("ParseStatement(): ';' expected after 'asm ( expression )'\n");
  6571. errorUnexpectedToken(tok);
  6572. tok = GetToken();
  6573. }
  6574. else if (tok == tokGoto)
  6575. {
  6576. if ((tok = GetToken()) != tokIdent)
  6577. errorUnexpectedToken(tok);
  6578. GenStartCommentLine();
  6579. if (doAnnotations)
  6580. {
  6581. printf2("goto ");
  6582. printf2(TokenIdentName);
  6583. printf2("\n");
  6584. }
  6585. GenJumpUncond(AddGotoLabel(TokenIdentName, 0));
  6586. if ((tok = GetToken()) != ';')
  6587. errorUnexpectedToken(tok);
  6588. tok = GetToken();
  6589. }
  6590. else
  6591. {
  6592. tok = ParseExpr(tok, &gotUnary, &synPtr, &constExpr, &exprVal, tokGotoLabel, 0);
  6593. if (tok == tokGotoLabel)
  6594. {
  6595. // found a label
  6596. if (doAnnotations)
  6597. {
  6598. GenStartCommentLine();
  6599. printf2(IdentTable + stack[0][1]);
  6600. printf2(":\n");
  6601. }
  6602. GenNumLabel(AddGotoLabel(IdentTable + stack[0][1], 1));
  6603. // a statement is needed after "label:"
  6604. statementNeeded = 1;
  6605. }
  6606. else
  6607. {
  6608. if (tok != ';')
  6609. //error("ParseStatement(): ';' expected\n");
  6610. errorUnexpectedToken(tok);
  6611. if (gotUnary)
  6612. GenExpr();
  6613. }
  6614. tok = GetToken();
  6615. }
  6616. } while (statementNeeded);
  6617. return tok;
  6618. }
  6619. // TBD!!! think of ways of getting rid of casesIdx
  6620. word ParseBlock(word BrkCntTarget[2], word casesIdx)
  6621. {
  6622. word tok = GetToken();
  6623. // Catch redeclarations of function parameters by not
  6624. // beginning a new scope if this block begins a function
  6625. // (the caller of ParseBlock() must've begun a new scope
  6626. // already, before the function parameters).
  6627. if (BrkCntTarget == BrkCntTargetFxn)
  6628. BrkCntTarget = NULL;
  6629. else
  6630. // Otherwise begin a new scope.
  6631. PushSyntax('#');
  6632. for (;;)
  6633. {
  6634. if (tok == 0)
  6635. return tok;
  6636. if (tok == '}' && ParseLevel > 0)
  6637. return tok;
  6638. if (TokenStartsDeclaration(tok, 0))
  6639. {
  6640. tok = ParseDecl(tok, NULL, 0, 1);
  6641. }
  6642. else if (ParseLevel > 0 || tok == tok_Asm)
  6643. {
  6644. tok = ParseStatement(tok, BrkCntTarget, casesIdx);
  6645. }
  6646. else
  6647. //error("ParseBlock(): Unexpected token %s\n", GetTokenName(tok));
  6648. errorUnexpectedToken(tok);
  6649. }
  6650. }
  6651. int main()
  6652. {
  6653. printf("BCC Compiler\n");
  6654. // Run-time initializer for SyntaxStack0[] to reduce
  6655. // executable file size (SyntaxStack0[] will be in .bss)
  6656. static unsigned char SyntaxStackInit[] =
  6657. {
  6658. tokVoid, // SymVoidSynPtr
  6659. tokInt, // SymIntSynPtr
  6660. tokUnsigned, // SymUintSynPtr
  6661. tokVoid, // SymWideCharSynPtr
  6662. tokFloat, // SymFloatSynPtr
  6663. tokIdent, // SymFuncPtr
  6664. '[',
  6665. tokNumUint,
  6666. ']',
  6667. tokChar
  6668. }; // SyntaxStackCnt must be initialized to the number of elements in SyntaxStackInit[]
  6669. memcpy(SyntaxStack0, SyntaxStackInit, sizeof SyntaxStackInit);
  6670. SyntaxStackCnt = 10;
  6671. SyntaxStack1[SymFuncPtr] = DummyIdent = AddIdent("");
  6672. GenInit();
  6673. // TODO: add BDOS path to filenames if not absolute path
  6674. compileOS = 0;
  6675. compileUserBDOS = 1;
  6676. char infilename[64];
  6677. BDOS_GetArgN(1, infilename);
  6678. if (infilename[0] == 0)
  6679. {
  6680. strcat(infilename, BDOS_GetPath());
  6681. if (infilename[strlen(infilename)-1] != '/')
  6682. {
  6683. strcat(infilename, "/");
  6684. }
  6685. strcat(infilename, "CODE.C");
  6686. //strcpy(infilename, "/TEST/TEST.C");
  6687. }
  6688. if (infilename[0] != '/')
  6689. {
  6690. char bothPath[64];
  6691. bothPath[0] = 0;
  6692. strcat(bothPath, BDOS_GetPath());
  6693. if (bothPath[strlen(bothPath)-1] != '/')
  6694. {
  6695. strcat(bothPath, "/");
  6696. }
  6697. strcat(bothPath, infilename);
  6698. strcpy(infilename, bothPath);
  6699. }
  6700. if (FileCnt == 0)
  6701. {
  6702. // If it's none of the known options,
  6703. // assume it's the source code file name
  6704. if (strlen(infilename) > MAX_FILE_NAME_LEN)
  6705. {
  6706. //error("File name too long\n");
  6707. errorFileName();
  6708. }
  6709. strcpy(FileNames[0], infilename);
  6710. Files[0] = fopen(FileNames[0], 0);
  6711. if (fcanopen(Files[0]) == EOF)
  6712. {
  6713. //error("Cannot open file \"%s\"\n", FileNames[0]);
  6714. errorFile(FileNames[0]);
  6715. }
  6716. else
  6717. {
  6718. //printf("Opened input file\n");
  6719. }
  6720. LineNos[0] = LineNo;
  6721. LinePoss[0] = LinePos;
  6722. FileCnt++;
  6723. }
  6724. char outfilename[64];
  6725. BDOS_GetArgN(2, outfilename);
  6726. if (outfilename[0] == 0)
  6727. {
  6728. strcat(outfilename, BDOS_GetPath());
  6729. if (outfilename[strlen(outfilename)-1] != '/')
  6730. {
  6731. strcat(outfilename, "/");
  6732. }
  6733. strcat(outfilename, "OUT.ASM");
  6734. //strcpy(outfilename, "/TEST/A.OUT");
  6735. }
  6736. if (outfilename[0] != '/')
  6737. {
  6738. char bothPath[64];
  6739. bothPath[0] = 0;
  6740. strcat(bothPath, BDOS_GetPath());
  6741. if (bothPath[strlen(bothPath)-1] != '/')
  6742. {
  6743. strcat(bothPath, "/");
  6744. }
  6745. strcat(bothPath, outfilename);
  6746. strcpy(outfilename, bothPath);
  6747. }
  6748. if (FileCnt == 1 && OutFile == NULL)
  6749. {
  6750. // This should be the output file name
  6751. OutFile = fopen(outfilename, 1);
  6752. if (fcanopen(OutFile) == EOF)
  6753. {
  6754. //error("Cannot open output file \"%s\"\n", argv[i]);
  6755. errorFile(outfilename);
  6756. }
  6757. else
  6758. {
  6759. //printf("Opened output file\n");
  6760. }
  6761. }
  6762. if (!FileCnt)
  6763. error("Input file not specified\n");
  6764. if (!OutFile)
  6765. error("Output file not specified\n");
  6766. GenInitFinalize();
  6767. // Define a few macros useful for conditional compilation
  6768. /*
  6769. DefineMacro("__SMALLER_C__", "0x0100");
  6770. DefineMacro("__SMALLER_C_32__", "");
  6771. DefineMacro("__SMALLER_C_SCHAR__", "");
  6772. */
  6773. // populate CharQueue[] with the initial file characters
  6774. ShiftChar();
  6775. puts2(FileHeader);
  6776. // compile
  6777. ParseBlock(NULL, 0);
  6778. GenFin();
  6779. if (doAnnotations)
  6780. {
  6781. DumpSynDecls();
  6782. DumpMacroTable();
  6783. DumpIdentTable();
  6784. }
  6785. /*
  6786. GenStartCommentLine();
  6787. printf2("Next label number: ");
  6788. printd2(LabelCnt);
  6789. printf2("\n");
  6790. */
  6791. //GenStartCommentLine();
  6792. printf("Finished compiling\n");
  6793. if (OutFile)
  6794. fclose(OutFile);
  6795. return 'q';
  6796. }
  6797. void interrupt()
  6798. {
  6799. }