bcc.c 206 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951
  1. /*
  2. Copyright (c) 2021, b4rt-dev
  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. if (!ConstExpr[1])
  2363. return !div0;
  2364. if (Unsigned)
  2365. {
  2366. sl = (word)truncUint(sl);
  2367. sr = (word)truncUint(sr);
  2368. }
  2369. else
  2370. {
  2371. sl = truncInt(sl);
  2372. sr = truncInt(sr);
  2373. }
  2374. if (sr == 0)
  2375. {
  2376. div0 = 1;
  2377. }
  2378. else if (!ConstExpr[0])
  2379. {
  2380. return !div0;
  2381. }
  2382. else if (!Unsigned && ((sl == INT_MIN && sr == -1) || division(sl , sr) != truncInt(division(sl , sr))))
  2383. {
  2384. div0 = 1;
  2385. }
  2386. else
  2387. {
  2388. if (Unsigned)
  2389. {
  2390. if (tok == '/')
  2391. sl = (word)((unsigned)division(sl , sr));
  2392. else
  2393. sl = (word)((unsigned)modulo(sl , sr));
  2394. }
  2395. else
  2396. {
  2397. // TBD!!! C89 gives freedom in how exactly division of negative integers
  2398. // can be implemented w.r.t. rounding and w.r.t. the sign of the remainder.
  2399. // A stricter, C99-conforming implementation, non-dependent on the
  2400. // compiler used to compile Smaller C is needed.
  2401. if (tok == '/')
  2402. sl = division(sl, sr);
  2403. else
  2404. sl = modulo(sl, sr);
  2405. }
  2406. *psl = sl;
  2407. }
  2408. if (div0)
  2409. warning("Division by 0 or division overflow\n");
  2410. return !div0;
  2411. }
  2412. void promoteType(word* ExprTypeSynPtr, word* TheOtherExprTypeSynPtr)
  2413. {
  2414. // Integer promotion to signed int or unsigned int from smaller types
  2415. // (all kinds of char and short). Promotion to unsigned int occurs
  2416. // only if the other operand (of a binary operator) is already an
  2417. // unsigned int. Effectively, this promotion to unsigned int performs
  2418. // usual arithmetic conversion for integers.
  2419. if (*ExprTypeSynPtr >= 0)
  2420. {
  2421. // chars must be promoted to ints in expressions as the very first thing
  2422. switch (SyntaxStack0[*ExprTypeSynPtr])
  2423. {
  2424. case tokChar:
  2425. case tokShort:
  2426. case tokUShort:
  2427. case tokSChar:
  2428. case tokUChar:
  2429. *ExprTypeSynPtr = SymIntSynPtr;
  2430. }
  2431. if (*TheOtherExprTypeSynPtr >= 0)
  2432. {
  2433. // ints must be converted to unsigned ints if they are used in binary
  2434. // operators whose other operand is unsigned int (except <<,>>,<<=,>>=)
  2435. if (SyntaxStack0[*ExprTypeSynPtr] == tokInt &&
  2436. SyntaxStack0[*TheOtherExprTypeSynPtr] == tokUnsigned)
  2437. *ExprTypeSynPtr = SymUintSynPtr;
  2438. }
  2439. }
  2440. }
  2441. word GetFxnInfo(word ExprTypeSynPtr, word* MinParams, word* MaxParams, word* ReturnExprTypeSynPtr, word* FirstParamSynPtr)
  2442. {
  2443. *MaxParams = *MinParams = 0;
  2444. if (ExprTypeSynPtr < 0)
  2445. {
  2446. ExprTypeSynPtr = -ExprTypeSynPtr;
  2447. }
  2448. else
  2449. {
  2450. while (SyntaxStack0[ExprTypeSynPtr] == tokIdent || SyntaxStack0[ExprTypeSynPtr] == tokLocalOfs)
  2451. ExprTypeSynPtr++;
  2452. if (SyntaxStack0[ExprTypeSynPtr] == '*')
  2453. ExprTypeSynPtr++;
  2454. }
  2455. if (SyntaxStack0[ExprTypeSynPtr] != '(')
  2456. return 0;
  2457. // DONE: return syntax pointer to the function's return type
  2458. // Count params
  2459. ExprTypeSynPtr++;
  2460. if (FirstParamSynPtr)
  2461. *FirstParamSynPtr = ExprTypeSynPtr;
  2462. if (SyntaxStack0[ExprTypeSynPtr] == ')')
  2463. {
  2464. // "fxn()": unspecified parameters, so, there can be any number of them
  2465. *MaxParams = 32767; // INT_MAX;
  2466. *ReturnExprTypeSynPtr = ExprTypeSynPtr + 1;
  2467. return 1;
  2468. }
  2469. if (SyntaxStack0[ExprTypeSynPtr + 1] == tokVoid)
  2470. {
  2471. // "fxn(void)": 0 parameters
  2472. *ReturnExprTypeSynPtr = ExprTypeSynPtr + 3;
  2473. return 1;
  2474. }
  2475. for (;;)
  2476. {
  2477. word tok = SyntaxStack0[ExprTypeSynPtr];
  2478. if (tok == tokIdent)
  2479. {
  2480. if (SyntaxStack0[ExprTypeSynPtr + 1] != tokEllipsis)
  2481. {
  2482. ++*MinParams;
  2483. ++*MaxParams;
  2484. }
  2485. else
  2486. {
  2487. *MaxParams = 32767; // INT_MAX;
  2488. }
  2489. }
  2490. else if (tok == '(')
  2491. {
  2492. // skip parameters in parameters
  2493. word c = 1;
  2494. while (c && ExprTypeSynPtr < SyntaxStackCnt)
  2495. {
  2496. tok = SyntaxStack0[++ExprTypeSynPtr];
  2497. c += (tok == '(') - (tok == ')');
  2498. }
  2499. }
  2500. else if (tok == ')')
  2501. {
  2502. ExprTypeSynPtr++;
  2503. break;
  2504. }
  2505. ExprTypeSynPtr++;
  2506. }
  2507. // get the function's return type
  2508. *ReturnExprTypeSynPtr = ExprTypeSynPtr;
  2509. return 1;
  2510. }
  2511. void simplifyConstExpr(word val, word isConst, word* ExprTypeSynPtr, word top, word bottom)
  2512. {
  2513. // If non-const, nothing to do.
  2514. // If const and already a number behind the scenes, nothing to do
  2515. // (val must not differ from the number!).
  2516. if (!isConst || stack[top][0] == tokNumInt || stack[top][0] == tokNumUint)
  2517. return;
  2518. // Const, but not a number yet. Reduce to a number equal val.
  2519. if (SyntaxStack0[*ExprTypeSynPtr] == tokUnsigned)
  2520. stack[top][0] = tokNumUint;
  2521. else
  2522. stack[top][0] = tokNumInt;
  2523. stack[top][1] = val;
  2524. del(bottom, top - bottom);
  2525. }
  2526. word AllocLocal(unsigned size)
  2527. {
  2528. // Let's calculate variable's relative on-stack location
  2529. word oldOfs = CurFxnLocalOfs;
  2530. // Note: local vars are word-aligned on the stack
  2531. CurFxnLocalOfs = (word)((CurFxnLocalOfs - size) & ~(SizeOfWord - 1u));
  2532. if (CurFxnLocalOfs >= oldOfs ||
  2533. CurFxnLocalOfs != truncInt(CurFxnLocalOfs) ||
  2534. (unsigned int)CurFxnLocalOfs < (unsigned int) (-GenMaxLocalsSize()))
  2535. //error("AllocLocal(): Local variables take too much space\n");
  2536. {
  2537. //printf("a");
  2538. errorVarSize();
  2539. }
  2540. if (CurFxnMinLocalOfs > CurFxnLocalOfs)
  2541. CurFxnMinLocalOfs = CurFxnLocalOfs;
  2542. return CurFxnLocalOfs;
  2543. }
  2544. // DONE: sizeof(type)
  2545. // DONE: "sizeof expr"
  2546. // DONE: constant expressions
  2547. // DONE: collapse constant subexpressions into constants
  2548. word exprval(word* idx, word* ExprTypeSynPtr, word* ConstExpr)
  2549. {
  2550. word tok;
  2551. word s;
  2552. word RightExprTypeSynPtr;
  2553. word oldIdxRight;
  2554. word oldSpRight;
  2555. word constExpr[3];
  2556. if (*idx < 0)
  2557. //error("exprval(): idx < 0\n");
  2558. errorInternal(5);
  2559. tok = stack[*idx][0];
  2560. s = stack[*idx][1];
  2561. --*idx;
  2562. oldIdxRight = *idx;
  2563. oldSpRight = sp;
  2564. switch (tok)
  2565. {
  2566. // Constants
  2567. case tokNumInt:
  2568. // return the constant's type: int
  2569. *ExprTypeSynPtr = SymIntSynPtr;
  2570. *ConstExpr = 1;
  2571. break;
  2572. case tokNumUint:
  2573. // return the constant's type: unsigned int
  2574. *ExprTypeSynPtr = SymUintSynPtr;
  2575. *ConstExpr = 1;
  2576. break;
  2577. // Identifiers
  2578. case tokIdent:
  2579. {
  2580. // DONE: support __func__
  2581. char* ident = IdentTable + s;
  2582. word synPtr, type;
  2583. {
  2584. synPtr = FindSymbol(ident);
  2585. // "Rename" static vars in function scope
  2586. if (synPtr >= 0 && synPtr + 1 < SyntaxStackCnt && SyntaxStack0[synPtr + 1] == tokIdent)
  2587. {
  2588. s = stack[*idx + 1][1] = SyntaxStack1[++synPtr];
  2589. ident = IdentTable + s;
  2590. }
  2591. }
  2592. if (synPtr < 0)
  2593. {
  2594. if ((*idx + 2 >= sp) || stack[*idx + 2][0] != ')')
  2595. {
  2596. printf("Undeclared identifier ");
  2597. error(ident);
  2598. }
  2599. else
  2600. {
  2601. // silent this warning for now, since it seems to trigger false positives
  2602. //printf("Call to undeclared function ");
  2603. //warning(ident);
  2604. // Implicitly declare "extern int ident();"
  2605. PushSyntax2(tokIdent, s);
  2606. PushSyntax('(');
  2607. PushSyntax(')');
  2608. PushSyntax(tokInt);
  2609. synPtr = FindSymbol(ident);
  2610. }
  2611. }
  2612. // DONE: this declaration is actually a type cast
  2613. if (!strncmp(IdentTable + SyntaxStack1[synPtr], "(something", sizeof "(something)" - 1 - 1))
  2614. {
  2615. word castSize;
  2616. if (SyntaxStack0[++synPtr] == tokLocalOfs) // TBD!!! is this really needed???
  2617. synPtr++;
  2618. s = exprval(idx, ExprTypeSynPtr, ConstExpr);
  2619. // can't cast void or structure/union to anything (except void)
  2620. if (*ExprTypeSynPtr >= 0 &&
  2621. (SyntaxStack0[*ExprTypeSynPtr] == tokVoid ||
  2622. SyntaxStack0[*ExprTypeSynPtr] == tokStructPtr) &&
  2623. SyntaxStack0[synPtr] != tokVoid)
  2624. errorOpType();
  2625. // can't cast to function, array or structure/union
  2626. if (SyntaxStack0[synPtr] == '(' ||
  2627. SyntaxStack0[synPtr] == '[' ||
  2628. SyntaxStack0[synPtr] == tokStructPtr)
  2629. errorOpType();
  2630. // will try to propagate constants through casts
  2631. if (!*ConstExpr &&
  2632. (stack[oldIdxRight - (oldSpRight - sp)][0] == tokNumInt ||
  2633. stack[oldIdxRight - (oldSpRight - sp)][0] == tokNumUint))
  2634. {
  2635. s = stack[oldIdxRight - (oldSpRight - sp)][1];
  2636. *ConstExpr = 1;
  2637. }
  2638. castSize = GetDeclSize(synPtr, 1); // 0 for cast to void
  2639. // insertion of tokUChar, tokSChar and tokUnaryPlus transforms
  2640. // lvalues (values formed by dereferences) into rvalues
  2641. // (by hiding the dereferences), just as casts should do
  2642. switch (castSize)
  2643. {
  2644. case 1:
  2645. // cast to unsigned char
  2646. stack[oldIdxRight + 1 - (oldSpRight - sp)][0] = tokUChar;
  2647. s &= 0xFFu;
  2648. break;
  2649. case -1:
  2650. // cast to signed char
  2651. stack[oldIdxRight + 1 - (oldSpRight - sp)][0] = tokSChar;
  2652. if ((s &= 0xFFu) >= 0x80)
  2653. s -= 0x100;
  2654. break;
  2655. default:
  2656. if (castSize && castSize != SizeOfWord)
  2657. {
  2658. // cast not to void and not to word-sized type (int/unsigned/pointer/float)
  2659. if (castSize == 2)
  2660. {
  2661. // cast to unsigned short
  2662. stack[oldIdxRight + 1 - (oldSpRight - sp)][0] = tokUShort;
  2663. s &= 0xFFFFu;
  2664. }
  2665. else
  2666. {
  2667. // cast to signed short
  2668. stack[oldIdxRight + 1 - (oldSpRight - sp)][0] = tokShort;
  2669. if ((s &= 0xFFFFu) >= 0x8000)
  2670. s -= 0x10000;
  2671. }
  2672. }
  2673. else // fallthrough
  2674. {
  2675. // cast to void or word-sized type (int/unsigned/pointer/float)
  2676. if (stack[oldIdxRight - (oldSpRight - sp)][0] == tokUnaryStar)
  2677. // hide the dereference
  2678. stack[oldIdxRight + 1 - (oldSpRight - sp)][0] = tokUnaryPlus;
  2679. }
  2680. break;
  2681. }
  2682. if (*ConstExpr)
  2683. stack[oldIdxRight - (oldSpRight - sp)][1] = s;
  2684. *ExprTypeSynPtr = synPtr;
  2685. simplifyConstExpr(s, *ConstExpr, ExprTypeSynPtr, oldIdxRight + 1 - (oldSpRight - sp), *idx + 1);
  2686. if (!*ConstExpr && stack[oldIdxRight + 1 - (oldSpRight - sp)][0] == tokIdent)
  2687. // nothing to hide, remove the cast
  2688. del(oldIdxRight + 1 - (oldSpRight - sp), 1);
  2689. switch (SyntaxStack0[synPtr])
  2690. {
  2691. case tokChar:
  2692. case tokSChar:
  2693. case tokUChar:
  2694. case tokShort:
  2695. case tokUShort:
  2696. case tokInt:
  2697. case tokUnsigned:
  2698. break;
  2699. default:
  2700. // only numeric types can be const
  2701. *ConstExpr = 0;
  2702. break;
  2703. }
  2704. break;
  2705. }
  2706. // Finally, not __func__, not enum, not cast.
  2707. type = SymType(synPtr);
  2708. if (type == SymLocalVar || type == SymLocalArr)
  2709. {
  2710. // replace local variables/arrays with their local addresses
  2711. // (global variables/arrays' addresses are their names)
  2712. stack[*idx + 1][0] = tokLocalOfs;
  2713. stack[*idx + 1][1] = SyntaxStack1[synPtr + 1];
  2714. }
  2715. if (type == SymLocalVar || type == SymGlobalVar)
  2716. {
  2717. // add implicit dereferences for local/global variables
  2718. ins2(*idx + 2, tokUnaryStar, GetDeclSize(synPtr, 1));
  2719. }
  2720. // return the identifier's type
  2721. while (SyntaxStack0[synPtr] == tokIdent || SyntaxStack0[synPtr] == tokLocalOfs)
  2722. synPtr++;
  2723. *ExprTypeSynPtr = synPtr;
  2724. }
  2725. *ConstExpr = 0;
  2726. break;
  2727. // sizeof operator
  2728. case tokSizeof:
  2729. exprval(idx, ExprTypeSynPtr, ConstExpr);
  2730. s = GetDeclSize(*ExprTypeSynPtr, 0);
  2731. if (s == 0)
  2732. error("sizeof of incomplete type\n");
  2733. // replace sizeof with its numeric value
  2734. stack[oldIdxRight + 1 - (oldSpRight - sp)][0] = tokNumUint;
  2735. stack[oldIdxRight + 1 - (oldSpRight - sp)][1] = s;
  2736. // remove the sizeof's subexpression
  2737. del(*idx + 1, oldIdxRight - (oldSpRight - sp) - *idx);
  2738. *ExprTypeSynPtr = SymUintSynPtr;
  2739. *ConstExpr = 1;
  2740. break;
  2741. // Address unary operator
  2742. case tokUnaryAnd:
  2743. exprval(idx, ExprTypeSynPtr, ConstExpr);
  2744. if (*ExprTypeSynPtr >= 0 &&
  2745. (SyntaxStack0[*ExprTypeSynPtr] == '[' || SyntaxStack0[*ExprTypeSynPtr] == '('))
  2746. {
  2747. // convert an array into a pointer to the array,
  2748. // convert a function into a pointer to the function,
  2749. // remove the reference
  2750. del(oldIdxRight + 1 - (oldSpRight - sp), 1);
  2751. }
  2752. else if (*ExprTypeSynPtr >= 0 &&
  2753. stack[oldIdxRight - (oldSpRight - sp)][0] == tokUnaryStar)
  2754. {
  2755. // it's an lvalue (with implicit or explicit dereference),
  2756. // convert it into its address by
  2757. // collapsing/removing the reference and the dereference
  2758. del(oldIdxRight - (oldSpRight - sp), 2);
  2759. }
  2760. else
  2761. //error("exprval(): lvalue expected after '&'\n");
  2762. errorNotLvalue();
  2763. // we cannot insert another '*' into the type to make it a pointer
  2764. // to an array/function/etc, so make the index into the type negative
  2765. *ExprTypeSynPtr = -*ExprTypeSynPtr;
  2766. *ConstExpr = 0;
  2767. break;
  2768. // Indirection unary operator
  2769. case tokUnaryStar:
  2770. exprval(idx, ExprTypeSynPtr, ConstExpr);
  2771. if (*ExprTypeSynPtr < 0 || SyntaxStack0[*ExprTypeSynPtr] == '*')
  2772. {
  2773. // type is a pointer to something,
  2774. // transform it into that something
  2775. if (*ExprTypeSynPtr < 0)
  2776. *ExprTypeSynPtr = -*ExprTypeSynPtr;
  2777. else
  2778. ++*ExprTypeSynPtr;
  2779. nonVoidTypeCheck(*ExprTypeSynPtr);
  2780. if (SyntaxStack0[*ExprTypeSynPtr] == tokStructPtr && !GetDeclSize(*ExprTypeSynPtr, 0))
  2781. // incomplete structure/union type
  2782. errorOpType();
  2783. // remove the dereference if that something is an array or a function
  2784. if (SyntaxStack0[*ExprTypeSynPtr] == '[' ||
  2785. SyntaxStack0[*ExprTypeSynPtr] == '(')
  2786. del(oldIdxRight + 1 - (oldSpRight - sp), 1);
  2787. // else attach dereference size in bytes
  2788. else
  2789. stack[oldIdxRight + 1 - (oldSpRight - sp)][1] = GetDeclSize(*ExprTypeSynPtr, 1);
  2790. }
  2791. else if (SyntaxStack0[*ExprTypeSynPtr] == '[')
  2792. {
  2793. // type is an array,
  2794. // transform it into the array's first element
  2795. // (a subarray, if type is a multidimensional array)
  2796. (*ExprTypeSynPtr) += 3;
  2797. // remove the dereference if that element is an array
  2798. if (SyntaxStack0[*ExprTypeSynPtr] == '[')
  2799. del(oldIdxRight + 1 - (oldSpRight - sp), 1);
  2800. // else attach dereference size in bytes
  2801. else
  2802. stack[oldIdxRight + 1 - (oldSpRight - sp)][1] = GetDeclSize(*ExprTypeSynPtr, 1);
  2803. }
  2804. else
  2805. //error("exprval(): pointer/array expected after '*' / before '[]'\n");
  2806. errorOpType();
  2807. *ConstExpr = 0;
  2808. break;
  2809. // Additive binary operators
  2810. case '+':
  2811. case '-':
  2812. // WRONGISH: DONE: replace prefix ++/-- with +=1/-=1
  2813. // WRONG: DONE: replace postfix ++/-- with (+=1)-1/(-=1)+1
  2814. {
  2815. word ptrmask;
  2816. word oldIdxLeft, oldSpLeft;
  2817. word sl, sr;
  2818. word incSize;
  2819. sr = exprval(idx, &RightExprTypeSynPtr, &constExpr[1]);
  2820. oldIdxLeft = *idx;
  2821. oldSpLeft = sp;
  2822. sl = exprval(idx, ExprTypeSynPtr, &constExpr[0]);
  2823. // Decay arrays to pointers to their first elements
  2824. // and ensure that the pointers are suitable for pointer arithmetic
  2825. // (not pointers to functions, sizes of pointees are known and non-zero)
  2826. decayArray(&RightExprTypeSynPtr, 1);
  2827. decayArray(ExprTypeSynPtr, 1);
  2828. // Bar void and struct/union
  2829. scalarTypeCheck(RightExprTypeSynPtr);
  2830. scalarTypeCheck(*ExprTypeSynPtr);
  2831. ptrmask = isAnyPtr(RightExprTypeSynPtr) + isAnyPtr(*ExprTypeSynPtr) * 2;
  2832. // DONE: index/subscript scaling
  2833. if (ptrmask == 1 && tok == '+') // pointer in right-hand expression
  2834. {
  2835. incSize = GetDeclSize(derefAnyPtr(RightExprTypeSynPtr), 0);
  2836. if (constExpr[0]) // integer constant in left-hand expression
  2837. {
  2838. s = (word)((unsigned)sl * incSize);
  2839. stack[oldIdxLeft - (oldSpLeft - sp)][1] = s;
  2840. // optimize a little if possible
  2841. {
  2842. word i = oldIdxRight - (oldSpRight - sp);
  2843. // Skip any type cast markers
  2844. while (stack[i][0] == tokUnaryPlus || stack[i][0] == '+')
  2845. i--;
  2846. // See if the pointer is an integer constant or a local variable offset
  2847. // and if it is, adjust it here instead of generating code for
  2848. // addition/subtraction
  2849. if (stack[i][0] == tokNumInt || stack[i][0] == tokNumUint || stack[i][0] == tokLocalOfs)
  2850. {
  2851. s = (word)((unsigned)stack[i][1] + s);
  2852. stack[i][1] = s; // TBD!!! need extra truncation?
  2853. del(oldIdxLeft - (oldSpLeft - sp), 1);
  2854. del(oldIdxRight - (oldSpRight - sp) + 1, 1);
  2855. }
  2856. }
  2857. }
  2858. else if (incSize != 1)
  2859. {
  2860. ins2(oldIdxLeft + 1 - (oldSpLeft - sp), tokNumInt, incSize);
  2861. ins(oldIdxLeft + 1 - (oldSpLeft - sp), '*');
  2862. }
  2863. *ExprTypeSynPtr = RightExprTypeSynPtr;
  2864. }
  2865. else if (ptrmask == 2) // pointer in left-hand expression
  2866. {
  2867. incSize = GetDeclSize(derefAnyPtr(*ExprTypeSynPtr), 0);
  2868. if (constExpr[1]) // integer constant in right-hand expression
  2869. {
  2870. s = (word)((unsigned)sr * incSize);
  2871. stack[oldIdxRight - (oldSpRight - sp)][1] = s;
  2872. // optimize a little if possible
  2873. {
  2874. word i = oldIdxLeft - (oldSpLeft - sp);
  2875. // Skip any type cast markers
  2876. while (stack[i][0] == tokUnaryPlus || stack[i][0] == '+')
  2877. i--;
  2878. // See if the pointer is an integer constant or a local variable offset
  2879. // and if it is, adjust it here instead of generating code for
  2880. // addition/subtraction
  2881. if (stack[i][0] == tokNumInt || stack[i][0] == tokNumUint || stack[i][0] == tokLocalOfs)
  2882. {
  2883. if (tok == '-')
  2884. s = (word)~(s - 1u);
  2885. s = (word)((unsigned)stack[i][1] + s);
  2886. stack[i][1] = s; // TBD!!! need extra truncation?
  2887. del(oldIdxRight - (oldSpRight - sp), 2);
  2888. }
  2889. }
  2890. }
  2891. else if (incSize != 1)
  2892. {
  2893. ins2(oldIdxRight + 1 - (oldSpRight - sp), tokNumInt, incSize);
  2894. ins(oldIdxRight + 1 - (oldSpRight - sp), '*');
  2895. }
  2896. }
  2897. else if (ptrmask == 3 && tok == '-') // pointers in both expressions
  2898. {
  2899. incSize = GetDeclSize(derefAnyPtr(*ExprTypeSynPtr), 0);
  2900. // TBD!!! "ptr1-ptr2": better pointer type compatibility test needed, like compatCheck()?
  2901. if (incSize != GetDeclSize(derefAnyPtr(RightExprTypeSynPtr), 0))
  2902. //error("exprval(): incompatible pointers\n");
  2903. errorOpType();
  2904. if (incSize != 1)
  2905. {
  2906. ins2(oldIdxRight + 2 - (oldSpRight - sp), tokNumInt, incSize);
  2907. ins(oldIdxRight + 2 - (oldSpRight - sp), '/');
  2908. }
  2909. *ExprTypeSynPtr = SymIntSynPtr;
  2910. }
  2911. else if (ptrmask)
  2912. //error("exprval(): invalid combination of operands for '+' or '-'\n");
  2913. errorOpType();
  2914. // Promote the result from char to int (and from int to unsigned) if necessary
  2915. promoteType(ExprTypeSynPtr, &RightExprTypeSynPtr);
  2916. *ConstExpr = constExpr[0] && constExpr[1];
  2917. {
  2918. if (tok == '+')
  2919. s = (word)((unsigned)sl + sr);
  2920. else
  2921. s = (word)((unsigned)sl - sr);
  2922. }
  2923. simplifyConstExpr(s, *ConstExpr, ExprTypeSynPtr, oldIdxRight + 1 - (oldSpRight - sp), *idx + 1);
  2924. }
  2925. break;
  2926. // Prefix/postfix increment/decrement unary operators
  2927. case tokInc:
  2928. case tokDec:
  2929. case tokPostInc:
  2930. case tokPostDec:
  2931. {
  2932. word incSize = 1;
  2933. word inc = tok == tokInc || tok == tokPostInc;
  2934. word post = tok == tokPostInc || tok == tokPostDec;
  2935. word opSize;
  2936. exprval(idx, ExprTypeSynPtr, ConstExpr);
  2937. lvalueCheck(*ExprTypeSynPtr, oldIdxRight - (oldSpRight - sp));
  2938. // if it's a pointer, ensure that it's suitable for pointer arithmetic
  2939. // (not pointer to function, pointee size is known and non-zero)
  2940. decayArray(ExprTypeSynPtr, 1); // no actual decay here, just a type check
  2941. // Bar void and struct/union
  2942. scalarTypeCheck(*ExprTypeSynPtr);
  2943. // "remove" the lvalue dereference as we don't need
  2944. // to read the value while forgetting its location.
  2945. // We need to keep the lvalue location.
  2946. // Remember the operand size.
  2947. opSize = stack[oldIdxRight - (oldSpRight - sp)][1];
  2948. del(oldIdxRight - (oldSpRight - sp), 1);
  2949. if (isAnyPtr(*ExprTypeSynPtr))
  2950. incSize = GetDeclSize(derefAnyPtr(*ExprTypeSynPtr), 0);
  2951. if (incSize == 1)
  2952. {
  2953. // store the operand size in the operator
  2954. stack[oldIdxRight + 1 - (oldSpRight - sp)][1] = opSize;
  2955. }
  2956. else
  2957. {
  2958. // replace ++/-- with "postfix" +=/-= incSize when incSize != 1
  2959. stack[oldIdxRight + 1 - (oldSpRight - sp)][0] =
  2960. inc ? (post ? tokPostAdd : tokAssignAdd) :
  2961. (post ? tokPostSub : tokAssignSub);
  2962. // store the operand size in the operator
  2963. stack[oldIdxRight + 1 - (oldSpRight - sp)][1] = opSize;
  2964. ins2(oldIdxRight + 1 - (oldSpRight - sp), tokNumInt, incSize);
  2965. }
  2966. *ConstExpr = 0;
  2967. }
  2968. break;
  2969. // Simple assignment binary operator
  2970. case '=':
  2971. {
  2972. word oldIdxLeft, oldSpLeft;
  2973. word opSize;
  2974. word structs;
  2975. exprval(idx, &RightExprTypeSynPtr, &constExpr[1]);
  2976. oldIdxLeft = *idx;
  2977. oldSpLeft = sp;
  2978. exprval(idx, ExprTypeSynPtr, &constExpr[0]);
  2979. lvalueCheck(*ExprTypeSynPtr, oldIdxLeft - (oldSpLeft - sp));
  2980. nonVoidTypeCheck(RightExprTypeSynPtr);
  2981. nonVoidTypeCheck(*ExprTypeSynPtr);
  2982. structs = (*ExprTypeSynPtr >= 0 && SyntaxStack0[*ExprTypeSynPtr] == tokStructPtr) * 2 +
  2983. (RightExprTypeSynPtr >= 0 && SyntaxStack0[RightExprTypeSynPtr] == tokStructPtr);
  2984. if (structs)
  2985. {
  2986. word sz;
  2987. if (structs != 3 ||
  2988. SyntaxStack1[RightExprTypeSynPtr] != SyntaxStack1[*ExprTypeSynPtr])
  2989. errorOpType();
  2990. // TBD??? (a = b) should be an rvalue and so &(a = b) and (&(a = b))->c shouldn't be
  2991. // allowed, while (a = b).c should be allowed.
  2992. // transform "*psleft = *psright" into "*fxn(sizeof *psright, psright, psleft)"
  2993. /*
  2994. if (stack[oldIdxLeft - (oldSpLeft - sp)][0] != tokUnaryStar ||
  2995. stack[oldIdxRight - (oldSpRight - sp)][0] != tokUnaryStar)
  2996. errorInternal(18);
  2997. */
  2998. stack[oldIdxLeft - (oldSpLeft - sp)][0] = ','; // replace '*' with ','
  2999. stack[oldIdxRight - (oldSpRight - sp)][0] = ','; // replace '*' with ','
  3000. sz = GetDeclSize(RightExprTypeSynPtr, 0);
  3001. stack[oldIdxRight + 1 - (oldSpRight - sp)][0] = tokNumUint; // replace '=' with "sizeof *psright"
  3002. stack[oldIdxRight + 1 - (oldSpRight - sp)][1] = sz;
  3003. ins(oldIdxRight + 2 - (oldSpRight - sp), ',');
  3004. if (!StructCpyLabel)
  3005. StructCpyLabel = LabelCnt++;
  3006. ins2(oldIdxRight + 2 - (oldSpRight - sp), tokIdent, AddNumericIdent(StructCpyLabel));
  3007. ins2(oldIdxRight + 2 - (oldSpRight - sp), ')', SizeOfWord * 3);
  3008. ins2(oldIdxRight + 2 - (oldSpRight - sp), tokUnaryStar, 0); // use 0 deref size to drop meaningless dereferences
  3009. ins2(*idx + 1, '(', SizeOfWord * 3);
  3010. }
  3011. else
  3012. {
  3013. // "remove" the lvalue dereference as we don't need
  3014. // to read the value while forgetting its location.
  3015. // We need to keep the lvalue location.
  3016. // Remember the operand size.
  3017. opSize = stack[oldIdxLeft - (oldSpLeft - sp)][1];
  3018. // store the operand size in the operator
  3019. stack[oldIdxRight + 1 - (oldSpRight - sp)][1] = opSize;
  3020. del(oldIdxLeft - (oldSpLeft - sp), 1);
  3021. }
  3022. *ConstExpr = 0;
  3023. }
  3024. break;
  3025. // DONE: other assignment operators
  3026. // Arithmetic and bitwise unary operators
  3027. case '~':
  3028. case tokUnaryPlus:
  3029. case tokUnaryMinus:
  3030. s = exprval(idx, ExprTypeSynPtr, ConstExpr);
  3031. numericTypeCheck(*ExprTypeSynPtr);
  3032. promoteType(ExprTypeSynPtr, ExprTypeSynPtr);
  3033. switch (tok)
  3034. {
  3035. case '~':
  3036. s = ~s;
  3037. break;
  3038. case tokUnaryPlus:
  3039. break;
  3040. case tokUnaryMinus:
  3041. {
  3042. s = (word)~(s - 1u);
  3043. }
  3044. break;
  3045. }
  3046. simplifyConstExpr(s, *ConstExpr, ExprTypeSynPtr, oldIdxRight + 1 - (oldSpRight - sp), *idx + 1);
  3047. break;
  3048. // Arithmetic and bitwise binary operators
  3049. case '*':
  3050. case '/':
  3051. case '%':
  3052. case tokLShift:
  3053. case tokRShift:
  3054. case '&':
  3055. case '^':
  3056. case '|':
  3057. {
  3058. word sr, sl;
  3059. word Unsigned;
  3060. sr = exprval(idx, &RightExprTypeSynPtr, &constExpr[1]);
  3061. sl = exprval(idx, ExprTypeSynPtr, &constExpr[0]);
  3062. numericTypeCheck(RightExprTypeSynPtr);
  3063. numericTypeCheck(*ExprTypeSynPtr);
  3064. *ConstExpr = constExpr[0] && constExpr[1];
  3065. Unsigned = SyntaxStack0[*ExprTypeSynPtr] == tokUnsigned || SyntaxStack0[RightExprTypeSynPtr] == tokUnsigned;
  3066. {
  3067. switch (tok)
  3068. {
  3069. // DONE: check for division overflows
  3070. case '/':
  3071. case '%':
  3072. *ConstExpr &= divCheckAndCalc(tok, &sl, sr, Unsigned, constExpr);
  3073. if (Unsigned)
  3074. {
  3075. if (tok == '/')
  3076. stack[oldIdxRight + 1 - (oldSpRight - sp)][0] = tokUDiv;
  3077. else
  3078. stack[oldIdxRight + 1 - (oldSpRight - sp)][0] = tokUMod;
  3079. }
  3080. break;
  3081. case '*':
  3082. sl = (word)((unsigned)sl * sr);
  3083. break;
  3084. case tokLShift:
  3085. case tokRShift:
  3086. if (constExpr[1])
  3087. {
  3088. if (SyntaxStack0[RightExprTypeSynPtr] != tokUnsigned)
  3089. sr = truncInt(sr);
  3090. else
  3091. sr = (word)truncUint(sr);
  3092. shiftCountCheck(&sr, oldIdxRight - (oldSpRight - sp), RightExprTypeSynPtr);
  3093. }
  3094. if (*ConstExpr)
  3095. {
  3096. if (tok == tokLShift)
  3097. {
  3098. // left shift is the same for signed and unsigned ints
  3099. sl = (word)((unsigned)sl << sr);
  3100. }
  3101. else
  3102. {
  3103. if (SyntaxStack0[*ExprTypeSynPtr] == tokUnsigned)
  3104. {
  3105. // right shift for unsigned ints
  3106. sl = (word)(truncUint(sl) >> sr);
  3107. }
  3108. else if (sr)
  3109. {
  3110. // right shift for signed ints is arithmetic, sign-bit-preserving
  3111. // don't depend on the compiler's implementation, do it "manually"
  3112. sl = truncInt(sl);
  3113. sl = (word)((truncUint(sl) >> sr) |
  3114. ((sl < 0) * (~0u << (8 * SizeOfWord - sr))));
  3115. }
  3116. }
  3117. }
  3118. if (SyntaxStack0[*ExprTypeSynPtr] == tokUnsigned && tok == tokRShift)
  3119. stack[oldIdxRight + 1 - (oldSpRight - sp)][0] = tokURShift;
  3120. // ignore RightExprTypeSynPtr for the purpose of promotion/conversion of the result of <</>>
  3121. RightExprTypeSynPtr = SymIntSynPtr;
  3122. break;
  3123. case '&': sl &= sr; break;
  3124. case '^': sl ^= sr; break;
  3125. case '|': sl |= sr; break;
  3126. }
  3127. s = sl;
  3128. }
  3129. promoteType(ExprTypeSynPtr, &RightExprTypeSynPtr);
  3130. simplifyConstExpr(s, *ConstExpr, ExprTypeSynPtr, oldIdxRight + 1 - (oldSpRight - sp), *idx + 1);
  3131. }
  3132. break;
  3133. // Relational and equality binary operators
  3134. // DONE: add (sub)tokens for unsigned >, >=, <, <= for pointers
  3135. case '<':
  3136. case '>':
  3137. case tokLEQ:
  3138. case tokGEQ:
  3139. case tokEQ:
  3140. case tokNEQ:
  3141. {
  3142. word ptrmask;
  3143. word sr, sl;
  3144. sr = exprval(idx, &RightExprTypeSynPtr, &constExpr[1]);
  3145. sl = exprval(idx, ExprTypeSynPtr, &constExpr[0]);
  3146. // Bar void and struct/union
  3147. scalarTypeCheck(RightExprTypeSynPtr);
  3148. scalarTypeCheck(*ExprTypeSynPtr);
  3149. ptrmask = isAnyPtr(RightExprTypeSynPtr) + isAnyPtr(*ExprTypeSynPtr) * 2;
  3150. // TBD??? stricter type checks???
  3151. if (tok != tokEQ && tok != tokNEQ)
  3152. {
  3153. // Disallow >, <, >=, <= between a pointer and a number
  3154. if (ptrmask == 1 || ptrmask == 2)
  3155. //error("exprval(): Invalid/unsupported combination of compared operands\n");
  3156. errorOpType();
  3157. // Disallow >, <, >=, <= with pointers to functions
  3158. if (((ptrmask & 1) && SyntaxStack0[derefAnyPtr(RightExprTypeSynPtr)] == '(') ||
  3159. ((ptrmask & 2) && SyntaxStack0[derefAnyPtr(*ExprTypeSynPtr)] == '('))
  3160. errorOpType();
  3161. }
  3162. else
  3163. {
  3164. // Disallow == and != between a pointer and a number other than constant 0 (AKA NULL)
  3165. if ((ptrmask == 1 && !(constExpr[0] && !truncInt(sl))) ||
  3166. (ptrmask == 2 && !(constExpr[1] && !truncInt(sr))))
  3167. errorOpType();
  3168. }
  3169. *ConstExpr = constExpr[0] && constExpr[1];
  3170. {
  3171. word Unsigned = isUint(*ExprTypeSynPtr) || isUint(RightExprTypeSynPtr);
  3172. if (*ConstExpr)
  3173. {
  3174. if (!Unsigned)
  3175. {
  3176. sl = truncInt(sl);
  3177. sr = truncInt(sr);
  3178. switch (tok)
  3179. {
  3180. case '<': sl = sl < sr; break;
  3181. case '>': sl = sl > sr; break;
  3182. case tokLEQ: sl = sl <= sr; break;
  3183. case tokGEQ: sl = sl >= sr; break;
  3184. case tokEQ: sl = sl == sr; break;
  3185. case tokNEQ: sl = sl != sr; break;
  3186. }
  3187. }
  3188. else
  3189. {
  3190. sl = (word)truncUint(sl);
  3191. sr = (word)truncUint(sr);
  3192. switch (tok)
  3193. {
  3194. case '<': sl = (unsigned)sl < (unsigned)sr; break;
  3195. case '>': sl = (unsigned)sl > (unsigned)sr; break;
  3196. case tokLEQ: sl = (unsigned)sl <= (unsigned)sr; break;
  3197. case tokGEQ: sl = (unsigned)sl >= (unsigned)sr; break;
  3198. case tokEQ: sl = sl == sr; break;
  3199. case tokNEQ: sl = sl != sr; break;
  3200. }
  3201. }
  3202. }
  3203. if (ptrmask || Unsigned)
  3204. {
  3205. // Pointer comparison should be unsigned
  3206. word t = tok;
  3207. switch (tok)
  3208. {
  3209. case '<': t = tokULess; break;
  3210. case '>': t = tokUGreater; break;
  3211. case tokLEQ: t = tokULEQ; break;
  3212. case tokGEQ: t = tokUGEQ; break;
  3213. }
  3214. stack[oldIdxRight + 1 - (oldSpRight - sp)][0] = t;
  3215. }
  3216. }
  3217. s = sl;
  3218. *ExprTypeSynPtr = SymIntSynPtr;
  3219. simplifyConstExpr(s, *ConstExpr, ExprTypeSynPtr, oldIdxRight + 1 - (oldSpRight - sp), *idx + 1);
  3220. }
  3221. break;
  3222. // implicit pseudo-conversion to _Bool of operands of && and ||
  3223. case tok_Bool:
  3224. s = exprval(idx, ExprTypeSynPtr, ConstExpr);
  3225. // Bar void and struct/union
  3226. scalarTypeCheck(*ExprTypeSynPtr);
  3227. {
  3228. s = truncInt(s) != 0;
  3229. }
  3230. *ExprTypeSynPtr = SymIntSynPtr;
  3231. simplifyConstExpr(s, *ConstExpr, ExprTypeSynPtr, oldIdxRight + 1 - (oldSpRight - sp), *idx + 1);
  3232. break;
  3233. // Logical binary operators
  3234. case tokLogAnd: // DONE: short-circuit
  3235. case tokLogOr: // DONE: short-circuit
  3236. {
  3237. word sr, sl;
  3238. // DONE: think of pushing a special short-circuit (jump-to) token
  3239. // to skip the rhs operand evaluation in && and ||
  3240. // DONE: add implicit "casts to _Bool" of && and || operands,
  3241. // do the same for control statements of if() while() and for(;;).
  3242. word sc = LabelCnt++;
  3243. // tag the logical operator as a numbered short-circuit jump target
  3244. stack[*idx + 1][1] = sc;
  3245. // insert "!= 0" for right-hand operand
  3246. switch (stack[*idx][0])
  3247. {
  3248. case '<':
  3249. case tokULess:
  3250. case '>':
  3251. case tokUGreater:
  3252. case tokLEQ:
  3253. case tokULEQ:
  3254. case tokGEQ:
  3255. case tokUGEQ:
  3256. case tokEQ:
  3257. case tokNEQ:
  3258. break;
  3259. default:
  3260. ins(++*idx, tok_Bool);
  3261. break;
  3262. }
  3263. sr = exprval(idx, &RightExprTypeSynPtr, &constExpr[1]);
  3264. // insert a reference to the short-circuit jump target
  3265. if (tok == tokLogAnd)
  3266. ins2(++*idx, tokShortCirc, sc);
  3267. else
  3268. ins2(++*idx, tokShortCirc, -sc);
  3269. // insert "!= 0" for left-hand operand
  3270. switch (stack[*idx - 1][0])
  3271. {
  3272. case '<':
  3273. case tokULess:
  3274. case '>':
  3275. case tokUGreater:
  3276. case tokLEQ:
  3277. case tokULEQ:
  3278. case tokGEQ:
  3279. case tokUGEQ:
  3280. case tokEQ:
  3281. case tokNEQ:
  3282. --*idx;
  3283. break;
  3284. default:
  3285. ins(*idx, tok_Bool);
  3286. break;
  3287. }
  3288. sl = exprval(idx, ExprTypeSynPtr, &constExpr[0]);
  3289. if (tok == tokLogAnd)
  3290. s = sl && sr;
  3291. else
  3292. s = sl || sr;
  3293. *ExprTypeSynPtr = SymIntSynPtr;
  3294. *ConstExpr = constExpr[0] && constExpr[1];
  3295. if (constExpr[0])
  3296. {
  3297. if (tok == tokLogAnd)
  3298. {
  3299. if (!sl)
  3300. *ConstExpr = 1, s = 0;
  3301. // TBD??? else can drop LHS expression
  3302. }
  3303. else
  3304. {
  3305. if (sl)
  3306. *ConstExpr = s = 1;
  3307. // TBD??? else can drop LHS expression
  3308. }
  3309. }
  3310. simplifyConstExpr(s, *ConstExpr, ExprTypeSynPtr, oldIdxRight + 1 - (oldSpRight - sp), *idx + 1);
  3311. }
  3312. break;
  3313. // Function call
  3314. case ')':
  3315. {
  3316. word tmpSynPtr, c;
  3317. word minParams, maxParams;
  3318. word firstParamSynPtr;
  3319. word oldIdx, oldSp;
  3320. exprval(idx, ExprTypeSynPtr, ConstExpr);
  3321. if (!GetFxnInfo(*ExprTypeSynPtr, &minParams, &maxParams, ExprTypeSynPtr, &firstParamSynPtr))
  3322. //error("exprval(): function or function pointer expected\n");
  3323. errorOpType();
  3324. // DONE: validate the number of function arguments
  3325. // DONE: warnings on int<->pointer substitution in params/args
  3326. // evaluate function arguments
  3327. c = 0;
  3328. while (stack[*idx][0] != '(')
  3329. {
  3330. word ptrmask;
  3331. // add a comma after the first (last to be pushed) argument,
  3332. // so all arguments can be pushed whenever a comma is encountered
  3333. if (!c)
  3334. ins(*idx + 1, ',');
  3335. oldIdx = *idx;
  3336. oldSp = sp;
  3337. (void)oldIdx;
  3338. (void)oldSp;
  3339. exprval(idx, &tmpSynPtr, ConstExpr);
  3340. //error("exprval(): function arguments cannot be of type 'void'\n");
  3341. if (c >= maxParams)
  3342. error("Too many function arguments\n");
  3343. // Find the type of the formal parameter in the function declaration
  3344. if (c < minParams)
  3345. {
  3346. word t;
  3347. while ((t = SyntaxStack0[firstParamSynPtr]) != tokIdent)
  3348. {
  3349. if (t == '(')
  3350. {
  3351. // skip parameters in parameters
  3352. word c = 1;
  3353. while (c)
  3354. {
  3355. t = SyntaxStack0[++firstParamSynPtr];
  3356. c += (t == '(') - (t == ')');
  3357. }
  3358. }
  3359. firstParamSynPtr++;
  3360. }
  3361. firstParamSynPtr++;
  3362. }
  3363. else
  3364. {
  3365. firstParamSynPtr = SymVoidSynPtr;
  3366. }
  3367. ptrmask = isAnyPtr(firstParamSynPtr) * 2 + isAnyPtr(tmpSynPtr);
  3368. (void)ptrmask;
  3369. // Bar void and struct/union
  3370. scalarTypeCheck(tmpSynPtr);
  3371. // if there's a formal parameter for this argument, check the types
  3372. if (c < minParams)
  3373. {
  3374. }
  3375. c++;
  3376. if (stack[*idx][0] == ',')
  3377. --*idx;
  3378. }
  3379. --*idx;
  3380. if (c < minParams)
  3381. error("Too few function arguments\n");
  3382. // store the cumulative argument size in the function call operators
  3383. {
  3384. word i = oldIdxRight + 1 - (oldSpRight - sp);
  3385. stack[1 + *idx][1] = stack[i][1] = c * SizeOfWord;
  3386. }
  3387. *ConstExpr = 0;
  3388. }
  3389. break;
  3390. // Binary comma operator
  3391. case tokComma:
  3392. {
  3393. word oldIdxLeft, oldSpLeft;
  3394. word retStruct = 0;
  3395. s = exprval(idx, &RightExprTypeSynPtr, &constExpr[1]);
  3396. oldIdxLeft = *idx;
  3397. oldSpLeft = sp;
  3398. // Signify uselessness of the result of the left operand's value
  3399. ins(*idx + 1, tokVoid);
  3400. exprval(idx, ExprTypeSynPtr, &constExpr[0]);
  3401. *ConstExpr = constExpr[0] && constExpr[1];
  3402. *ExprTypeSynPtr = RightExprTypeSynPtr;
  3403. retStruct = RightExprTypeSynPtr >= 0 && SyntaxStack0[RightExprTypeSynPtr] == tokStructPtr;
  3404. if (*ConstExpr)
  3405. {
  3406. // both subexprs are const, remove both and comma
  3407. simplifyConstExpr(s, *ConstExpr, ExprTypeSynPtr, oldIdxRight + 1 - (oldSpRight - sp), *idx + 1);
  3408. }
  3409. else if (constExpr[0])
  3410. {
  3411. // only left subexpr is const, remove it
  3412. del(*idx + 1, oldIdxLeft - (oldSpLeft - sp) - *idx);
  3413. if (!retStruct)
  3414. // Ensure non-lvalue-ness of the result by changing comma to unary plus
  3415. // and thus hiding dereference, if any
  3416. stack[oldIdxRight + 1 - (oldSpRight - sp)][0] = tokUnaryPlus;
  3417. else
  3418. // However, (something, struct).member should still be allowed,
  3419. // so, comma needs to produce lvalue
  3420. del(oldIdxRight + 1 - (oldSpRight - sp), 1);
  3421. }
  3422. else if (retStruct)
  3423. {
  3424. // However, (something, struct).member should still be allowed,
  3425. // so, comma needs to produce lvalue. Swap comma and structure dereference.
  3426. word i = oldIdxRight + 1 - (oldSpRight - sp);
  3427. stack[i][0] = tokUnaryStar;
  3428. stack[i][1] = stack[i - 1][1];
  3429. stack[i - 1][0] = tokComma;
  3430. }
  3431. }
  3432. break;
  3433. // Compound assignment operators
  3434. case tokAssignMul: case tokAssignDiv: case tokAssignMod:
  3435. case tokAssignAdd: case tokAssignSub:
  3436. case tokAssignLSh: case tokAssignRSh:
  3437. case tokAssignAnd: case tokAssignXor: case tokAssignOr:
  3438. {
  3439. word ptrmask;
  3440. word oldIdxLeft, oldSpLeft;
  3441. word incSize;
  3442. word opSize;
  3443. word Unsigned;
  3444. word sr = exprval(idx, &RightExprTypeSynPtr, &constExpr[1]);
  3445. oldIdxLeft = *idx;
  3446. oldSpLeft = sp;
  3447. exprval(idx, ExprTypeSynPtr, &constExpr[0]);
  3448. lvalueCheck(*ExprTypeSynPtr, oldIdxLeft - (oldSpLeft - sp));
  3449. // if it's a pointer, ensure that it's suitable for pointer arithmetic
  3450. // (not pointer to function, pointee size is known and non-zero)
  3451. decayArray(ExprTypeSynPtr, 1); // no actual decay here, just a type check
  3452. // Bar void and struct/union
  3453. scalarTypeCheck(RightExprTypeSynPtr);
  3454. scalarTypeCheck(*ExprTypeSynPtr);
  3455. // "remove" the lvalue dereference as we don't need
  3456. // to read the value while forgetting its location.
  3457. // We need to keep the lvalue location.
  3458. // Remember the operand size.
  3459. opSize = stack[oldIdxLeft - (oldSpLeft - sp)][1];
  3460. // store the operand size in the operator
  3461. stack[oldIdxRight + 1 - (oldSpRight - sp)][1] = opSize;
  3462. del(oldIdxLeft - (oldSpLeft - sp), 1);
  3463. ptrmask = isAnyPtr(*ExprTypeSynPtr) * 2 + isAnyPtr(RightExprTypeSynPtr);
  3464. Unsigned = isUint(*ExprTypeSynPtr) * 2 + isUint(RightExprTypeSynPtr);
  3465. if (tok != tokAssignAdd && tok != tokAssignSub)
  3466. {
  3467. if (ptrmask)
  3468. //error("exprval(): invalid combination of operands for %s\n", GetTokenName(tok));
  3469. errorOpType();
  3470. }
  3471. else
  3472. {
  3473. // No pointer to the right of += and -=
  3474. if (ptrmask & 1)
  3475. //error("exprval(): invalid combination of operands for %s\n", GetTokenName(tok));
  3476. errorOpType();
  3477. }
  3478. if (tok == tokAssignLSh || tok == tokAssignRSh)
  3479. {
  3480. if (constExpr[1])
  3481. {
  3482. if (Unsigned & 1)
  3483. sr = (word)truncUint(sr);
  3484. else
  3485. sr = truncInt(sr);
  3486. shiftCountCheck(&sr, oldIdxRight - (oldSpRight - sp), RightExprTypeSynPtr);
  3487. }
  3488. }
  3489. if (tok == tokAssignDiv || tok == tokAssignMod)
  3490. {
  3491. word t, sl = 0;
  3492. if (tok == tokAssignDiv)
  3493. t = '/';
  3494. else
  3495. t = '%';
  3496. divCheckAndCalc(t, &sl, sr, 1, constExpr);
  3497. }
  3498. // TBD??? replace +=/-= with prefix ++/-- if incSize == 1
  3499. if (ptrmask == 2) // left-hand expression
  3500. {
  3501. incSize = GetDeclSize(derefAnyPtr(*ExprTypeSynPtr), 0);
  3502. if (constExpr[1])
  3503. {
  3504. word t = (word)(stack[oldIdxRight - (oldSpRight - sp)][1] * (unsigned)incSize);
  3505. stack[oldIdxRight - (oldSpRight - sp)][1] = t;
  3506. }
  3507. else if (incSize != 1)
  3508. {
  3509. ins2(oldIdxRight + 1 - (oldSpRight - sp), tokNumInt, incSize);
  3510. ins(oldIdxRight + 1 - (oldSpRight - sp), '*');
  3511. }
  3512. }
  3513. else if (Unsigned)
  3514. {
  3515. word t = tok;
  3516. switch (tok)
  3517. {
  3518. case tokAssignDiv: t = tokAssignUDiv; break;
  3519. case tokAssignMod: t = tokAssignUMod; break;
  3520. case tokAssignRSh:
  3521. if (Unsigned & 2)
  3522. t = tokAssignURSh;
  3523. break;
  3524. }
  3525. stack[oldIdxRight + 1 - (oldSpRight - sp)][0] = t;
  3526. }
  3527. *ConstExpr = 0;
  3528. }
  3529. break;
  3530. // Ternary/conditional operator
  3531. case '?':
  3532. {
  3533. word oldIdxLeft, oldSpLeft;
  3534. word oldIdxCond, oldSpCond;
  3535. word sr, sl, smid;
  3536. word condTypeSynPtr;
  3537. word sc = (LabelCnt += 2) - 2;
  3538. word structs;
  3539. // "exprL ? exprMID : exprR" appears on the stack as
  3540. // "exprL exprR exprMID ?"
  3541. // label at the end of ?:
  3542. stack[*idx + 1][0] = tokLogAnd; // piggyback on && for CG (ugly, but simple)
  3543. stack[*idx + 1][1] = sc + 1;
  3544. smid = exprval(idx, ExprTypeSynPtr, &constExpr[1]);
  3545. oldIdxLeft = *idx;
  3546. oldSpLeft = sp;
  3547. sr = exprval(idx, &RightExprTypeSynPtr, &constExpr[2]);
  3548. decayArray(&RightExprTypeSynPtr, 0);
  3549. decayArray(ExprTypeSynPtr, 0);
  3550. promoteType(&RightExprTypeSynPtr, ExprTypeSynPtr);
  3551. promoteType(ExprTypeSynPtr, &RightExprTypeSynPtr);
  3552. structs = (*ExprTypeSynPtr >= 0 && SyntaxStack0[*ExprTypeSynPtr] == tokStructPtr) * 2 +
  3553. (RightExprTypeSynPtr >= 0 && SyntaxStack0[RightExprTypeSynPtr] == tokStructPtr);
  3554. // TBD??? move struct/union-related checks into compatChecks()
  3555. if (structs)
  3556. {
  3557. if (structs != 3 ||
  3558. SyntaxStack1[RightExprTypeSynPtr] != SyntaxStack1[*ExprTypeSynPtr])
  3559. errorOpType();
  3560. // transform "cond ? a : b" into "*(cond ? &a : &b)"
  3561. /*
  3562. if (stack[oldIdxLeft - (oldSpLeft - sp)][0] != tokUnaryStar ||
  3563. stack[oldIdxRight - (oldSpRight - sp)][0] != tokUnaryStar)
  3564. errorInternal(19);
  3565. */
  3566. del(oldIdxLeft - (oldSpLeft - sp), 1); // delete '*'
  3567. del(oldIdxRight - (oldSpRight - sp), 1); // delete '*'
  3568. oldSpLeft--;
  3569. // '*' will be inserted at the end
  3570. }
  3571. else
  3572. {
  3573. compatCheck(ExprTypeSynPtr,
  3574. RightExprTypeSynPtr,
  3575. &constExpr[1],
  3576. oldIdxRight - (oldSpRight - sp),
  3577. oldIdxLeft - (oldSpLeft - sp));
  3578. }
  3579. // label at the start of exprMID
  3580. ins2(oldIdxLeft + 1 - (oldSpLeft - sp), tokLogAnd, sc); // piggyback on && for CG (ugly, but simple)
  3581. // jump from the end of exprR over exprMID to the end of ?:
  3582. ins2(oldIdxLeft - (oldSpLeft - sp), tokGoto, sc + 1);
  3583. // jump to exprMID if exprL is non-zero
  3584. ins2(*idx + 1, tokShortCirc, -sc);
  3585. oldIdxCond = *idx;
  3586. oldSpCond = sp;
  3587. sl = exprval(idx, &condTypeSynPtr, &constExpr[0]);
  3588. // Bar void and struct/union
  3589. scalarTypeCheck(condTypeSynPtr);
  3590. *ConstExpr = s = 0;
  3591. if (constExpr[0])
  3592. {
  3593. word c1 = 0, c2 = 0;
  3594. // Stack now: exprL tokShortCirc exprR tokGoto tokLogAnd exprMID ?/tokLogAnd
  3595. if (
  3596. (truncUint(sl) != 0))
  3597. {
  3598. if (constExpr[1])
  3599. {
  3600. *ConstExpr = 1, s = smid;
  3601. }
  3602. else
  3603. {
  3604. // Drop exprL and exprR subexpressions
  3605. c1 = oldIdxLeft - (oldSpLeft - sp) - *idx; // includes tokShortCirc, tokGoto, tokLogAnd
  3606. c2 = 1; // include '?'/tokLogAnd
  3607. }
  3608. }
  3609. else
  3610. {
  3611. if (constExpr[2])
  3612. {
  3613. *ConstExpr = 1, s = sr;
  3614. }
  3615. else
  3616. {
  3617. // Drop exprL and exprMID subexpressions
  3618. c1 = oldIdxCond - (oldSpCond - sp) - *idx + 1; // includes tokShortCirc
  3619. c2 = (oldIdxRight - (oldSpRight - sp)) -
  3620. (oldIdxLeft - (oldSpLeft - sp)) + 3; // includes tokGoto, tokLogAnd, '?'/tokLogAnd
  3621. }
  3622. }
  3623. if (c1)
  3624. {
  3625. word pos = oldIdxRight - (oldSpRight - sp) + 2 - c2;
  3626. if (!structs && stack[pos - 1][0] == tokUnaryStar)
  3627. stack[pos++][0] = tokUnaryPlus, c2--; // ensure non-lvalue-ness by hiding the dereference
  3628. del(pos, c2);
  3629. del(*idx + 1, c1);
  3630. }
  3631. }
  3632. // finish transforming "cond ? a : b" into "*(cond ? &a : &b)", insert '*'
  3633. if (structs)
  3634. ins2(oldIdxRight + 2 - (oldSpRight - sp), tokUnaryStar, 0); // use 0 deref size to drop meaningless dereferences
  3635. simplifyConstExpr(s, *ConstExpr, ExprTypeSynPtr, oldIdxRight + 1 - (oldSpRight - sp), *idx + 1);
  3636. }
  3637. break;
  3638. // Postfix indirect structure/union member selection operator
  3639. case tokArrow:
  3640. {
  3641. word member, i = 0, j = 0, c = 1, ofs = 0;
  3642. stack[*idx + 1][0] = '+'; // replace -> with +
  3643. member = stack[*idx][1]; // keep the member name, it will be replaced with member offset
  3644. stack[*idx][0] = tokNumInt;
  3645. --*idx;
  3646. exprval(idx, ExprTypeSynPtr, ConstExpr);
  3647. if (!isAnyPtr(*ExprTypeSynPtr) ||
  3648. SyntaxStack0[i = derefAnyPtr(*ExprTypeSynPtr)] != tokStructPtr)
  3649. error("Pointer to or structure or union expected\n");
  3650. i = SyntaxStack1[i];
  3651. if (i + 2 > SyntaxStackCnt ||
  3652. (SyntaxStack0[i] != tokStruct && SyntaxStack0[i] != tokUnion) ||
  3653. SyntaxStack0[i + 1] != tokTag)
  3654. errorInternal(20);
  3655. if (!GetDeclSize(i, 0))
  3656. // incomplete structure/union type
  3657. errorOpType();
  3658. i += 5; // step inside the {} body of the struct/union
  3659. while (c)
  3660. {
  3661. word t = SyntaxStack0[i];
  3662. c += (t == '(') - (t == ')') + (t == '{') - (t == '}');
  3663. if (c == 1 &&
  3664. t == tokMemberIdent && SyntaxStack1[i] == member &&
  3665. SyntaxStack0[i + 1] == tokLocalOfs)
  3666. {
  3667. j = i;
  3668. ofs = SyntaxStack1[i + 1];
  3669. break;
  3670. }
  3671. i++;
  3672. }
  3673. if (!j)
  3674. {
  3675. printf("Undefined structure or union member ");
  3676. error(IdentTable + member);
  3677. }
  3678. j += 2;
  3679. // we cannot insert another '*' into the type to make it a pointer,
  3680. // so make the index into the type negative
  3681. *ExprTypeSynPtr = -j; // type: pointer to member's type
  3682. stack[oldIdxRight - (oldSpRight - sp)][1] = ofs; // member offset within structure/union
  3683. // optimize a little, if possible
  3684. {
  3685. word i = oldIdxRight - (oldSpRight - sp) - 1;
  3686. // Skip any type cast markers
  3687. while (stack[i][0] == tokUnaryPlus)
  3688. i--;
  3689. // See if the pointer is an integer constant or a local variable offset
  3690. // and if it is, adjust it here instead of generating code for
  3691. // addition/subtraction
  3692. if (stack[i][0] == tokNumInt || stack[i][0] == tokNumUint || stack[i][0] == tokLocalOfs)
  3693. {
  3694. stack[i][1] = (word)((unsigned)stack[i][1] + ofs); // TBD!!! need extra truncation?
  3695. del(oldIdxRight - (oldSpRight - sp), 2);
  3696. }
  3697. }
  3698. *ConstExpr = 0;
  3699. }
  3700. break;
  3701. default:
  3702. //error("exprval(): Unexpected token %s\n", GetTokenName(tok));
  3703. errorInternal(21);
  3704. }
  3705. return s;
  3706. }
  3707. word ParseExpr(word tok, word* GotUnary, word* ExprTypeSynPtr, word* ConstExpr, word* ConstVal, word option, word option2)
  3708. {
  3709. word identFirst = tok == tokIdent;
  3710. *ConstVal = *ConstExpr = 0;
  3711. *ExprTypeSynPtr = SymVoidSynPtr;
  3712. if (!ExprLevel++)
  3713. {
  3714. opsp = sp = 0;
  3715. }
  3716. if (option == '=')
  3717. push2(tokIdent, option2);
  3718. tok = expr(tok, GotUnary, option == ',' || option == '=');
  3719. if (tok == tokEof || strchr(",;:)]}", tok) == NULL)
  3720. //error("ParseExpr(): Unexpected token %s\n", GetTokenName(tok));
  3721. errorUnexpectedToken(tok);
  3722. if (option == '=')
  3723. {
  3724. push('=');
  3725. }
  3726. else if (option == tokGotoLabel && identFirst && tok == ':' && *GotUnary && sp == 1 && stack[sp - 1][0] == tokIdent)
  3727. {
  3728. // This is a label.
  3729. ExprLevel--;
  3730. return tokGotoLabel;
  3731. }
  3732. if (*GotUnary)
  3733. {
  3734. word j;
  3735. // Do this twice so we can see the stack before
  3736. // and after manipulations
  3737. for (j = 0; j < 2; j++)
  3738. {
  3739. if (doAnnotations)
  3740. {
  3741. word i;
  3742. GenStartCommentLine();
  3743. if (j) printf2("Expanded");
  3744. else printf2("RPN'ized");
  3745. printf2(" expression: \"");
  3746. for (i = 0; i < sp; i++)
  3747. {
  3748. word tok = stack[i][0];
  3749. switch (tok)
  3750. {
  3751. case tokNumInt:
  3752. printd2(truncInt(stack[i][1]));
  3753. break;
  3754. case tokNumUint:
  3755. printd2(truncUint(stack[i][1]));
  3756. break;
  3757. case tokIdent:
  3758. {
  3759. char* p = IdentTable + stack[i][1];
  3760. if (isdigit(*p))
  3761. printf2("L");
  3762. printf2(p);
  3763. }
  3764. break;
  3765. case tokShortCirc:
  3766. if (stack[i][1] >= 0)
  3767. {
  3768. printf2("[sh&&->");
  3769. printd2(stack[i][1]);
  3770. printf2("]");
  3771. }
  3772. else
  3773. {
  3774. printf2("[sh||->");
  3775. printd2(-stack[i][1]);
  3776. printf2("]");
  3777. }
  3778. break;
  3779. case tokLocalOfs:
  3780. printf2("(@");
  3781. printd2(truncInt(stack[i][1]));
  3782. printf2(")");
  3783. break;
  3784. case tokUnaryStar:
  3785. if (j)
  3786. {
  3787. printf2("*(");
  3788. printd2(stack[i][1]);
  3789. printf2(")");
  3790. }
  3791. else printf2("*u");
  3792. break;
  3793. case '(': case ',':
  3794. if (!j)
  3795. {
  3796. char* ctmp = " ";
  3797. ctmp[0] = tok;
  3798. printf2(ctmp);
  3799. }
  3800. // else printf2("\b");
  3801. break;
  3802. case ')':
  3803. if (j) printf2("(");
  3804. char* ctmp = " ";
  3805. ctmp[0] = tok;
  3806. printf2(ctmp);
  3807. if (j) printd2(stack[i][1]);
  3808. break;
  3809. default:
  3810. printf2(GetTokenName(tok));
  3811. if (j)
  3812. {
  3813. switch (tok)
  3814. {
  3815. case tokLogOr: case tokLogAnd:
  3816. printf2("[");
  3817. printd2(stack[i][1]);
  3818. printf2("]");
  3819. break;
  3820. case '=':
  3821. case tokInc: case tokDec:
  3822. case tokPostInc: case tokPostDec:
  3823. case tokAssignAdd: case tokAssignSub:
  3824. case tokPostAdd: case tokPostSub:
  3825. case tokAssignMul:
  3826. case tokAssignDiv: case tokAssignMod:
  3827. case tokAssignUDiv: case tokAssignUMod:
  3828. case tokAssignLSh: case tokAssignRSh: case tokAssignURSh:
  3829. case tokAssignAnd: case tokAssignXor: case tokAssignOr:
  3830. printf2("(");
  3831. printd2(stack[i][1]);
  3832. printf2(")");
  3833. break;
  3834. }
  3835. }
  3836. break;
  3837. }
  3838. printf2(" ");
  3839. }
  3840. printf2("\"\n");
  3841. }
  3842. if (!j)
  3843. {
  3844. word idx = sp - 1;
  3845. *ConstVal = exprval(&idx, ExprTypeSynPtr, ConstExpr);
  3846. // remove the unneeded unary +'s that have served their cast-substitute purpose
  3847. // also remove dereferences of size 0 (dereferences of pointers to structures)
  3848. for (idx = sp - 1; idx >= 0; idx--)
  3849. if (stack[idx][0] == tokUnaryPlus ||
  3850. (stack[idx][0] == tokUnaryStar && !stack[idx][1]))
  3851. del(idx, 1);
  3852. }
  3853. else if (*ConstExpr)
  3854. {
  3855. if (doAnnotations)
  3856. {
  3857. GenStartCommentLine();
  3858. switch (SyntaxStack0[*ExprTypeSynPtr])
  3859. {
  3860. case tokChar:
  3861. case tokSChar:
  3862. case tokUChar:
  3863. case tokShort:
  3864. case tokUShort:
  3865. case tokInt:
  3866. printf2("Expression value: ");
  3867. printd2(truncInt(*ConstVal));
  3868. printf2("\n");
  3869. break;
  3870. default:
  3871. case tokUnsigned:
  3872. printf2("Expression value: ");
  3873. printd2(truncUint(*ConstVal));
  3874. printf2("\n");
  3875. break;
  3876. }
  3877. }
  3878. }
  3879. }
  3880. }
  3881. ExprLevel--;
  3882. return tok;
  3883. }
  3884. // smc.c code
  3885. // Equivalent to puts() but outputs to OutFile.
  3886. word puts2(char* s)
  3887. {
  3888. word res;
  3889. if (!OutFile)
  3890. return 0;
  3891. // Turbo C++ 1.01's fputs() returns EOF if s is empty, which is wrong.
  3892. // Hence the workaround.
  3893. fputs(OutFile, s);
  3894. res = fputc(OutFile, '\n');
  3895. return res;
  3896. }
  3897. // Print string to outfile
  3898. word printf2(char* sToWrite)
  3899. {
  3900. if (!OutFile)
  3901. {
  3902. printf("COULD NOT WRITE TO OUT!");
  3903. return 0;
  3904. }
  3905. // TODO: escape handling
  3906. word res = fputs(OutFile, sToWrite);
  3907. return res;
  3908. }
  3909. // Print decimal to outfile
  3910. word printd2(word dToWrite)
  3911. {
  3912. if (!OutFile)
  3913. return 0;
  3914. char buf[32];
  3915. // handle negative numbers
  3916. if (dToWrite < 0)
  3917. {
  3918. fputc(OutFile, '-');
  3919. dToWrite = -dToWrite;
  3920. }
  3921. itoa(dToWrite, buf);
  3922. word res = fputs(OutFile, buf);
  3923. return res;
  3924. }
  3925. void error(char* strToPrint)
  3926. {
  3927. word i, fidx = FileCnt - 1 + !FileCnt;
  3928. for (i = 0; i < FileCnt; i++)
  3929. if (Files[i])
  3930. fclose(Files[i]);
  3931. /*
  3932. puts2("");
  3933. DumpSynDecls();
  3934. DumpMacroTable();
  3935. DumpIdentTable();
  3936. */
  3937. // using stdout implicitly instead of stderr explicitly because:
  3938. // - stderr can be a macro and it's unknown if standard headers
  3939. // aren't included (which is the case when SmallerC is compiled
  3940. // with itself and linked with some other compiler's standard
  3941. // libraries)
  3942. // - output to stderr can interfere/overlap with buffered
  3943. // output to stdout and the result may literally look ugly
  3944. //GenStartCommentLine(); printf2("Compilation failed.\n");
  3945. if (OutFile)
  3946. fclose(OutFile);
  3947. printf("Error in ");
  3948. printf(FileNames[fidx]);
  3949. printf(" at ");
  3950. printd(LineNo);
  3951. printf(":");
  3952. printd(LinePos);
  3953. printf("\n");
  3954. printf(strToPrint);
  3955. printf("\n");
  3956. exit(EXIT_FAILURE);
  3957. }
  3958. void warning(char* strToPrint)
  3959. {
  3960. word fidx = FileCnt - 1 + !FileCnt;
  3961. warnCnt++;
  3962. if (!warnings)
  3963. return;
  3964. //printf("Warning in \"%s\" (%d:%d)\n", FileNames[fidx], LineNo, LinePos);
  3965. printf("warning.");
  3966. printf(strToPrint);
  3967. }
  3968. void errorFile(char* n)
  3969. {
  3970. printf("Unable to open, read, write or close file ");
  3971. error(n);
  3972. }
  3973. void errorFileName(void)
  3974. {
  3975. error("Invalid or too long file name or path name\n");
  3976. }
  3977. void errorInternal(word n)
  3978. {
  3979. printd(n);
  3980. error(" internal error\n");
  3981. }
  3982. void errorChrStr(void)
  3983. {
  3984. error("Invalid or unsupported character constant or string literal\n");
  3985. }
  3986. void errorStrLen(void)
  3987. {
  3988. error("String literal too long\n");
  3989. }
  3990. void errorUnexpectedToken(word tok)
  3991. {
  3992. printf("Unexpected token ");
  3993. error((tok == tokIdent) ? TokenIdentName : GetTokenName(tok));
  3994. }
  3995. void errorDirective(void)
  3996. {
  3997. error("Invalid or unsupported preprocessor directive\n");
  3998. }
  3999. void errorCtrlOutOfScope(void)
  4000. {
  4001. error("break, continue, case or default in wrong scope\n");
  4002. }
  4003. void errorDecl(void)
  4004. {
  4005. error("Invalid or unsupported declaration\n");
  4006. }
  4007. void errorTagRedef(word ident)
  4008. {
  4009. printf("Redefinition of type tagged ");
  4010. printd(IdentTable + ident);
  4011. error("\n");
  4012. }
  4013. void errorVarSize(void)
  4014. {
  4015. error("Variable(s) take(s) too much space\n");
  4016. }
  4017. void errorInit(void)
  4018. {
  4019. error("Invalid or unsupported initialization\n");
  4020. }
  4021. void errorUnexpectedVoid(void)
  4022. {
  4023. error("Unexpected declaration or expression of type void\n");
  4024. }
  4025. void errorOpType(void)
  4026. {
  4027. error("Unexpected operand type\n");
  4028. }
  4029. void errorNotLvalue(void)
  4030. {
  4031. error("lvalue expected\n");
  4032. }
  4033. void errorNotConst(void)
  4034. {
  4035. error("Non-constant expression\n");
  4036. }
  4037. void errorLongExpr(void)
  4038. {
  4039. error("Expression too long\n");
  4040. }
  4041. word tsd[] =
  4042. {
  4043. tokVoid, tokChar, tokInt,
  4044. tokSigned, tokUnsigned, tokShort,
  4045. tokStruct, tokUnion,
  4046. };
  4047. word TokenStartsDeclaration(word t, word params)
  4048. {
  4049. unsigned i;
  4050. for (i = 0; i < division(sizeof tsd, sizeof tsd[0]); i++)
  4051. if (tsd[i] == t)
  4052. return 1;
  4053. return
  4054. (SizeOfWord != 2 && t == tokLong) ||
  4055. (!params && (t == tokExtern ||
  4056. t == tokStatic));
  4057. }
  4058. void PushSyntax2(word t, word v)
  4059. {
  4060. if (SyntaxStackCnt >= SYNTAX_STACK_MAX)
  4061. error("Symbol table exhausted\n");
  4062. SyntaxStack0[SyntaxStackCnt] = t;
  4063. SyntaxStack1[SyntaxStackCnt++] = v;
  4064. }
  4065. void PushSyntax(word t)
  4066. {
  4067. PushSyntax2(t, 0);
  4068. }
  4069. void InsertSyntax2(word pos, word t, word v)
  4070. {
  4071. if (SyntaxStackCnt >= SYNTAX_STACK_MAX)
  4072. error("Symbol table exhausted\n");
  4073. memmove(&SyntaxStack0[pos + 1],
  4074. &SyntaxStack0[pos],
  4075. sizeof(SyntaxStack0[0]) * (SyntaxStackCnt - pos));
  4076. memmove(&SyntaxStack1[pos + 1],
  4077. &SyntaxStack1[pos],
  4078. sizeof(SyntaxStack1[0]) * (SyntaxStackCnt - pos));
  4079. SyntaxStack0[pos] = t;
  4080. SyntaxStack1[pos] = v;
  4081. SyntaxStackCnt++;
  4082. }
  4083. void InsertSyntax(word pos, word t)
  4084. {
  4085. InsertSyntax2(pos, t, 0);
  4086. }
  4087. void DeleteSyntax(word pos, word cnt)
  4088. {
  4089. memmove(&SyntaxStack0[pos],
  4090. &SyntaxStack0[pos + cnt],
  4091. sizeof(SyntaxStack0[0]) * (SyntaxStackCnt - (pos + cnt)));
  4092. memmove(&SyntaxStack1[pos],
  4093. &SyntaxStack1[pos + cnt],
  4094. sizeof(SyntaxStack1[0]) * (SyntaxStackCnt - (pos + cnt)));
  4095. SyntaxStackCnt -= cnt;
  4096. }
  4097. word FindSymbol(char* s)
  4098. {
  4099. word i;
  4100. // TBD!!! return declaration scope number so
  4101. // redeclarations can be reported if occur in the same scope.
  4102. // TBD??? Also, I could first use FindIdent() and then just look for the
  4103. // index into IdentTable[] instead of doing strcmp()
  4104. for (i = SyntaxStackCnt - 1; i >= 0; i--)
  4105. {
  4106. word t = SyntaxStack0[i];
  4107. if (t == tokIdent &&
  4108. !strcmp(IdentTable + SyntaxStack1[i], s))
  4109. {
  4110. return i;
  4111. }
  4112. if (t == ')')
  4113. {
  4114. // Skip over the function params
  4115. word c = -1;
  4116. while (c)
  4117. {
  4118. t = SyntaxStack0[--i];
  4119. c += (t == '(') - (t == ')');
  4120. }
  4121. }
  4122. }
  4123. return -1;
  4124. }
  4125. word SymType(word SynPtr)
  4126. {
  4127. word local = 0;
  4128. if (SyntaxStack0[SynPtr] == tokIdent)
  4129. SynPtr++;
  4130. if ((local = SyntaxStack0[SynPtr] == tokLocalOfs) != 0)
  4131. SynPtr++;
  4132. switch (SyntaxStack0[SynPtr])
  4133. {
  4134. case '(':
  4135. return SymFxn;
  4136. case '[':
  4137. if (local)
  4138. return SymLocalArr;
  4139. return SymGlobalArr;
  4140. default:
  4141. if (local)
  4142. return SymLocalVar;
  4143. return SymGlobalVar;
  4144. }
  4145. }
  4146. word FindTaggedDecl(char* s, word start, word* CurScope)
  4147. {
  4148. word i;
  4149. *CurScope = 1;
  4150. for (i = start; i >= 0; i--)
  4151. {
  4152. word t = SyntaxStack0[i];
  4153. if (t == tokTag &&
  4154. !strcmp(IdentTable + SyntaxStack1[i], s))
  4155. {
  4156. return i - 1;
  4157. }
  4158. else if (t == ')')
  4159. {
  4160. // Skip over the function params
  4161. word c = -1;
  4162. while (c)
  4163. {
  4164. t = SyntaxStack0[--i];
  4165. c += (t == '(') - (t == ')');
  4166. }
  4167. }
  4168. else if (t == '#')
  4169. {
  4170. // the scope has changed to the outer scope
  4171. *CurScope = 0;
  4172. }
  4173. }
  4174. return -1;
  4175. }
  4176. word GetDeclSize(word SyntaxPtr, word SizeForDeref)
  4177. {
  4178. word i;
  4179. unsigned size = 1;
  4180. word arr = 0;
  4181. if (SyntaxPtr < 0) // pointer?
  4182. return SizeOfWord;
  4183. for (i = SyntaxPtr; i < SyntaxStackCnt; i++)
  4184. {
  4185. word tok = SyntaxStack0[i];
  4186. switch (tok)
  4187. {
  4188. case tokIdent: // skip leading identifiers, if any
  4189. case tokLocalOfs: // skip local var offset, too
  4190. break;
  4191. case tokChar:
  4192. case tokSChar:
  4193. if (!arr && ((tok == tokSChar) || CharIsSigned) && SizeForDeref)
  4194. return -1; // 1 byte, needing sign extension when converted to int/unsigned int
  4195. // fallthrough
  4196. case tokUChar:
  4197. return (word)size;
  4198. case tokShort:
  4199. if (!arr && SizeForDeref)
  4200. return -2; // 2 bytes, needing sign extension when converted to int/unsigned int
  4201. // fallthrough
  4202. case tokUShort:
  4203. //if (size * 2 / 2 != size)
  4204. //error("Variable too big\n");
  4205. // errorVarSize();
  4206. size *= 2;
  4207. if (size != truncUint(size))
  4208. //error("Variable too big\n");
  4209. {
  4210. //printf("b");
  4211. errorVarSize();
  4212. }
  4213. return (word)size;
  4214. case tokInt:
  4215. case tokUnsigned:
  4216. case '*':
  4217. case '(': // size of fxn = size of ptr for now
  4218. //if (size * SizeOfWord / SizeOfWord != size)
  4219. //error("Variable too big\n");
  4220. //errorVarSize();
  4221. size *= SizeOfWord;
  4222. if (size != truncUint(size))
  4223. //error("Variable too big\n");
  4224. {
  4225. //printf("c");
  4226. errorVarSize();
  4227. }
  4228. return (word)size;
  4229. case '[':
  4230. if (SyntaxStack0[i + 1] != tokNumInt && SyntaxStack0[i + 1] != tokNumUint)
  4231. errorInternal(11);
  4232. //if (SyntaxStack1[i + 1] &&
  4233. //size * SyntaxStack1[i + 1] / SyntaxStack1[i + 1] != size)
  4234. //error("Variable too big\n");
  4235. //errorVarSize();
  4236. size *= SyntaxStack1[i + 1];
  4237. if (size != truncUint(size))
  4238. //error("Variable too big\n");
  4239. {
  4240. //printf("d");
  4241. errorVarSize();
  4242. }
  4243. i += 2;
  4244. arr = 1;
  4245. break;
  4246. case tokStructPtr:
  4247. // follow the "type pointer"
  4248. i = SyntaxStack1[i] - 1;
  4249. break;
  4250. case tokStruct:
  4251. case tokUnion:
  4252. if (i + 2 < SyntaxStackCnt && SyntaxStack0[i + 2] == tokSizeof && !SizeForDeref)
  4253. {
  4254. unsigned s = SyntaxStack1[i + 2];
  4255. //if (s && size * s / s != size)
  4256. // errorVarSize();
  4257. size *= s;
  4258. if (size != truncUint(size))
  4259. {
  4260. //printf("d");
  4261. errorVarSize();
  4262. }
  4263. return (word)size;
  4264. }
  4265. return 0;
  4266. case tokVoid:
  4267. return 0;
  4268. default:
  4269. errorInternal(12);
  4270. }
  4271. }
  4272. errorInternal(13);
  4273. return 0;
  4274. }
  4275. word GetDeclAlignment(word SyntaxPtr)
  4276. {
  4277. word i;
  4278. if (SyntaxPtr < 0) // pointer?
  4279. return SizeOfWord;
  4280. for (i = SyntaxPtr; i < SyntaxStackCnt; i++)
  4281. {
  4282. word tok = SyntaxStack0[i];
  4283. switch (tok)
  4284. {
  4285. case tokIdent: // skip leading identifiers, if any
  4286. case tokLocalOfs: // skip local var offset, too
  4287. break;
  4288. case tokChar:
  4289. case tokSChar:
  4290. case tokUChar:
  4291. return 1;
  4292. case tokShort:
  4293. case tokUShort:
  4294. return 2;
  4295. case tokInt:
  4296. case tokUnsigned:
  4297. case '*':
  4298. case '(':
  4299. return SizeOfWord;
  4300. case '[':
  4301. if (SyntaxStack0[i + 1] != tokNumInt && SyntaxStack0[i + 1] != tokNumUint)
  4302. errorInternal(15);
  4303. i += 2;
  4304. break;
  4305. case tokStructPtr:
  4306. // follow the "type pointer"
  4307. i = SyntaxStack1[i] - 1;
  4308. break;
  4309. case tokStruct:
  4310. case tokUnion:
  4311. if (i + 3 < SyntaxStackCnt && SyntaxStack0[i + 2] == tokSizeof)
  4312. {
  4313. return SyntaxStack1[i + 3];
  4314. }
  4315. return 1;
  4316. case tokVoid:
  4317. return 1;
  4318. default:
  4319. errorInternal(16);
  4320. }
  4321. }
  4322. errorInternal(17);
  4323. return 0;
  4324. }
  4325. void DumpDecl(word SyntaxPtr, word IsParam)
  4326. {
  4327. word i;
  4328. word icnt = 0;
  4329. if (SyntaxPtr < 0)
  4330. return;
  4331. for (i = SyntaxPtr; i < SyntaxStackCnt; i++)
  4332. {
  4333. word tok = SyntaxStack0[i];
  4334. word v = SyntaxStack1[i];
  4335. switch (tok)
  4336. {
  4337. case tokLocalOfs:
  4338. printf2("(@");
  4339. printd2(truncInt(v));
  4340. printf2(") : ");
  4341. break;
  4342. case tokIdent:
  4343. if (++icnt > 1 && !IsParam) // show at most one declaration, except params
  4344. return;
  4345. GenStartCommentLine();
  4346. if (ParseLevel == 0)
  4347. printf2("glb ");
  4348. else if (IsParam)
  4349. printf2("prm ");
  4350. else
  4351. printf2("loc ");
  4352. {
  4353. word j;
  4354. for (j = 0; j < ParseLevel * 4; j++)
  4355. printf2(" ");
  4356. }
  4357. if (IsParam && !strcmp(IdentTable + v, "<something>") && (i + 1 < SyntaxStackCnt))
  4358. {
  4359. if (SyntaxStack0[i + 1] == tokEllipsis)
  4360. continue;
  4361. }
  4362. printf2(IdentTable + v);
  4363. printf2(" : ");
  4364. if (!IsParam && (i + 1 < SyntaxStackCnt) && SyntaxStack0[i + 1] == tokIdent)
  4365. {
  4366. // renamed local static variable
  4367. GenPrintLabel(IdentTable + SyntaxStack1[++i]);
  4368. printf2(" : ");
  4369. }
  4370. break;
  4371. case '[':
  4372. printf2("[");
  4373. break;
  4374. case tokNumInt:
  4375. printd2(truncInt(v));
  4376. break;
  4377. case tokNumUint:
  4378. printd2(truncUint(v));
  4379. break;
  4380. case ']':
  4381. printf2("] ");
  4382. break;
  4383. case '(':
  4384. {
  4385. word noparams;
  4386. // Skip over the params to the base type
  4387. word j = ++i, c = 1;
  4388. while (c)
  4389. {
  4390. word t = SyntaxStack0[j++];
  4391. c += (t == '(') - (t == ')');
  4392. }
  4393. noparams = (i + 1 == j) || (SyntaxStack0[i + 1] == tokVoid);
  4394. printf2("(");
  4395. // Print the params (recursively)
  4396. if (noparams)
  4397. {
  4398. // Don't recurse if it's "fxn()" or "fxn(void)"
  4399. if (i + 1 != j)
  4400. printf2("void");
  4401. }
  4402. else
  4403. {
  4404. puts2("");
  4405. ParseLevel++;
  4406. DumpDecl(i, 1);
  4407. ParseLevel--;
  4408. }
  4409. // Continue normally
  4410. i = j - 1;
  4411. if (!noparams)
  4412. {
  4413. GenStartCommentLine();
  4414. printf2(" ");
  4415. {
  4416. word j;
  4417. for (j = 0; j < ParseLevel * 4; j++)
  4418. printf2(" ");
  4419. }
  4420. }
  4421. printf2(") ");
  4422. }
  4423. break;
  4424. case ')': // end of param list
  4425. return;
  4426. case tokStructPtr:
  4427. DumpDecl(v, 0);
  4428. break;
  4429. default:
  4430. switch (tok)
  4431. {
  4432. case tokVoid:
  4433. case tokChar:
  4434. case tokSChar:
  4435. case tokUChar:
  4436. case tokShort:
  4437. case tokUShort:
  4438. case tokInt:
  4439. case tokUnsigned:
  4440. case tokEllipsis:
  4441. printf2(GetTokenName(tok));
  4442. printf2("\n");
  4443. break;
  4444. default:
  4445. printf2(GetTokenName(tok));
  4446. printf2(" ");
  4447. break;
  4448. case tokTag:
  4449. printf2(IdentTable + v);
  4450. printf2("\n");
  4451. return;
  4452. }
  4453. break;
  4454. }
  4455. }
  4456. }
  4457. void DumpSynDecls(void)
  4458. {
  4459. word used = SyntaxStackCnt * (sizeof SyntaxStack0[0] + sizeof SyntaxStack1[0]);
  4460. word total = SYNTAX_STACK_MAX * (sizeof SyntaxStack0[0] + sizeof SyntaxStack1[0]);
  4461. puts2("");
  4462. GenStartCommentLine(); printf2("Syntax/declaration table/stack:\n");
  4463. GenStartCommentLine();
  4464. printf2("Bytes used: ");
  4465. printd2(used);
  4466. printf2("/");
  4467. printd2(total);
  4468. printf2("\n\n");
  4469. }
  4470. word ParseArrayDimension(word AllowEmptyDimension)
  4471. {
  4472. word tok;
  4473. word gotUnary, synPtr, constExpr, exprVal;
  4474. unsigned exprValU;
  4475. word oldssp, oldesp, undoIdents;
  4476. tok = GetToken();
  4477. // DONE: support arbitrary constant expressions
  4478. oldssp = SyntaxStackCnt;
  4479. oldesp = sp;
  4480. undoIdents = IdentTableLen;
  4481. tok = ParseExpr(tok, &gotUnary, &synPtr, &constExpr, &exprVal, 0, 0);
  4482. IdentTableLen = undoIdents; // remove all temporary identifier names from e.g. "sizeof"
  4483. SyntaxStackCnt = oldssp; // undo any temporary declarations from e.g. "sizeof" in the expression
  4484. sp = oldesp;
  4485. if (tok != ']')
  4486. //error("ParseArrayDimension(): Unsupported or invalid array dimension (token %s)\n", GetTokenName(tok));
  4487. errorUnexpectedToken(tok);
  4488. if (!gotUnary)
  4489. {
  4490. if (!AllowEmptyDimension)
  4491. //error("ParseArrayDimension(): missing array dimension\n");
  4492. errorUnexpectedToken(tok);
  4493. // Empty dimension is dimension of 0
  4494. exprVal = 0;
  4495. }
  4496. else
  4497. {
  4498. if (!constExpr)
  4499. //error("ParseArrayDimension(): non-constant array dimension\n");
  4500. errorNotConst();
  4501. exprValU = truncUint(exprVal);
  4502. exprVal = truncInt(exprVal);
  4503. promoteType(&synPtr, &synPtr);
  4504. anyIntTypeCheck(synPtr);
  4505. if ((SyntaxStack0[synPtr] == tokInt && exprVal < 1) || (SyntaxStack0[synPtr] == tokUnsigned && exprValU < 1))
  4506. error("Array dimension less than 1\n");
  4507. exprVal = (word)exprValU;
  4508. }
  4509. PushSyntax2(tokNumUint, exprVal);
  4510. return tok;
  4511. }
  4512. void ParseFxnParams(word tok);
  4513. static word BrkCntTargetFxn[2];
  4514. word ParseBlock(word BrkCntTarget[2], word casesIdx);
  4515. void AddFxnParamSymbols(word SyntaxPtr);
  4516. void CheckRedecl(word lastSyntaxPtr);
  4517. word ParseBase(word tok, word base[2])
  4518. {
  4519. word valid = 1;
  4520. base[1] = 0;
  4521. switch (tok)
  4522. {
  4523. case tokVoid:
  4524. *base = tok;
  4525. tok = GetToken();
  4526. break;
  4527. case tokChar:
  4528. case tokInt:
  4529. case tokShort:
  4530. case tokLong:
  4531. case tokSigned:
  4532. case tokUnsigned:
  4533. {
  4534. word allowedMask = 0x7F; // double:0x40 unsigned:0x20 signed:0x10 long:0x08 int:0x04 short:0x02 char:0x01
  4535. word typeMask = 0;
  4536. word tokMask, disallowedMask;
  4537. lcont:
  4538. switch (tok)
  4539. {
  4540. case tokChar:
  4541. tokMask = 0x01; disallowedMask = 0x4E; break; // disallows double, long, int, short
  4542. case tokShort:
  4543. tokMask = 0x02; disallowedMask = 0x49; break; // disallows double, long, char
  4544. case tokInt:
  4545. tokMask = 0x04; disallowedMask = 0x41; break; // disallows double, char
  4546. case tokLong:
  4547. tokMask = 0x08; disallowedMask = 0x03; break; // disallows short, char
  4548. case tokSigned:
  4549. tokMask = 0x10; disallowedMask = 0x60; break; // disallows double, unsigned
  4550. case tokUnsigned:
  4551. tokMask = 0x20; disallowedMask = 0x50; break; // disallows double, signed
  4552. default:
  4553. tokMask = disallowedMask = 0; break;
  4554. }
  4555. if (allowedMask & tokMask)
  4556. {
  4557. typeMask |= tokMask;
  4558. allowedMask &= ~(disallowedMask | tokMask);
  4559. tok = GetToken();
  4560. goto lcont;
  4561. }
  4562. switch (typeMask)
  4563. {
  4564. case 0x01: typeMask = tokChar; break;
  4565. case 0x11: typeMask = tokSChar; break;
  4566. case 0x21: typeMask = tokUChar; break;
  4567. case 0x02: case 0x12: case 0x06: case 0x16: typeMask = tokShort; break;
  4568. case 0x22: case 0x26: typeMask = tokUShort; break;
  4569. case 0x04: case 0x10: case 0x14: typeMask = tokInt; break;
  4570. case 0x20: case 0x24: typeMask = tokUnsigned; break;
  4571. case 0x08: case 0x18: case 0x0C: case 0x1C: typeMask = tokLong; break;
  4572. case 0x28: case 0x2C: typeMask = tokULong; break;
  4573. default:
  4574. errorDecl();
  4575. }
  4576. *base = typeMask;
  4577. }
  4578. break;
  4579. case tokStruct:
  4580. case tokUnion:
  4581. {
  4582. word structType = tok;
  4583. word empty = 1;
  4584. word typePtr = SyntaxStackCnt;
  4585. word gotTag = 0, tagIdent = 0, declPtr = -1, curScope = 0;
  4586. tok = GetToken();
  4587. if (tok == tokIdent)
  4588. {
  4589. // this is a structure/union/enum tag
  4590. gotTag = 1;
  4591. declPtr = FindTaggedDecl(TokenIdentName, SyntaxStackCnt - 1, &curScope);
  4592. tagIdent = AddIdent(TokenIdentName);
  4593. if (declPtr >= 0)
  4594. {
  4595. // Within the same scope we can't declare more than one union, structure or enum
  4596. // with the same tag.
  4597. // There's one common tag namespace for structures, unions and enumerations.
  4598. if (curScope && SyntaxStack0[declPtr] != structType)
  4599. errorTagRedef(tagIdent);
  4600. }
  4601. else if (ParamLevel)
  4602. {
  4603. // new structure/union/enum declarations aren't supported in function parameters
  4604. errorDecl();
  4605. }
  4606. tok = GetToken();
  4607. }
  4608. else
  4609. {
  4610. // structure/union/enum declarations aren't supported in expressions
  4611. if (ExprLevel)
  4612. errorDecl();
  4613. PushSyntax(structType);
  4614. PushSyntax2(tokTag, AddIdent("<something>"));
  4615. }
  4616. if (tok == '{')
  4617. {
  4618. unsigned structInfo[4], sz, alignment, tmp;
  4619. // new structure/union/enum declarations aren't supported in expressions and function parameters
  4620. if (ExprLevel || ParamLevel)
  4621. errorDecl();
  4622. if (gotTag)
  4623. {
  4624. // Cannot redefine a tagged structure/union/enum within the same scope
  4625. if (declPtr >= 0 &&
  4626. curScope &&
  4627. ((declPtr + 2 < SyntaxStackCnt && SyntaxStack0[declPtr + 2] == tokSizeof)
  4628. ))
  4629. errorTagRedef(tagIdent);
  4630. PushSyntax(structType);
  4631. PushSyntax2(tokTag, tagIdent);
  4632. }
  4633. {
  4634. structInfo[0] = structType;
  4635. structInfo[1] = 1; // initial member alignment
  4636. structInfo[2] = 0; // initial member offset
  4637. structInfo[3] = 0; // initial max member size (for unions)
  4638. PushSyntax(tokSizeof); // 0 = initial structure/union size, to be updated
  4639. PushSyntax2(tokSizeof, 1); // 1 = initial structure/union alignment, to be updated
  4640. PushSyntax('{');
  4641. tok = GetToken();
  4642. while (tok != '}')
  4643. {
  4644. if (!TokenStartsDeclaration(tok, 1))
  4645. errorUnexpectedToken(tok);
  4646. tok = ParseDecl(tok, structInfo, 0, 0);
  4647. empty = 0;
  4648. }
  4649. if (empty)
  4650. errorUnexpectedToken('}');
  4651. PushSyntax('}');
  4652. // Update structure/union alignment
  4653. alignment = structInfo[1];
  4654. SyntaxStack1[typePtr + 3] = alignment;
  4655. // Update structure/union size and include trailing padding if needed
  4656. sz = structInfo[2] + structInfo[3];
  4657. tmp = sz;
  4658. sz = (sz + alignment - 1) & ~(alignment - 1);
  4659. if (sz < tmp || sz != truncUint(sz))
  4660. {
  4661. //printf("e");
  4662. errorVarSize();
  4663. }
  4664. SyntaxStack1[typePtr + 2] = (word)sz;
  4665. tok = GetToken();
  4666. }
  4667. }
  4668. else
  4669. {
  4670. if (gotTag)
  4671. {
  4672. if (declPtr >= 0 &&
  4673. SyntaxStack0[declPtr] == structType)
  4674. {
  4675. base[0] = tokStructPtr;
  4676. base[1] = declPtr;
  4677. return tok;
  4678. }
  4679. PushSyntax(structType);
  4680. PushSyntax2(tokTag, tagIdent);
  4681. empty = 0;
  4682. }
  4683. }
  4684. if (empty)
  4685. errorDecl();
  4686. base[0] = tokStructPtr;
  4687. base[1] = typePtr;
  4688. // If we've just defined a structure/union and there are
  4689. // preceding references to this tag within this scope,
  4690. // IOW references to an incomplete type, complete the
  4691. // type in the references
  4692. if (gotTag && SyntaxStack0[SyntaxStackCnt - 1] == '}')
  4693. {
  4694. word i;
  4695. for (i = SyntaxStackCnt - 1; i >= 0; i--)
  4696. if (SyntaxStack0[i] == tokStructPtr)
  4697. {
  4698. word j = SyntaxStack1[i];
  4699. if (SyntaxStack1[j + 1] == tagIdent && !GetDeclSize(i, 0))
  4700. SyntaxStack1[i] = typePtr;
  4701. }
  4702. else if (SyntaxStack0[i] == '#')
  4703. {
  4704. // reached the beginning of the current scope
  4705. break;
  4706. }
  4707. }
  4708. }
  4709. break;
  4710. default:
  4711. valid = 0;
  4712. break;
  4713. }
  4714. if (SizeOfWord == 2 &&
  4715. (*base == tokLong || *base == tokULong))
  4716. valid = 0;
  4717. // to simplify matters, treat long and unsigned long as aliases for int and unsigned int
  4718. // in 32-bit and huge mode(l)s
  4719. if (*base == tokLong)
  4720. *base = tokInt;
  4721. if (*base == tokULong)
  4722. *base = tokUnsigned;
  4723. if (SizeOfWord == 2)
  4724. {
  4725. // to simplify matters, treat short and unsigned short as aliases for int and unsigned int
  4726. // in 16-bit mode
  4727. if (*base == tokShort)
  4728. *base = tokInt;
  4729. if (*base == tokUShort)
  4730. *base = tokUnsigned;
  4731. }
  4732. // TBD!!! review/test this fxn
  4733. // if (!valid || !tok || !(strchr("*([,)", tok) || tok == tokIdent))
  4734. if (!valid | !tok)
  4735. //error("ParseBase(): Invalid or unsupported type\n");
  4736. error("Invalid or unsupported type\n");
  4737. return tok;
  4738. }
  4739. /*
  4740. base * name [] -> name : [] * base
  4741. base *2 (*1 name []1) []2 -> name : []1 *1 []2 *2 base
  4742. base *3 (*2 (*1 name []1) []2) []3 -> name : []1 *1 []2 *2 []3 *3 base
  4743. */
  4744. word ParseDerived(word tok)
  4745. {
  4746. word stars = 0;
  4747. word params = 0;
  4748. while (tok == '*')
  4749. {
  4750. stars++;
  4751. tok = GetToken();
  4752. }
  4753. if (tok == '(')
  4754. {
  4755. tok = GetToken();
  4756. if (tok != ')' && !TokenStartsDeclaration(tok, 1))
  4757. {
  4758. tok = ParseDerived(tok);
  4759. if (tok != ')')
  4760. //error("ParseDerived(): ')' expected\n");
  4761. errorUnexpectedToken(tok);
  4762. tok = GetToken();
  4763. }
  4764. else
  4765. {
  4766. params = 1;
  4767. }
  4768. }
  4769. else if (tok == tokIdent)
  4770. {
  4771. PushSyntax2(tok, AddIdent(TokenIdentName));
  4772. tok = GetToken();
  4773. }
  4774. else
  4775. {
  4776. PushSyntax2(tokIdent, AddIdent("<something>"));
  4777. }
  4778. if (params | (tok == '('))
  4779. {
  4780. word t = SyntaxStack0[SyntaxStackCnt - 1];
  4781. if ((t == ')') | (t == ']'))
  4782. errorUnexpectedToken('('); // array of functions or function returning function
  4783. if (!params)
  4784. tok = GetToken();
  4785. else
  4786. PushSyntax2(tokIdent, AddIdent("<something>"));
  4787. PushSyntax('(');
  4788. ParseLevel++;
  4789. ParamLevel++;
  4790. ParseFxnParams(tok);
  4791. ParamLevel--;
  4792. ParseLevel--;
  4793. PushSyntax(')');
  4794. tok = GetToken();
  4795. }
  4796. else if (tok == '[')
  4797. {
  4798. // DONE!!! allow the first [] without the dimension in function parameters
  4799. word allowEmptyDimension = 1;
  4800. if (SyntaxStack0[SyntaxStackCnt - 1] == ')')
  4801. errorUnexpectedToken('['); // function returning array
  4802. while (tok == '[')
  4803. {
  4804. word oldsp = SyntaxStackCnt;
  4805. PushSyntax(tokVoid); // prevent cases like "int arr[arr];" and "int arr[arr[0]];"
  4806. PushSyntax(tok);
  4807. tok = ParseArrayDimension(allowEmptyDimension);
  4808. if (tok != ']')
  4809. //error("ParseDerived(): ']' expected\n");
  4810. errorUnexpectedToken(tok);
  4811. PushSyntax(']');
  4812. tok = GetToken();
  4813. DeleteSyntax(oldsp, 1);
  4814. allowEmptyDimension = 0;
  4815. }
  4816. }
  4817. while (stars--)
  4818. PushSyntax('*');
  4819. if (!tok || !strchr(",;{=)", tok))
  4820. //error("ParseDerived(): unexpected token %s\n", GetTokenName(tok));
  4821. errorUnexpectedToken(tok);
  4822. return tok;
  4823. }
  4824. void PushBase(word base[2])
  4825. {
  4826. {
  4827. PushSyntax2(base[0], base[1]);
  4828. }
  4829. // Cannot have array of void
  4830. if (SyntaxStack0[SyntaxStackCnt - 1] == tokVoid &&
  4831. SyntaxStack0[SyntaxStackCnt - 2] == ']')
  4832. errorUnexpectedVoid();
  4833. }
  4834. word InitScalar(word synPtr, word tok);
  4835. word InitArray(word synPtr, word tok);
  4836. word InitStruct(word synPtr, word tok);
  4837. word InitVar(word synPtr, word tok)
  4838. {
  4839. word p = synPtr, t;
  4840. word undoIdents = IdentTableLen;
  4841. while ((t = SyntaxStack0[p]), (t == tokIdent) | (t == tokLocalOfs))
  4842. p++;
  4843. switch (t)
  4844. {
  4845. case '[':
  4846. // Initializers for aggregates must be enclosed in braces,
  4847. // except for arrays of char initialized with string literals,
  4848. // in which case braces are optional
  4849. if (tok != '{')
  4850. {
  4851. t = SyntaxStack0[p + 3];
  4852. if (((tok != tokLitStr) | ((t != tokChar) & (t != tokUChar) & (t != tokSChar)))
  4853. )
  4854. errorUnexpectedToken(tok);
  4855. }
  4856. tok = InitArray(p, tok);
  4857. break;
  4858. case tokStructPtr:
  4859. // Initializers for aggregates must be enclosed in braces
  4860. if (tok != '{')
  4861. errorUnexpectedToken(tok);
  4862. tok = InitStruct(p, tok);
  4863. break;
  4864. default:
  4865. tok = InitScalar(p, tok);
  4866. break;
  4867. }
  4868. if (!strchr(",;", tok))
  4869. errorUnexpectedToken(tok);
  4870. IdentTableLen = undoIdents; // remove all temporary identifier names from e.g. "sizeof" or "str"
  4871. return tok;
  4872. }
  4873. word InitScalar(word synPtr, word tok)
  4874. {
  4875. unsigned elementSz = GetDeclSize(synPtr, 0);
  4876. word gotUnary, synPtr2, constExpr, exprVal;
  4877. word oldssp = SyntaxStackCnt;
  4878. word undoIdents = IdentTableLen;
  4879. word ttop;
  4880. word braces = 0;
  4881. // Initializers for scalars can be optionally enclosed in braces
  4882. if (tok == '{')
  4883. {
  4884. braces = 1;
  4885. tok = GetToken();
  4886. }
  4887. tok = ParseExpr(tok, &gotUnary, &synPtr2, &constExpr, &exprVal, ',', 0);
  4888. if (!gotUnary)
  4889. errorUnexpectedToken(tok);
  4890. if (braces)
  4891. {
  4892. if (tok != '}')
  4893. errorUnexpectedToken(tok);
  4894. tok = GetToken();
  4895. }
  4896. // Bar void and struct/union
  4897. scalarTypeCheck(synPtr2);
  4898. ttop = stack[sp - 1][0];
  4899. if (ttop == tokNumInt || ttop == tokNumUint)
  4900. {
  4901. word val = stack[sp - 1][1];
  4902. // TBD??? truncate values for types smaller than int (e.g. char and short),
  4903. // so they are always in range for the assembler?
  4904. GenIntData(elementSz, val);
  4905. }
  4906. else if (elementSz == (unsigned)SizeOfWord)
  4907. {
  4908. if (ttop == tokIdent)
  4909. {
  4910. GenAddrData(elementSz, IdentTable + stack[sp - 1][1], 0);
  4911. }
  4912. else if (ttop == '+' || ttop == '-')
  4913. {
  4914. word tleft = stack[sp - 3][0];
  4915. word tright = stack[sp - 2][0];
  4916. if (tleft == tokIdent &&
  4917. (tright == tokNumInt || tright == tokNumUint))
  4918. {
  4919. GenAddrData(elementSz, IdentTable + stack[sp - 3][1], (ttop == '+') ? stack[sp - 2][1] : -stack[sp - 2][1]);
  4920. }
  4921. else if (ttop == '+' &&
  4922. tright == tokIdent &&
  4923. (tleft == tokNumInt || tleft == tokNumUint))
  4924. {
  4925. GenAddrData(elementSz, IdentTable + stack[sp - 2][1], stack[sp - 3][1]);
  4926. }
  4927. else
  4928. errorNotConst();
  4929. }
  4930. else
  4931. errorNotConst();
  4932. // Defer storage of string literal data (if any) until the end.
  4933. // This will let us generate the contiguous array of pointers to
  4934. // string literals unperturbed by the string literal data
  4935. // (e.g. "char* colors[] = { "red", "green", "blue" };").
  4936. }
  4937. else
  4938. //error("ParseDecl(): cannot initialize a global variable with a non-constant expression\n");
  4939. errorNotConst();
  4940. IdentTableLen = undoIdents; // remove all temporary identifier names from e.g. "sizeof" or "str"
  4941. SyntaxStackCnt = oldssp; // undo any temporary declarations from e.g. "sizeof" or "str" in the expression
  4942. return tok;
  4943. }
  4944. word InitArray(word synPtr, word tok)
  4945. {
  4946. word elementTypePtr = synPtr + 3;
  4947. word elementType = SyntaxStack0[elementTypePtr];
  4948. unsigned elementSz = GetDeclSize(elementTypePtr, 0);
  4949. word braces = 0;
  4950. unsigned elementCnt = 0;
  4951. unsigned elementsRequired = SyntaxStack1[synPtr + 1];
  4952. word arrOfChar = (elementType == tokChar) | (elementType == tokUChar) | (elementType == tokSChar);
  4953. if (tok == '{')
  4954. {
  4955. braces = 1;
  4956. tok = GetToken();
  4957. }
  4958. if ((arrOfChar & (tok == tokLitStr))
  4959. )
  4960. {
  4961. word ltok = tok;
  4962. unsigned sz = 0;
  4963. // this is 'someArray[someCountIfAny] = "some string"' or
  4964. // 'someArray[someCountIfAny] = { "some string" }'
  4965. do
  4966. {
  4967. GetString('"', 0, 'd');
  4968. if (sz + TokenStringSize < sz ||
  4969. sz + TokenStringSize >= truncUint(-1))
  4970. errorStrLen();
  4971. sz += TokenStringSize;
  4972. elementCnt += TokenStringLen;
  4973. tok = GetToken();
  4974. } while (tok == ltok); // concatenate adjacent string literals
  4975. if (elementsRequired && elementCnt > elementsRequired)
  4976. errorStrLen();
  4977. if (elementCnt < elementsRequired)
  4978. GenZeroData(elementsRequired - elementCnt, 0);
  4979. if (!elementsRequired)
  4980. GenZeroData(elementSz, 0), elementCnt++;
  4981. if (braces)
  4982. {
  4983. if (tok != '}')
  4984. errorUnexpectedToken(tok);
  4985. tok = GetToken();
  4986. }
  4987. }
  4988. else
  4989. {
  4990. while (tok != '}')
  4991. {
  4992. if (elementType == '[')
  4993. {
  4994. tok = InitArray(elementTypePtr, tok);
  4995. }
  4996. else if (elementType == tokStructPtr)
  4997. {
  4998. tok = InitStruct(elementTypePtr, tok);
  4999. }
  5000. else
  5001. {
  5002. tok = InitScalar(elementTypePtr, tok);
  5003. }
  5004. // Last element?
  5005. if (++elementCnt >= elementsRequired && elementsRequired)
  5006. {
  5007. if (braces & (tok == ','))
  5008. tok = GetToken();
  5009. break;
  5010. }
  5011. if (tok == ',')
  5012. tok = GetToken();
  5013. else if (tok != '}')
  5014. errorUnexpectedToken(tok);
  5015. }
  5016. if (braces)
  5017. {
  5018. if ((!elementCnt) | (tok != '}'))
  5019. errorUnexpectedToken(tok);
  5020. tok = GetToken();
  5021. }
  5022. if (elementCnt < elementsRequired)
  5023. GenZeroData((elementsRequired - elementCnt) * elementSz, 0);
  5024. }
  5025. // Store the element count if it's an incomplete array
  5026. if (!elementsRequired)
  5027. SyntaxStack1[synPtr + 1] = elementCnt;
  5028. return tok;
  5029. }
  5030. word InitStruct(word synPtr, word tok)
  5031. {
  5032. word isUnion;
  5033. unsigned size, ofs = 0;
  5034. word braces = 0;
  5035. word c = 1;
  5036. synPtr = SyntaxStack1[synPtr];
  5037. isUnion = SyntaxStack0[synPtr++] == tokUnion;
  5038. size = SyntaxStack1[++synPtr];
  5039. synPtr += 3; // step inside the {} body of the struct/union
  5040. if (tok == '{')
  5041. {
  5042. braces = 1;
  5043. tok = GetToken();
  5044. }
  5045. // Find the first member
  5046. while (c)
  5047. {
  5048. word t = SyntaxStack0[synPtr];
  5049. c += (t == '(') - (t == ')') + (t == '{') - (t == '}');
  5050. if (c == 1 && t == tokMemberIdent)
  5051. break;
  5052. synPtr++;
  5053. }
  5054. while (tok != '}')
  5055. {
  5056. word c = 1;
  5057. word elementTypePtr, elementType;
  5058. unsigned elementOfs, elementSz;
  5059. elementOfs = SyntaxStack1[++synPtr];
  5060. elementTypePtr = ++synPtr;
  5061. elementType = SyntaxStack0[elementTypePtr];
  5062. elementSz = GetDeclSize(elementTypePtr, 0);
  5063. // Alignment
  5064. if (ofs < elementOfs)
  5065. GenZeroData(elementOfs - ofs, 0);
  5066. if (elementType == '[')
  5067. {
  5068. tok = InitArray(elementTypePtr, tok);
  5069. }
  5070. else if (elementType == tokStructPtr)
  5071. {
  5072. tok = InitStruct(elementTypePtr, tok);
  5073. }
  5074. else
  5075. {
  5076. tok = InitScalar(elementTypePtr, tok);
  5077. }
  5078. ofs = elementOfs + elementSz;
  5079. // Find the next member or the closing brace
  5080. while (c)
  5081. {
  5082. word t = SyntaxStack0[synPtr];
  5083. c += (t == '(') - (t == ')') + (t == '{') - (t == '}');
  5084. if (c == 1 && t == tokMemberIdent)
  5085. break;
  5086. synPtr++;
  5087. }
  5088. // Last member?
  5089. // Only one member (first) is initialized in unions explicitly
  5090. if ((!c) | isUnion)
  5091. {
  5092. if (braces & (tok == ','))
  5093. tok = GetToken();
  5094. break;
  5095. }
  5096. if (tok == ',')
  5097. tok = GetToken();
  5098. else if (tok != '}')
  5099. errorUnexpectedToken(tok);
  5100. }
  5101. if (braces)
  5102. {
  5103. if ((!ofs) | (tok != '}'))
  5104. errorUnexpectedToken(tok);
  5105. tok = GetToken();
  5106. }
  5107. // Implicit initialization of the rest and trailing padding
  5108. if (ofs < size)
  5109. GenZeroData(size - ofs, 0);
  5110. return tok;
  5111. }
  5112. word compatCheck2(word lastSyntaxPtr, word i)
  5113. {
  5114. word res = 0;
  5115. word c = 0;
  5116. word t;
  5117. for (;;)
  5118. {
  5119. t = SyntaxStack0[lastSyntaxPtr];
  5120. if (t != SyntaxStack0[i])
  5121. {
  5122. if (SyntaxStack0[i] == ')' && SyntaxStack0[i - 1] == '(')
  5123. {
  5124. // Complete a previously incomplete parameter specification
  5125. word c1 = 1;
  5126. // Skip over the function params
  5127. do
  5128. {
  5129. t = SyntaxStack0[lastSyntaxPtr++];
  5130. c1 += (t == '(') - (t == ')');
  5131. } while (c1);
  5132. lastSyntaxPtr--;
  5133. }
  5134. else if (t == ')' &&
  5135. SyntaxStack0[i - 1] == '(' && SyntaxStack0[i] == tokIdent &&
  5136. SyntaxStack0[i + 1] == tokVoid && SyntaxStack0[i + 2] == ')')
  5137. {
  5138. // As an exception allow foo(void) to be redeclared as foo()
  5139. // since this happens very often in code.
  5140. // This weakens our redeclaration checks, however. Warn about it.
  5141. i += 2;
  5142. warning("Redeclaration from no parameters to unspecified parameters.\n");
  5143. }
  5144. else
  5145. goto lend;
  5146. }
  5147. if (t != tokIdent &&
  5148. SyntaxStack1[lastSyntaxPtr] != SyntaxStack1[i])
  5149. {
  5150. if (SyntaxStack0[lastSyntaxPtr - 1] == '[')
  5151. {
  5152. // Complete an incomplete array dimension or check for dimension mismatch
  5153. if (SyntaxStack1[lastSyntaxPtr] == 0)
  5154. SyntaxStack1[lastSyntaxPtr] = SyntaxStack1[i];
  5155. else if (SyntaxStack1[i])
  5156. goto lend;
  5157. }
  5158. else
  5159. goto lend;
  5160. }
  5161. c += (t == '(') - (t == ')') + (t == '[') - (t == ']');
  5162. if (!c)
  5163. {
  5164. switch (t)
  5165. {
  5166. case tokVoid:
  5167. case tokChar: case tokSChar: case tokUChar:
  5168. case tokShort: case tokUShort:
  5169. case tokInt: case tokUnsigned:
  5170. case tokStructPtr:
  5171. goto lok;
  5172. }
  5173. }
  5174. lastSyntaxPtr++;
  5175. i++;
  5176. }
  5177. lok:
  5178. res = 1;
  5179. lend:
  5180. return res;
  5181. }
  5182. void CheckRedecl(word lastSyntaxPtr)
  5183. {
  5184. word tid, id, external = 0;
  5185. word i;
  5186. word curScopeOnly;
  5187. word level = ParseLevel;
  5188. tid = SyntaxStack0[lastSyntaxPtr];
  5189. id = SyntaxStack1[lastSyntaxPtr];
  5190. switch (tid)
  5191. {
  5192. case tokIdent:
  5193. switch (SyntaxStack0[lastSyntaxPtr + 1])
  5194. {
  5195. default:
  5196. external = 1;
  5197. // fallthrough
  5198. case tokLocalOfs: // block-scope auto
  5199. case tokIdent: // block-scope static
  5200. ;
  5201. }
  5202. // fallthrough
  5203. case tokTypedef:
  5204. break;
  5205. case tokMemberIdent:
  5206. {
  5207. word c = 1;
  5208. i = lastSyntaxPtr - 1;
  5209. do
  5210. {
  5211. word t = SyntaxStack0[i];
  5212. c -= (t == '(') - (t == ')') + (t == '{') - (t == '}');
  5213. if (c == 1 &&
  5214. t == tokMemberIdent && SyntaxStack1[i] == id &&
  5215. SyntaxStack0[i + 1] == tokLocalOfs)
  5216. errorRedecl(IdentTable + id);
  5217. i--;
  5218. } while (c);
  5219. }
  5220. return;
  5221. default:
  5222. errorInternal(23);
  5223. }
  5224. // limit search to current scope for typedef and enum,
  5225. // ditto for non-external declarations
  5226. curScopeOnly = tid != tokIdent || !external;
  5227. for (i = lastSyntaxPtr - 1; i >= 0; i--)
  5228. {
  5229. word t = SyntaxStack0[i];
  5230. switch (t)
  5231. {
  5232. case ')':
  5233. {
  5234. // Skip over the function params
  5235. word c = -1;
  5236. while (c)
  5237. {
  5238. t = SyntaxStack0[--i];
  5239. c += (t == '(') - (t == ')');
  5240. }
  5241. }
  5242. break;
  5243. case '#':
  5244. // the scope has changed to the outer scope
  5245. if (curScopeOnly)
  5246. return;
  5247. level--;
  5248. break;
  5249. case tokTypedef:
  5250. case tokIdent:
  5251. if (SyntaxStack1[i] == id)
  5252. {
  5253. if (level == ParseLevel)
  5254. {
  5255. // block scope:
  5256. // can differentiate between auto(tokLocalOfs), static(tokIdent),
  5257. // extern/proto(nothing) in SyntaxStack*[], hence dup checks and
  5258. // type match checks needed here
  5259. // file scope:
  5260. // can't differentiate between static(nothing), extern(nothing),
  5261. // neither(nothing) in SyntaxStack*[], but duplicate definitions
  5262. // are taken care of (in CG), hence only type match checks needed
  5263. // here
  5264. if (level) // block scope: check for bad dups
  5265. {
  5266. switch (SyntaxStack0[i + 1])
  5267. {
  5268. case tokLocalOfs: // block-scope auto
  5269. case tokIdent: // block-scope static
  5270. // auto and static can't be redefined in block scope
  5271. errorRedecl(IdentTable + id);
  5272. default:
  5273. // extern can't be redefined as non-extern in block scope
  5274. if (!external)
  5275. errorRedecl(IdentTable + id);
  5276. }
  5277. // extern/proto type match check follows
  5278. }
  5279. if (compatCheck2(lastSyntaxPtr, i))
  5280. return;
  5281. errorRedecl(IdentTable + id);
  5282. }
  5283. else // elseof if (level == ParseLevel)
  5284. {
  5285. // The new decl is extern/proto.
  5286. // Ignore typedef and enum
  5287. if (t == tokIdent)
  5288. {
  5289. switch (SyntaxStack0[i + 1])
  5290. {
  5291. case tokLocalOfs: // block-scope auto
  5292. case tokIdent: // block-scope static
  5293. // Ignore auto and static
  5294. break;
  5295. default:
  5296. // extern/proto
  5297. if (compatCheck2(lastSyntaxPtr, i))
  5298. return;
  5299. errorRedecl(IdentTable + id);
  5300. }
  5301. }
  5302. }
  5303. } // endof if (SyntaxStack1[i] == id)
  5304. break;
  5305. } // endof switch (t)
  5306. } // endof for (i = lastSyntaxPtr - 1; i >= 0; i--)
  5307. }
  5308. // DONE: support extern
  5309. // DONE: support static
  5310. // DONE: support basic initialization
  5311. // DONE: support simple non-array initializations with string literals
  5312. // DONE: support basic 1-d array initialization
  5313. // DONE: global/static data allocations
  5314. word ParseDecl(word tok, unsigned structInfo[4], word cast, word label)
  5315. {
  5316. word base[2];
  5317. word lastSyntaxPtr;
  5318. word external = tok == tokExtern;
  5319. word Static = tok == tokStatic;
  5320. (void)label;
  5321. if (external |
  5322. Static)
  5323. {
  5324. tok = GetToken();
  5325. if (!TokenStartsDeclaration(tok, 1))
  5326. //error("ParseDecl(): unexpected token %s\n", GetTokenName(tok));
  5327. // Implicit int (as in "extern x; static y;") isn't supported
  5328. errorUnexpectedToken(tok);
  5329. }
  5330. tok = ParseBase(tok, base);
  5331. for (;;)
  5332. {
  5333. lastSyntaxPtr = SyntaxStackCnt;
  5334. /* derived type */
  5335. tok = ParseDerived(tok);
  5336. /* base type */
  5337. PushBase(base);
  5338. if ((tok && strchr(",;{=", tok)) || (tok == ')' && ExprLevel))
  5339. {
  5340. word isLocal = 0, isGlobal = 0, isFxn, isStruct, isArray, isIncompleteArr;
  5341. unsigned alignment = 0;
  5342. word staticLabel = 0;
  5343. // Disallow void variables
  5344. if (SyntaxStack0[SyntaxStackCnt - 1] == tokVoid)
  5345. {
  5346. if (SyntaxStack0[SyntaxStackCnt - 2] == tokIdent &&
  5347. !(cast
  5348. ))
  5349. //error("ParseDecl(): Cannot declare a variable ('%s') of type 'void'\n", IdentTable + SyntaxStack1[lastSyntaxPtr]);
  5350. errorUnexpectedVoid();
  5351. }
  5352. isFxn = SyntaxStack0[lastSyntaxPtr + 1] == '(';
  5353. isArray = SyntaxStack0[lastSyntaxPtr + 1] == '[';
  5354. isIncompleteArr = isArray && SyntaxStack1[lastSyntaxPtr + 2] == 0;
  5355. isStruct = SyntaxStack0[lastSyntaxPtr + 1] == tokStructPtr;
  5356. if (!(ExprLevel || structInfo) &&
  5357. !(external |
  5358. Static) &&
  5359. !strcmp(IdentTable + SyntaxStack1[lastSyntaxPtr], "<something>") &&
  5360. tok == ';')
  5361. {
  5362. if (isStruct)
  5363. {
  5364. // This is either an incomplete tagged structure/union declaration, e.g. "struct sometag;",
  5365. // or a tagged complete structure/union declaration, e.g. "struct sometag { ... };", without an instance variable,
  5366. // or an untagged complete structure/union declaration, e.g. "struct { ... };", without an instance variable
  5367. word declPtr, curScope;
  5368. word j = SyntaxStack1[lastSyntaxPtr + 1];
  5369. if (j + 2 < SyntaxStackCnt &&
  5370. IdentTable[SyntaxStack1[j + 1]] == '<' && // without tag
  5371. SyntaxStack0[j + 2] == tokSizeof) // but with the {} "body"
  5372. errorDecl();
  5373. // If a structure/union with this tag has been declared in an outer scope,
  5374. // this new declaration should override it
  5375. declPtr = FindTaggedDecl(IdentTable + SyntaxStack1[j + 1], lastSyntaxPtr - 1, &curScope);
  5376. if (declPtr >= 0 && !curScope)
  5377. {
  5378. // If that's the case, unbind this declaration from the old declaration
  5379. // and make it a new incomplete declaration
  5380. PushSyntax(SyntaxStack0[j]); // tokStruct or tokUnion
  5381. PushSyntax2(tokTag, SyntaxStack1[j + 1]);
  5382. SyntaxStack1[lastSyntaxPtr + 1] = SyntaxStackCnt - 2;
  5383. }
  5384. return GetToken();
  5385. }
  5386. }
  5387. // Structure/union members can't be initialized nor be functions nor
  5388. // be incompletely typed arrays inside structure/union declarations
  5389. if (structInfo && ((tok == '=') | isFxn | (tok == '{') | isIncompleteArr))
  5390. errorDecl();
  5391. // Error conditions in declarations(/definitions/initializations):
  5392. // Legend:
  5393. // + error
  5394. // - no error
  5395. //
  5396. // file scope fxn fxn {} var arr[] arr[]...[] arr[incomplete] arr[incomplete]...[]
  5397. // - - - - - + +
  5398. // file scope fxn= var= arr[]= arr[]...[]= arr[incomplete]= arr[incomplete]...[]=
  5399. // + - - + - +
  5400. // file scope extern fxn fxn {} var arr[] arr[]...[] arr[incomplete] arr[incomplete]...[]
  5401. // - - - - - - -
  5402. // file scope extern fxn= var= arr[]= arr[]...[]= arr[incomplete]= arr[incomplete]...[]=
  5403. // + + + + + +
  5404. // file scope static fxn fxn {} var arr[] arr[]...[] arr[incomplete] arr[incomplete]...[]
  5405. // - - - - - + +
  5406. // file scope static fxn= var= arr[]= arr[]...[]= arr[incomplete]= arr[incomplete]...[]=
  5407. // + - - + - +
  5408. // fxn scope fxn fxn {} var arr[] arr[]...[] arr[incomplete] arr[incomplete]...[]
  5409. // - + - - - + +
  5410. // fxn scope fxn= var= arr[]= arr[]...[]= arr[incomplete]= arr[incomplete]...[]=
  5411. // + - + + + +
  5412. // fxn scope extern fxn fxn {} var arr[] arr[]...[] arr[incomplete] arr[incomplete]...[]
  5413. // - + - - - - -
  5414. // fxn scope extern fxn= var= arr[]= arr[]...[]= arr[incomplete]= arr[incomplete]...[]=
  5415. // + + + + + +
  5416. // fxn scope static fxn fxn {} var arr[] arr[]...[] arr[incomplete] arr[incomplete]...[]
  5417. // + + + + + + +
  5418. // fxn scope static fxn= var= arr[]= arr[]...[]= arr[incomplete]= arr[incomplete]...[]=
  5419. // + + + + + +
  5420. if (isFxn & (tok == '='))
  5421. //error("ParseDecl(): cannot initialize a function\n");
  5422. errorInit();
  5423. if ((isFxn & (tok == '{')) && ParseLevel)
  5424. //error("ParseDecl(): cannot define a nested function\n");
  5425. errorDecl();
  5426. if ((isFxn & Static) && ParseLevel)
  5427. //error("ParseDecl(): cannot declare a static function in this scope\n");
  5428. errorDecl();
  5429. if (external & (tok == '='))
  5430. //error("ParseDecl(): cannot initialize an external variable\n");
  5431. errorInit();
  5432. if (isIncompleteArr & !(external |
  5433. (tok == '=')))
  5434. //error("ParseDecl(): cannot define an array of incomplete type\n");
  5435. errorDecl();
  5436. // TBD!!! de-uglify
  5437. if (!strcmp(IdentTable + SyntaxStack1[lastSyntaxPtr], "<something>"))
  5438. {
  5439. // Disallow nameless variables, prototypes, structure/union members and typedefs.
  5440. if (structInfo ||
  5441. !ExprLevel)
  5442. error("Identifier expected in declaration\n");
  5443. }
  5444. else
  5445. {
  5446. // Disallow named variables and prototypes in sizeof(typedecl) and (typedecl).
  5447. if (ExprLevel && !structInfo)
  5448. error("Identifier unexpected in declaration\n");
  5449. }
  5450. if (!isFxn
  5451. )
  5452. {
  5453. // This is a variable or a variable (member) in a struct/union declaration
  5454. word sz = GetDeclSize(lastSyntaxPtr, 0);
  5455. if (!((sz | isIncompleteArr) || ExprLevel)) // incomplete type
  5456. errorDecl(); // TBD!!! different error when struct/union tag is not found
  5457. if (isArray && !GetDeclSize(lastSyntaxPtr + 4, 0))
  5458. // incomplete type of array element (e.g. struct/union)
  5459. errorDecl();
  5460. alignment = GetDeclAlignment(lastSyntaxPtr);
  5461. if (structInfo)
  5462. {
  5463. // It's a variable (member) in a struct/union declaration
  5464. unsigned tmp;
  5465. unsigned newAlignment = alignment;
  5466. // Update structure/union alignment
  5467. if (structInfo[1] < newAlignment)
  5468. structInfo[1] = newAlignment;
  5469. // Align structure member
  5470. tmp = structInfo[2];
  5471. structInfo[2] = (structInfo[2] + newAlignment - 1) & ~(newAlignment - 1);
  5472. if (structInfo[2] < tmp || structInfo[2] != truncUint(structInfo[2]))
  5473. {
  5474. //printf("f");
  5475. errorVarSize();
  5476. }
  5477. // Change tokIdent to tokMemberIdent and insert a local var offset token
  5478. SyntaxStack0[lastSyntaxPtr] = tokMemberIdent;
  5479. InsertSyntax2(lastSyntaxPtr + 1, tokLocalOfs, (word)structInfo[2]);
  5480. // Advance member offset for structures, keep it zero for unions
  5481. if (structInfo[0] == tokStruct)
  5482. {
  5483. tmp = structInfo[2];
  5484. structInfo[2] += sz;
  5485. if (structInfo[2] < tmp || structInfo[2] != truncUint(structInfo[2]))
  5486. {
  5487. //printf("g");
  5488. errorVarSize();
  5489. }
  5490. }
  5491. // Update max member size for unions
  5492. else if (structInfo[3] < (unsigned)sz)
  5493. {
  5494. structInfo[3] = sz;
  5495. }
  5496. }
  5497. else if (ParseLevel && !((external | Static) || ExprLevel))
  5498. {
  5499. // It's a local variable
  5500. isLocal = 1;
  5501. // Defer size calculation until initialization
  5502. // Insert a local var offset token, the offset is to be updated
  5503. InsertSyntax2(lastSyntaxPtr + 1, tokLocalOfs, 0);
  5504. }
  5505. else if (!ExprLevel)
  5506. {
  5507. // It's a global variable (external, static or neither)
  5508. isGlobal = 1;
  5509. if (Static && ParseLevel)
  5510. {
  5511. // It's a static variable in function scope, "rename" it by providing
  5512. // an alternative unique numeric identifier right next to it and use it
  5513. staticLabel = LabelCnt++;
  5514. InsertSyntax2(lastSyntaxPtr + 1, tokIdent, AddNumericIdent(staticLabel));
  5515. }
  5516. }
  5517. }
  5518. // If it's a type declaration in a sizeof(typedecl) expression or
  5519. // in an expression with a cast, e.g. (typedecl)expr, we're done
  5520. if (ExprLevel && !structInfo)
  5521. {
  5522. if (doAnnotations)
  5523. {
  5524. DumpDecl(lastSyntaxPtr, 0);
  5525. }
  5526. return tok;
  5527. }
  5528. if (isLocal | isGlobal)
  5529. {
  5530. word hasInit = tok == '=';
  5531. word needsGlobalInit = isGlobal & !external;
  5532. word sz = GetDeclSize(lastSyntaxPtr, 0);
  5533. word initLabel = 0;
  5534. word bss = (!hasInit) & UseBss;
  5535. if (doAnnotations)
  5536. {
  5537. if (isGlobal)
  5538. DumpDecl(lastSyntaxPtr, 0);
  5539. }
  5540. if (hasInit)
  5541. {
  5542. tok = GetToken();
  5543. }
  5544. if (isLocal & hasInit)
  5545. needsGlobalInit = isArray | (isStruct & (tok == '{'));
  5546. if (needsGlobalInit)
  5547. {
  5548. char** oldHeaderFooter = CurHeaderFooter;
  5549. if (oldHeaderFooter)
  5550. puts2(oldHeaderFooter[1]);
  5551. CurHeaderFooter = bss ? BssHeaderFooter : DataHeaderFooter;
  5552. puts2(CurHeaderFooter[0]);
  5553. // DONE: imperfect condition for alignment
  5554. if (alignment != 1)
  5555. GenWordAlignment(bss);
  5556. if (isGlobal)
  5557. {
  5558. if (Static && ParseLevel)
  5559. GenNumLabel(staticLabel);
  5560. else
  5561. GenLabel(IdentTable + SyntaxStack1[lastSyntaxPtr], Static);
  5562. }
  5563. else
  5564. {
  5565. // Generate numeric labels for global initializers of local vars
  5566. GenNumLabel(initLabel = LabelCnt++);
  5567. }
  5568. // Generate global initializers
  5569. if (hasInit)
  5570. {
  5571. if (doAnnotations)
  5572. {
  5573. if (isGlobal)
  5574. {
  5575. GenStartCommentLine(); printf2("=\n");
  5576. }
  5577. }
  5578. tok = InitVar(lastSyntaxPtr, tok);
  5579. // Update the size in case it's an incomplete array
  5580. sz = GetDeclSize(lastSyntaxPtr, 0);
  5581. }
  5582. else
  5583. {
  5584. GenZeroData(sz, bss);
  5585. }
  5586. puts2(CurHeaderFooter[1]);
  5587. if (oldHeaderFooter)
  5588. puts2(oldHeaderFooter[0]);
  5589. CurHeaderFooter = oldHeaderFooter;
  5590. }
  5591. if (isLocal)
  5592. {
  5593. // Now that the size of the local is certainly known,
  5594. // update its offset in the offset token
  5595. SyntaxStack1[lastSyntaxPtr + 1] = AllocLocal(sz);
  5596. if (doAnnotations)
  5597. {
  5598. DumpDecl(lastSyntaxPtr, 0);
  5599. }
  5600. }
  5601. // Copy global initializers into local vars
  5602. if (isLocal & needsGlobalInit)
  5603. {
  5604. if (doAnnotations)
  5605. {
  5606. GenStartCommentLine(); printf2("=\n");
  5607. }
  5608. if (!StructCpyLabel)
  5609. StructCpyLabel = LabelCnt++;
  5610. sp = 0;
  5611. push2('(', SizeOfWord * 3);
  5612. push2(tokLocalOfs, SyntaxStack1[lastSyntaxPtr + 1]);
  5613. push(',');
  5614. push2(tokIdent, AddNumericIdent(initLabel));
  5615. push(',');
  5616. push2(tokNumUint, sz);
  5617. push(',');
  5618. push2(tokIdent, AddNumericIdent(StructCpyLabel));
  5619. push2(')', SizeOfWord * 3);
  5620. GenExpr();
  5621. }
  5622. // Initialize local vars with expressions
  5623. else if (hasInit & !needsGlobalInit)
  5624. {
  5625. word gotUnary, synPtr, constExpr, exprVal;
  5626. word brace = 0;
  5627. // Initializers for scalars can be optionally enclosed in braces
  5628. if ((!isStruct) & (tok == '{'))
  5629. {
  5630. brace = 1;
  5631. tok = GetToken();
  5632. }
  5633. // ParseExpr() will transform the initializer expression into an assignment expression here
  5634. tok = ParseExpr(tok, &gotUnary, &synPtr, &constExpr, &exprVal, '=', SyntaxStack1[lastSyntaxPtr]);
  5635. if (!gotUnary)
  5636. errorUnexpectedToken(tok);
  5637. if (brace)
  5638. {
  5639. if (tok != '}')
  5640. errorUnexpectedToken(tok);
  5641. tok = GetToken();
  5642. }
  5643. if (!isStruct)
  5644. {
  5645. // This is a special case for initialization of integers smaller than int.
  5646. // Since a local integer variable always takes as much space as a whole int,
  5647. // we can optimize code generation a bit by storing the initializer as an int.
  5648. // This is an old accidental optimization and I preserve it for now.
  5649. // Note, this implies a little-endian CPU.
  5650. stack[sp - 1][1] = SizeOfWord;
  5651. }
  5652. // Storage of string literal data from the initializing expression
  5653. // occurs here.
  5654. GenExpr();
  5655. }
  5656. }
  5657. else if (tok == '{')
  5658. {
  5659. // It's a function body. Let's add function parameters as
  5660. // local variables to the symbol table and parse the body.
  5661. word undoSymbolsPtr = SyntaxStackCnt;
  5662. word undoIdents = IdentTableLen;
  5663. word i;
  5664. word endLabel = 0;
  5665. if (doAnnotations)
  5666. {
  5667. DumpDecl(lastSyntaxPtr, 0);
  5668. }
  5669. CurFxnName = IdentTable + SyntaxStack1[lastSyntaxPtr];
  5670. IsMain = !strcmp(CurFxnName, "main");
  5671. gotoLabCnt = 0;
  5672. if (verbose)
  5673. {
  5674. printf(CurFxnName);
  5675. printf("()\n");
  5676. }
  5677. ParseLevel++;
  5678. GetFxnInfo(lastSyntaxPtr, &CurFxnParamCntMin, &CurFxnParamCntMax, &CurFxnReturnExprTypeSynPtr, NULL); // get return type
  5679. CurHeaderFooter = CodeHeaderFooter;
  5680. puts2(CurHeaderFooter[0]);
  5681. //BDOS_PrintlnConsole(CurFxnName);
  5682. //printf2("; put the function label here:\n");
  5683. GenLabel(CurFxnName, Static);
  5684. GenFxnProlog();
  5685. CurFxnEpilogLabel = LabelCnt++;
  5686. // A new scope begins before the function parameters
  5687. PushSyntax('#');
  5688. AddFxnParamSymbols(lastSyntaxPtr);
  5689. // The block doesn't begin yet another new scope.
  5690. // This is to catch redeclarations of the function parameters.
  5691. tok = ParseBlock(BrkCntTargetFxn, 0);
  5692. ParseLevel--;
  5693. if (tok != '}')
  5694. //error("ParseDecl(): '}' expected\n");
  5695. errorUnexpectedToken(tok);
  5696. for (i = 0; i < gotoLabCnt; i++)
  5697. if (gotoLabStat[i] == 2)
  5698. {
  5699. printf("Undeclared label ");
  5700. error(IdentTable + gotoLabels[i][0]);
  5701. }
  5702. // DONE: if execution of main() reaches here, before the epilog (i.e. without using return),
  5703. // main() should return 0.
  5704. if (IsMain)
  5705. {
  5706. sp = 0;
  5707. push(tokNumInt);
  5708. push(tokReturn); // value produced by generated code is used
  5709. GenExpr();
  5710. }
  5711. GenNumLabel(CurFxnEpilogLabel);
  5712. GenFxnEpilog();
  5713. if (GenFxnSizeNeeded())
  5714. GenNumLabel(endLabel = LabelCnt++);
  5715. puts2(CurHeaderFooter[1]);
  5716. CurHeaderFooter = NULL;
  5717. if (GenFxnSizeNeeded())
  5718. GenRecordFxnSize(CurFxnName, endLabel);
  5719. CurFxnName = NULL;
  5720. IdentTableLen = undoIdents; // remove all identifier names
  5721. SyntaxStackCnt = undoSymbolsPtr; // remove all params and locals
  5722. SyntaxStack1[SymFuncPtr] = DummyIdent;
  5723. }
  5724. else if (isFxn)
  5725. {
  5726. if (doAnnotations)
  5727. {
  5728. // function prototype
  5729. DumpDecl(lastSyntaxPtr, 0);
  5730. }
  5731. }
  5732. CheckRedecl(lastSyntaxPtr);
  5733. if ((tok == ';') | (tok == '}'))
  5734. break;
  5735. tok = GetToken();
  5736. continue;
  5737. }
  5738. //error("ParseDecl(): unexpected token %s\n", GetTokenName(tok));
  5739. errorUnexpectedToken(tok);
  5740. }
  5741. tok = GetToken();
  5742. return tok;
  5743. }
  5744. void ParseFxnParams(word tok)
  5745. {
  5746. word base[2];
  5747. word lastSyntaxPtr;
  5748. word cnt = 0;
  5749. word ellCnt = 0;
  5750. for (;;)
  5751. {
  5752. lastSyntaxPtr = SyntaxStackCnt;
  5753. if (tok == ')') /* unspecified params */
  5754. break;
  5755. if (!TokenStartsDeclaration(tok, 1))
  5756. {
  5757. if (tok == tokEllipsis)
  5758. {
  5759. // "..." cannot be the first parameter and
  5760. // it can be only one
  5761. if (!cnt || ellCnt)
  5762. //error("ParseFxnParams(): '...' unexpected here\n");
  5763. errorUnexpectedToken(tok);
  5764. ellCnt++;
  5765. }
  5766. else
  5767. //error("ParseFxnParams(): Unexpected token %s\n", GetTokenName(tok));
  5768. errorUnexpectedToken(tok);
  5769. base[0] = tok; // "..."
  5770. base[1] = 0;
  5771. PushSyntax2(tokIdent, AddIdent("<something>"));
  5772. tok = GetToken();
  5773. }
  5774. else
  5775. {
  5776. if (ellCnt)
  5777. //error("ParseFxnParams(): '...' must be the last in the parameter list\n");
  5778. errorUnexpectedToken(tok);
  5779. /* base type */
  5780. tok = ParseBase(tok, base);
  5781. /* derived type */
  5782. tok = ParseDerived(tok);
  5783. }
  5784. /* base type */
  5785. PushBase(base);
  5786. /* Decay arrays to pointers */
  5787. lastSyntaxPtr++; /* skip name */
  5788. if (SyntaxStack0[lastSyntaxPtr] == '[')
  5789. {
  5790. word t;
  5791. DeleteSyntax(lastSyntaxPtr, 1);
  5792. t = SyntaxStack0[lastSyntaxPtr];
  5793. if (t == tokNumInt || t == tokNumUint)
  5794. DeleteSyntax(lastSyntaxPtr, 1);
  5795. SyntaxStack0[lastSyntaxPtr] = '*';
  5796. }
  5797. /* "(Un)decay" functions to function pointers */
  5798. else if (SyntaxStack0[lastSyntaxPtr] == '(')
  5799. {
  5800. InsertSyntax(lastSyntaxPtr, '*');
  5801. }
  5802. lastSyntaxPtr--; /* "unskip" name */
  5803. cnt++;
  5804. if (tok == ')' || tok == ',')
  5805. {
  5806. word t = SyntaxStack0[SyntaxStackCnt - 2];
  5807. if (SyntaxStack0[SyntaxStackCnt - 1] == tokVoid)
  5808. {
  5809. // Disallow void variables. TBD!!! de-uglify
  5810. if (t == tokIdent &&
  5811. !(!strcmp(IdentTable + SyntaxStack1[SyntaxStackCnt - 2], "<something>") &&
  5812. cnt == 1 && tok == ')'))
  5813. //error("ParseFxnParams(): Cannot declare a variable ('%s') of type 'void'\n", IdentTable + SyntaxStack1[lastSyntaxPtr]);
  5814. errorUnexpectedVoid();
  5815. }
  5816. if (tok == ')')
  5817. break;
  5818. tok = GetToken();
  5819. continue;
  5820. }
  5821. //error("ParseFxnParams(): Unexpected token %s\n", GetTokenName(tok));
  5822. errorUnexpectedToken(tok);
  5823. }
  5824. }
  5825. void AddFxnParamSymbols(word SyntaxPtr)
  5826. {
  5827. word i;
  5828. unsigned paramOfs = 2 * SizeOfWord; // ret addr, xbp
  5829. if (SyntaxPtr < 0 ||
  5830. SyntaxPtr > SyntaxStackCnt - 3 ||
  5831. SyntaxStack0[SyntaxPtr] != tokIdent ||
  5832. SyntaxStack0[SyntaxPtr + 1] != '(')
  5833. //error("Internal error: AddFxnParamSymbols(): Invalid input\n");
  5834. errorInternal(6);
  5835. CurFxnSyntaxPtr = SyntaxPtr;
  5836. CurFxnLocalOfs = 0;
  5837. CurFxnMinLocalOfs = 0;
  5838. SyntaxPtr += 2; // skip "ident("
  5839. for (i = SyntaxPtr; i < SyntaxStackCnt; i++)
  5840. {
  5841. word tok = SyntaxStack0[i];
  5842. if (tok == tokIdent)
  5843. {
  5844. unsigned sz;
  5845. word paramPtr;
  5846. if (i + 1 >= SyntaxStackCnt)
  5847. //error("Internal error: AddFxnParamSymbols(): Invalid input\n");
  5848. errorInternal(7);
  5849. if (SyntaxStack0[i + 1] == tokVoid) // "ident(void)" = no params
  5850. break;
  5851. if (SyntaxStack0[i + 1] == tokEllipsis) // "ident(something,...)" = no more params
  5852. break;
  5853. // Make sure the parameter is not an incomplete structure
  5854. sz = GetDeclSize(i, 0);
  5855. if (sz == 0)
  5856. //error("Internal error: AddFxnParamSymbols(): GetDeclSize() = 0\n");
  5857. //errorInternal(8);
  5858. errorDecl();
  5859. // Let's calculate this parameter's relative on-stack location
  5860. paramPtr = SyntaxStackCnt;
  5861. PushSyntax2(SyntaxStack0[i], SyntaxStack1[i]);
  5862. PushSyntax2(tokLocalOfs, paramOfs);
  5863. if (sz + SizeOfWord - 1 < sz)
  5864. {
  5865. //printf("h");
  5866. errorVarSize();
  5867. }
  5868. sz = (sz + SizeOfWord - 1) & ~(SizeOfWord - 1u);
  5869. if (paramOfs + sz < paramOfs)
  5870. {
  5871. //printf("i");
  5872. errorVarSize();
  5873. }
  5874. paramOfs += sz;
  5875. if (paramOfs > (unsigned)GenMaxLocalsSize())
  5876. {
  5877. //printf("j");
  5878. errorVarSize();
  5879. }
  5880. // Duplicate this parameter in the symbol table
  5881. i++;
  5882. while (i < SyntaxStackCnt)
  5883. {
  5884. tok = SyntaxStack0[i];
  5885. if (tok == tokIdent || tok == ')')
  5886. {
  5887. if (doAnnotations)
  5888. {
  5889. DumpDecl(paramPtr, 0);
  5890. }
  5891. if (IdentTable[SyntaxStack1[paramPtr]] == '<')
  5892. error("Parameter name expected\n");
  5893. CheckRedecl(paramPtr);
  5894. i--;
  5895. break;
  5896. }
  5897. else if (tok == '(')
  5898. {
  5899. word c = 1;
  5900. i++;
  5901. PushSyntax(tok);
  5902. while (c && i < SyntaxStackCnt)
  5903. {
  5904. tok = SyntaxStack0[i];
  5905. c += (tok == '(') - (tok == ')');
  5906. PushSyntax2(SyntaxStack0[i], SyntaxStack1[i]);
  5907. i++;
  5908. }
  5909. }
  5910. else
  5911. {
  5912. PushSyntax2(SyntaxStack0[i], SyntaxStack1[i]);
  5913. i++;
  5914. }
  5915. }
  5916. }
  5917. else if (tok == ')') // endof "ident(" ... ")"
  5918. break;
  5919. else
  5920. //error("Internal error: AddFxnParamSymbols(): Unexpected token %s\n", GetTokenName(tok));
  5921. errorInternal(9);
  5922. }
  5923. }
  5924. word ParseStatement(word tok, word BrkCntTarget[2], word casesIdx)
  5925. {
  5926. /*
  5927. labeled statements:
  5928. + ident : statement
  5929. + case const-expr : statement
  5930. + default : statement
  5931. compound statement:
  5932. + { declaration(s)/statement(s)-opt }
  5933. expression statement:
  5934. + expression-opt ;
  5935. selection statements:
  5936. + if ( expression ) statement
  5937. + if ( expression ) statement else statement
  5938. + switch ( expression ) { statement(s)-opt }
  5939. iteration statements:
  5940. + while ( expression ) statement
  5941. + do statement while ( expression ) ;
  5942. + for ( expression-opt ; expression-opt ; expression-opt ) statement
  5943. jump statements:
  5944. + goto ident ;
  5945. + continue ;
  5946. + break ;
  5947. + return expression-opt ;
  5948. */
  5949. word gotUnary, synPtr, constExpr, exprVal;
  5950. word brkCntTarget[2];
  5951. word statementNeeded;
  5952. do
  5953. {
  5954. statementNeeded = 0;
  5955. if (tok == ';')
  5956. {
  5957. tok = GetToken();
  5958. }
  5959. else if (tok == '{')
  5960. {
  5961. // A new {} block begins in the function body
  5962. word undoSymbolsPtr = SyntaxStackCnt;
  5963. word undoLocalOfs = CurFxnLocalOfs;
  5964. word undoIdents = IdentTableLen;
  5965. if (doAnnotations)
  5966. {
  5967. GenStartCommentLine(); printf2("{\n");
  5968. }
  5969. ParseLevel++;
  5970. tok = ParseBlock(BrkCntTarget, casesIdx);
  5971. ParseLevel--;
  5972. if (tok != '}')
  5973. //error("ParseStatement(): '}' expected. Unexpected token %s\n", GetTokenName(tok));
  5974. errorUnexpectedToken(tok);
  5975. UndoNonLabelIdents(undoIdents); // remove all identifier names, except those of labels
  5976. SyntaxStackCnt = undoSymbolsPtr; // remove all params and locals
  5977. CurFxnLocalOfs = undoLocalOfs; // destroy on-stack local variables
  5978. if (doAnnotations)
  5979. {
  5980. GenStartCommentLine(); printf2("}\n");
  5981. }
  5982. tok = GetToken();
  5983. }
  5984. else if (tok == tokReturn)
  5985. {
  5986. // DONE: functions returning void vs non-void
  5987. word retVoid = CurFxnReturnExprTypeSynPtr >= 0 &&
  5988. SyntaxStack0[CurFxnReturnExprTypeSynPtr] == tokVoid;
  5989. if (doAnnotations)
  5990. {
  5991. GenStartCommentLine(); printf2("return\n");
  5992. }
  5993. tok = GetToken();
  5994. if (tok == ';')
  5995. {
  5996. gotUnary = 0;
  5997. if (!retVoid)
  5998. //error("ParseStatement(): missing return value\n");
  5999. errorUnexpectedToken(tok);
  6000. }
  6001. else
  6002. {
  6003. if (retVoid)
  6004. //error("Error: ParseStatement(): cannot return a value from a function returning 'void'\n");
  6005. errorUnexpectedToken(tok);
  6006. if ((tok = ParseExpr(tok, &gotUnary, &synPtr, &constExpr, &exprVal, 0, 0)) != ';')
  6007. //error("ParseStatement(): ';' expected\n");
  6008. errorUnexpectedToken(tok);
  6009. if (gotUnary)
  6010. //error("ParseStatement(): cannot return a value of type 'void'\n");
  6011. // Bar void
  6012. nonVoidTypeCheck(synPtr);
  6013. }
  6014. if (gotUnary)
  6015. {
  6016. decayArray(&synPtr, 0);
  6017. {
  6018. word castSize = GetDeclSize(CurFxnReturnExprTypeSynPtr, 1);
  6019. // If return value (per function declaration) is a scalar type smaller than machine word,
  6020. // properly zero- or sign-extend the returned value to machine word size.
  6021. // TBD??? Move this cast to the caller?
  6022. if (castSize != SizeOfWord && castSize != GetDeclSize(synPtr, 1))
  6023. {
  6024. if (constExpr)
  6025. {
  6026. switch (castSize)
  6027. {
  6028. case 1:
  6029. exprVal &= 0xFFu;
  6030. break;
  6031. case -1:
  6032. if ((exprVal &= 0xFFu) >= 0x80)
  6033. exprVal -= 0x100;
  6034. break;
  6035. case 2:
  6036. exprVal &= 0xFFFFu;
  6037. break;
  6038. case -2:
  6039. if ((exprVal &= 0xFFFFu) >= 0x8000)
  6040. exprVal -= 0x10000;
  6041. break;
  6042. }
  6043. }
  6044. else
  6045. {
  6046. switch (castSize)
  6047. {
  6048. case 1:
  6049. push(tokUChar);
  6050. break;
  6051. case -1:
  6052. push(tokSChar);
  6053. break;
  6054. case 2:
  6055. push(tokUShort);
  6056. break;
  6057. case -2:
  6058. push(tokShort);
  6059. break;
  6060. }
  6061. }
  6062. }
  6063. }
  6064. if (constExpr)
  6065. stack[0][1] = exprVal;
  6066. push(tokReturn); // value produced by generated code is used
  6067. GenExpr();
  6068. }
  6069. tok = GetToken();
  6070. // If this return is the last statement in the function, the epilogue immediately
  6071. // follows and there's no need to jump to it.
  6072. if (!(tok == '}' && ParseLevel == 1 && !IsMain))
  6073. GenJumpUncond(CurFxnEpilogLabel);
  6074. }
  6075. else if (tok == tokWhile)
  6076. {
  6077. word labelBefore = LabelCnt++;
  6078. word labelAfter = LabelCnt++;
  6079. word forever = 0;
  6080. if (doAnnotations)
  6081. {
  6082. GenStartCommentLine(); printf2("while\n");
  6083. }
  6084. tok = GetToken();
  6085. if (tok != '(')
  6086. //error("ParseStatement(): '(' expected after 'while'\n");
  6087. errorUnexpectedToken(tok);
  6088. tok = GetToken();
  6089. if ((tok = ParseExpr(tok, &gotUnary, &synPtr, &constExpr, &exprVal, 0, 0)) != ')')
  6090. //error("ParseStatement(): ')' expected after 'while ( expression'\n");
  6091. errorUnexpectedToken(tok);
  6092. if (!gotUnary)
  6093. //error("ParseStatement(): expression expected in 'while ( expression )'\n");
  6094. errorUnexpectedToken(tok);
  6095. // DONE: void control expressions
  6096. //error("ParseStatement(): unexpected 'void' expression in 'while ( expression )'\n");
  6097. // Bar void and struct/union
  6098. scalarTypeCheck(synPtr);
  6099. GenNumLabel(labelBefore);
  6100. if (constExpr)
  6101. {
  6102. // Special cases for while(0) and while(1)
  6103. if (!(forever = truncInt(exprVal)))
  6104. GenJumpUncond(labelAfter);
  6105. }
  6106. else
  6107. {
  6108. switch (stack[sp - 1][0])
  6109. {
  6110. case '<':
  6111. case '>':
  6112. case tokEQ:
  6113. case tokNEQ:
  6114. case tokLEQ:
  6115. case tokGEQ:
  6116. case tokULess:
  6117. case tokUGreater:
  6118. case tokULEQ:
  6119. case tokUGEQ:
  6120. push2(tokIfNot, labelAfter);
  6121. GenExpr();
  6122. break;
  6123. default:
  6124. push(tokReturn); // value produced by generated code is used
  6125. GenExpr();
  6126. GenJumpIfZero(labelAfter);
  6127. break;
  6128. }
  6129. }
  6130. tok = GetToken();
  6131. brkCntTarget[0] = labelAfter; // break target
  6132. brkCntTarget[1] = labelBefore; // continue target
  6133. tok = ParseStatement(tok, brkCntTarget, casesIdx);
  6134. // Special case for while(0)
  6135. if (!(constExpr && !forever))
  6136. GenJumpUncond(labelBefore);
  6137. GenNumLabel(labelAfter);
  6138. }
  6139. else if (tok == tokDo)
  6140. {
  6141. word labelBefore = LabelCnt++;
  6142. word labelWhile = LabelCnt++;
  6143. word labelAfter = LabelCnt++;
  6144. if (doAnnotations)
  6145. {
  6146. GenStartCommentLine(); printf2("do\n");
  6147. }
  6148. GenNumLabel(labelBefore);
  6149. tok = GetToken();
  6150. brkCntTarget[0] = labelAfter; // break target
  6151. brkCntTarget[1] = labelWhile; // continue target
  6152. tok = ParseStatement(tok, brkCntTarget, casesIdx);
  6153. if (tok != tokWhile)
  6154. //error("ParseStatement(): 'while' expected after 'do statement'\n");
  6155. errorUnexpectedToken(tok);
  6156. if (doAnnotations)
  6157. {
  6158. GenStartCommentLine(); printf2("while\n");
  6159. }
  6160. tok = GetToken();
  6161. if (tok != '(')
  6162. //error("ParseStatement(): '(' expected after 'while'\n");
  6163. errorUnexpectedToken(tok);
  6164. tok = GetToken();
  6165. if ((tok = ParseExpr(tok, &gotUnary, &synPtr, &constExpr, &exprVal, 0, 0)) != ')')
  6166. //error("ParseStatement(): ')' expected after 'while ( expression'\n");
  6167. errorUnexpectedToken(tok);
  6168. if (!gotUnary)
  6169. //error("ParseStatement(): expression expected in 'while ( expression )'\n");
  6170. errorUnexpectedToken(tok);
  6171. tok = GetToken();
  6172. if (tok != ';')
  6173. //error("ParseStatement(): ';' expected after 'do statement while ( expression )'\n");
  6174. errorUnexpectedToken(tok);
  6175. // DONE: void control expressions
  6176. //error("ParseStatement(): unexpected 'void' expression in 'while ( expression )'\n");
  6177. // Bar void and struct/union
  6178. scalarTypeCheck(synPtr);
  6179. GenNumLabel(labelWhile);
  6180. if (constExpr)
  6181. {
  6182. // Special cases for while(0) and while(1)
  6183. if (truncInt(exprVal))
  6184. GenJumpUncond(labelBefore);
  6185. }
  6186. else
  6187. {
  6188. switch (stack[sp - 1][0])
  6189. {
  6190. case '<':
  6191. case '>':
  6192. case tokEQ:
  6193. case tokNEQ:
  6194. case tokLEQ:
  6195. case tokGEQ:
  6196. case tokULess:
  6197. case tokUGreater:
  6198. case tokULEQ:
  6199. case tokUGEQ:
  6200. push2(tokIf, labelBefore);
  6201. GenExpr();
  6202. break;
  6203. default:
  6204. push(tokReturn); // value produced by generated code is used
  6205. GenExpr();
  6206. GenJumpIfNotZero(labelBefore);
  6207. break;
  6208. }
  6209. }
  6210. GenNumLabel(labelAfter);
  6211. tok = GetToken();
  6212. }
  6213. else if (tok == tokIf)
  6214. {
  6215. word labelAfterIf = LabelCnt++;
  6216. word labelAfterElse = LabelCnt++;
  6217. if (doAnnotations)
  6218. {
  6219. GenStartCommentLine(); printf2("if\n");
  6220. }
  6221. tok = GetToken();
  6222. if (tok != '(')
  6223. //error("ParseStatement(): '(' expected after 'if'\n");
  6224. errorUnexpectedToken(tok);
  6225. tok = GetToken();
  6226. if ((tok = ParseExpr(tok, &gotUnary, &synPtr, &constExpr, &exprVal, 0, 0)) != ')')
  6227. //error("ParseStatement(): ')' expected after 'if ( expression'\n");
  6228. errorUnexpectedToken(tok);
  6229. if (!gotUnary)
  6230. //error("ParseStatement(): expression expected in 'if ( expression )'\n");
  6231. errorUnexpectedToken(tok);
  6232. // DONE: void control expressions
  6233. //error("ParseStatement(): unexpected 'void' expression in 'if ( expression )'\n");
  6234. // Bar void and struct/union
  6235. scalarTypeCheck(synPtr);
  6236. if (constExpr)
  6237. {
  6238. // Special cases for if(0) and if(1)
  6239. if (!truncInt(exprVal))
  6240. GenJumpUncond(labelAfterIf);
  6241. }
  6242. else
  6243. {
  6244. switch (stack[sp - 1][0])
  6245. {
  6246. case '<':
  6247. case '>':
  6248. case tokEQ:
  6249. case tokNEQ:
  6250. case tokLEQ:
  6251. case tokGEQ:
  6252. case tokULess:
  6253. case tokUGreater:
  6254. case tokULEQ:
  6255. case tokUGEQ:
  6256. push2(tokIfNot, labelAfterIf);
  6257. GenExpr();
  6258. break;
  6259. default:
  6260. push(tokReturn); // value produced by generated code is used
  6261. GenExpr();
  6262. GenJumpIfZero(labelAfterIf);
  6263. break;
  6264. }
  6265. }
  6266. tok = GetToken();
  6267. tok = ParseStatement(tok, BrkCntTarget, casesIdx);
  6268. // DONE: else
  6269. if (tok == tokElse)
  6270. {
  6271. GenJumpUncond(labelAfterElse);
  6272. GenNumLabel(labelAfterIf);
  6273. if (doAnnotations)
  6274. {
  6275. GenStartCommentLine(); printf2("else\n");
  6276. }
  6277. tok = GetToken();
  6278. tok = ParseStatement(tok, BrkCntTarget, casesIdx);
  6279. GenNumLabel(labelAfterElse);
  6280. }
  6281. else
  6282. {
  6283. GenNumLabel(labelAfterIf);
  6284. }
  6285. }
  6286. else if (tok == tokFor)
  6287. {
  6288. word labelBefore = LabelCnt++;
  6289. word labelExpr3 = LabelCnt++;
  6290. word labelBody = LabelCnt++;
  6291. word labelAfter = LabelCnt++;
  6292. word cond = -1;
  6293. static word expr3Stack[STACK_SIZE >> 1][2];
  6294. static word expr3Sp;
  6295. if (doAnnotations)
  6296. {
  6297. GenStartCommentLine(); printf2("for\n");
  6298. }
  6299. tok = GetToken();
  6300. if (tok != '(')
  6301. //error("ParseStatement(): '(' expected after 'for'\n");
  6302. errorUnexpectedToken(tok);
  6303. tok = GetToken();
  6304. {
  6305. if ((tok = ParseExpr(tok, &gotUnary, &synPtr, &constExpr, &exprVal, 0, 0)) != ';')
  6306. //error("ParseStatement(): ';' expected after 'for ( expression'\n");
  6307. errorUnexpectedToken(tok);
  6308. if (gotUnary)
  6309. {
  6310. GenExpr();
  6311. }
  6312. tok = GetToken();
  6313. }
  6314. GenNumLabel(labelBefore);
  6315. if ((tok = ParseExpr(tok, &gotUnary, &synPtr, &constExpr, &exprVal, 0, 0)) != ';')
  6316. //error("ParseStatement(): ';' expected after 'for ( expression ; expression'\n");
  6317. errorUnexpectedToken(tok);
  6318. if (gotUnary)
  6319. {
  6320. // DONE: void control expressions
  6321. //error("ParseStatement(): unexpected 'void' expression in 'for ( ; expression ; )'\n");
  6322. // Bar void and struct/union
  6323. scalarTypeCheck(synPtr);
  6324. if (constExpr)
  6325. {
  6326. // Special cases for for(...; 0; ...) and for(...; 1; ...)
  6327. cond = truncInt(exprVal) != 0;
  6328. }
  6329. else
  6330. {
  6331. switch (stack[sp - 1][0])
  6332. {
  6333. case '<':
  6334. case '>':
  6335. case tokEQ:
  6336. case tokNEQ:
  6337. case tokLEQ:
  6338. case tokGEQ:
  6339. case tokULess:
  6340. case tokUGreater:
  6341. case tokULEQ:
  6342. case tokUGEQ:
  6343. push2(tokIfNot, labelAfter);
  6344. GenExpr();
  6345. break;
  6346. default:
  6347. push(tokReturn); // value produced by generated code is used
  6348. GenExpr();
  6349. GenJumpIfZero(labelAfter);
  6350. break;
  6351. }
  6352. }
  6353. }
  6354. else
  6355. {
  6356. // Special case for for(...; ; ...)
  6357. cond = 1;
  6358. }
  6359. if (!cond)
  6360. // Special case for for(...; 0; ...)
  6361. GenJumpUncond(labelAfter);
  6362. tok = GetToken();
  6363. if ((tok = ParseExpr(tok, &gotUnary, &synPtr, &constExpr, &exprVal, 0, 0)) != ')')
  6364. //error("ParseStatement(): ')' expected after 'for ( expression ; expression ; expression'\n");
  6365. errorUnexpectedToken(tok);
  6366. // Try to reorder expr3 with body to reduce the number of jumps, favor small expr3's
  6367. if (gotUnary && sp <= 16 && (unsigned)sp <= division(sizeof expr3Stack , sizeof expr3Stack[0]) - expr3Sp)
  6368. {
  6369. word cnt = sp;
  6370. // Stash the stack containing expr3
  6371. memcpy(expr3Stack + expr3Sp, stack, cnt * sizeof stack[0]);
  6372. expr3Sp += cnt;
  6373. // Body
  6374. tok = GetToken();
  6375. brkCntTarget[0] = labelAfter; // break target
  6376. brkCntTarget[1] = labelExpr3; // continue target
  6377. tok = ParseStatement(tok, brkCntTarget, casesIdx);
  6378. // Unstash expr3 and generate code for it
  6379. expr3Sp -= cnt;
  6380. memcpy(stack, expr3Stack + expr3Sp, cnt * sizeof stack[0]);
  6381. sp = cnt;
  6382. GenNumLabel(labelExpr3);
  6383. GenExpr();
  6384. // Special case for for(...; 0; ...)
  6385. if (cond)
  6386. GenJumpUncond(labelBefore);
  6387. }
  6388. else
  6389. {
  6390. if (gotUnary)
  6391. {
  6392. GenJumpUncond(labelBody);
  6393. // expr3
  6394. GenNumLabel(labelExpr3);
  6395. GenExpr();
  6396. GenJumpUncond(labelBefore);
  6397. GenNumLabel(labelBody);
  6398. }
  6399. // Body
  6400. tok = GetToken();
  6401. brkCntTarget[0] = labelAfter; // break target
  6402. brkCntTarget[1] = gotUnary ? labelExpr3 : (cond ? labelBefore : labelAfter); // continue target
  6403. tok = ParseStatement(tok, brkCntTarget, casesIdx);
  6404. // Special case for for(...; 0; ...)
  6405. if (brkCntTarget[1] != labelAfter)
  6406. GenJumpUncond(brkCntTarget[1]);
  6407. }
  6408. GenNumLabel(labelAfter);
  6409. }
  6410. else if (tok == tokBreak)
  6411. {
  6412. if (doAnnotations)
  6413. {
  6414. GenStartCommentLine(); printf2("break\n");
  6415. }
  6416. if ((tok = GetToken()) != ';')
  6417. //error("ParseStatement(): ';' expected\n");
  6418. errorUnexpectedToken(tok);
  6419. tok = GetToken();
  6420. if (BrkCntTarget == NULL)
  6421. //error("ParseStatement(): 'break' must be within 'while', 'for' or 'switch' statement\n");
  6422. errorCtrlOutOfScope();
  6423. GenJumpUncond(BrkCntTarget[0]);
  6424. }
  6425. else if (tok == tokCont)
  6426. {
  6427. if (doAnnotations)
  6428. {
  6429. GenStartCommentLine(); printf2("continue\n");
  6430. }
  6431. if ((tok = GetToken()) != ';')
  6432. //error("ParseStatement(): ';' expected\n");
  6433. errorUnexpectedToken(tok);
  6434. tok = GetToken();
  6435. if (BrkCntTarget == NULL || BrkCntTarget[1] == 0)
  6436. //error("ParseStatement(): 'continue' must be within 'while' or 'for' statement\n");
  6437. errorCtrlOutOfScope();
  6438. GenJumpUncond(BrkCntTarget[1]);
  6439. }
  6440. else if (tok == tokSwitch)
  6441. {
  6442. word undoCases = CasesCnt;
  6443. word brkLabel = LabelCnt++;
  6444. word lbl = LabelCnt++;
  6445. word i;
  6446. if (doAnnotations)
  6447. {
  6448. GenStartCommentLine(); printf2("switch\n");
  6449. }
  6450. tok = GetToken();
  6451. if (tok != '(')
  6452. //error("ParseStatement(): '(' expected after 'switch'\n");
  6453. errorUnexpectedToken(tok);
  6454. tok = GetToken();
  6455. if ((tok = ParseExpr(tok, &gotUnary, &synPtr, &constExpr, &exprVal, 0, 0)) != ')')
  6456. //error("ParseStatement(): ')' expected after 'switch ( expression'\n");
  6457. errorUnexpectedToken(tok);
  6458. if (!gotUnary)
  6459. //error("ParseStatement(): expression expected in 'switch ( expression )'\n");
  6460. errorUnexpectedToken(tok);
  6461. // DONE: void control expressions
  6462. //error("ParseStatement(): unexpected 'void' expression in 'switch ( expression )'\n");
  6463. anyIntTypeCheck(synPtr);
  6464. push(tokReturn); // value produced by generated code is used
  6465. GenExpr();
  6466. tok = GetToken();
  6467. // Skip the code for the cases
  6468. GenJumpUncond(lbl);
  6469. brkCntTarget[0] = brkLabel; // break target
  6470. brkCntTarget[1] = 0; // continue target
  6471. if (BrkCntTarget)
  6472. {
  6473. // Preserve the continue target
  6474. brkCntTarget[1] = BrkCntTarget[1]; // continue target
  6475. }
  6476. // Reserve a slot in the case table for the default label
  6477. AddCase(0, 0);
  6478. tok = ParseStatement(tok, brkCntTarget, CasesCnt);
  6479. // If there's no default target, will use the break target as default
  6480. if (!Cases[undoCases][1])
  6481. Cases[undoCases][1] = brkLabel;
  6482. // End of switch reached (not via break), skip conditional jumps
  6483. GenJumpUncond(brkLabel);
  6484. // Generate conditional jumps
  6485. GenNumLabel(lbl);
  6486. for (i = undoCases + 1; i < CasesCnt; i++)
  6487. {
  6488. GenJumpIfEqual(Cases[i][0], Cases[i][1]);
  6489. }
  6490. // If none of the cases matches, take the default case
  6491. if (Cases[undoCases][1] != brkLabel)
  6492. GenJumpUncond(Cases[undoCases][1]);
  6493. GenNumLabel(brkLabel); // break label
  6494. CasesCnt = undoCases;
  6495. }
  6496. else if (tok == tokCase)
  6497. {
  6498. word i;
  6499. if (doAnnotations)
  6500. {
  6501. GenStartCommentLine(); printf2("case\n");
  6502. }
  6503. if (!casesIdx)
  6504. //error("ParseStatement(): 'case' must be within 'switch' statement\n");
  6505. errorCtrlOutOfScope();
  6506. tok = GetToken();
  6507. if ((tok = ParseExpr(tok, &gotUnary, &synPtr, &constExpr, &exprVal, 0, 0)) != ':')
  6508. //error("ParseStatement(): ':' expected after 'case expression'\n");
  6509. errorUnexpectedToken(tok);
  6510. if (!gotUnary)
  6511. errorUnexpectedToken(tok);
  6512. anyIntTypeCheck(synPtr);
  6513. if (!constExpr)
  6514. //error("ParseStatement(): constant integer expression expected in 'case expression :'\n");
  6515. errorNotConst();
  6516. // Check for dups
  6517. exprVal = truncInt(exprVal);
  6518. for (i = casesIdx; i < CasesCnt; i++)
  6519. if (Cases[i][0] == exprVal)
  6520. error("Duplicate case value\n");
  6521. AddCase(exprVal, LabelCnt);
  6522. GenNumLabel(LabelCnt++); // case exprVal:
  6523. tok = GetToken();
  6524. // a statement is needed after "case:"
  6525. statementNeeded = 1;
  6526. }
  6527. else if (tok == tokDefault)
  6528. {
  6529. if (doAnnotations)
  6530. {
  6531. GenStartCommentLine(); printf2("default\n");
  6532. }
  6533. if (!casesIdx)
  6534. //error("ParseStatement(): 'default' must be within 'switch' statement\n");
  6535. errorCtrlOutOfScope();
  6536. if (Cases[casesIdx - 1][1])
  6537. //error("ParseStatement(): only one 'default' allowed in 'switch'\n");
  6538. errorUnexpectedToken(tok);
  6539. tok = GetToken();
  6540. if (tok != ':')
  6541. //error("ParseStatement(): ':' expected after 'default'\n");
  6542. errorUnexpectedToken(tok);
  6543. tok = GetToken();
  6544. GenNumLabel(Cases[casesIdx - 1][1] = LabelCnt++); // default:
  6545. // a statement is needed after "default:"
  6546. statementNeeded = 1;
  6547. }
  6548. else if (tok == tok_Asm)
  6549. {
  6550. tok = GetToken();
  6551. if (tok != '(')
  6552. //error("ParseStatement(): '(' expected after 'asm'\n");
  6553. errorUnexpectedToken(tok);
  6554. tok = GetToken();
  6555. if (tok != tokLitStr)
  6556. //error("ParseStatement(): string literal expression expected in 'asm ( expression )'\n");
  6557. errorUnexpectedToken(tok);
  6558. do
  6559. {
  6560. GetString('"', 0, 'a');
  6561. tok = GetToken();
  6562. } while (tok == tokLitStr); // concatenate adjacent string literals
  6563. printf2("\n");
  6564. if (tok != ')')
  6565. //error("ParseStatement(): ')' expected after 'asm ( expression'\n");
  6566. errorUnexpectedToken(tok);
  6567. tok = GetToken();
  6568. if (tok != ';')
  6569. //error("ParseStatement(): ';' expected after 'asm ( expression )'\n");
  6570. errorUnexpectedToken(tok);
  6571. tok = GetToken();
  6572. }
  6573. else if (tok == tokGoto)
  6574. {
  6575. if ((tok = GetToken()) != tokIdent)
  6576. errorUnexpectedToken(tok);
  6577. GenStartCommentLine();
  6578. if (doAnnotations)
  6579. {
  6580. printf2("goto ");
  6581. printf2(TokenIdentName);
  6582. printf2("\n");
  6583. }
  6584. GenJumpUncond(AddGotoLabel(TokenIdentName, 0));
  6585. if ((tok = GetToken()) != ';')
  6586. errorUnexpectedToken(tok);
  6587. tok = GetToken();
  6588. }
  6589. else
  6590. {
  6591. tok = ParseExpr(tok, &gotUnary, &synPtr, &constExpr, &exprVal, tokGotoLabel, 0);
  6592. if (tok == tokGotoLabel)
  6593. {
  6594. // found a label
  6595. if (doAnnotations)
  6596. {
  6597. GenStartCommentLine();
  6598. printf2(IdentTable + stack[0][1]);
  6599. printf2(":\n");
  6600. }
  6601. GenNumLabel(AddGotoLabel(IdentTable + stack[0][1], 1));
  6602. // a statement is needed after "label:"
  6603. statementNeeded = 1;
  6604. }
  6605. else
  6606. {
  6607. if (tok != ';')
  6608. //error("ParseStatement(): ';' expected\n");
  6609. errorUnexpectedToken(tok);
  6610. if (gotUnary)
  6611. GenExpr();
  6612. }
  6613. tok = GetToken();
  6614. }
  6615. } while (statementNeeded);
  6616. return tok;
  6617. }
  6618. // TBD!!! think of ways of getting rid of casesIdx
  6619. word ParseBlock(word BrkCntTarget[2], word casesIdx)
  6620. {
  6621. word tok = GetToken();
  6622. // Catch redeclarations of function parameters by not
  6623. // beginning a new scope if this block begins a function
  6624. // (the caller of ParseBlock() must've begun a new scope
  6625. // already, before the function parameters).
  6626. if (BrkCntTarget == BrkCntTargetFxn)
  6627. BrkCntTarget = NULL;
  6628. else
  6629. // Otherwise begin a new scope.
  6630. PushSyntax('#');
  6631. for (;;)
  6632. {
  6633. if (tok == 0)
  6634. return tok;
  6635. if (tok == '}' && ParseLevel > 0)
  6636. return tok;
  6637. if (TokenStartsDeclaration(tok, 0))
  6638. {
  6639. tok = ParseDecl(tok, NULL, 0, 1);
  6640. }
  6641. else if (ParseLevel > 0 || tok == tok_Asm)
  6642. {
  6643. tok = ParseStatement(tok, BrkCntTarget, casesIdx);
  6644. }
  6645. else
  6646. //error("ParseBlock(): Unexpected token %s\n", GetTokenName(tok));
  6647. errorUnexpectedToken(tok);
  6648. }
  6649. }
  6650. int main()
  6651. {
  6652. printf("BCC Compiler\n");
  6653. // Run-time initializer for SyntaxStack0[] to reduce
  6654. // executable file size (SyntaxStack0[] will be in .bss)
  6655. static unsigned char SyntaxStackInit[] =
  6656. {
  6657. tokVoid, // SymVoidSynPtr
  6658. tokInt, // SymIntSynPtr
  6659. tokUnsigned, // SymUintSynPtr
  6660. tokVoid, // SymWideCharSynPtr
  6661. tokFloat, // SymFloatSynPtr
  6662. tokIdent, // SymFuncPtr
  6663. '[',
  6664. tokNumUint,
  6665. ']',
  6666. tokChar
  6667. }; // SyntaxStackCnt must be initialized to the number of elements in SyntaxStackInit[]
  6668. memcpy(SyntaxStack0, SyntaxStackInit, sizeof SyntaxStackInit);
  6669. SyntaxStackCnt = 10;
  6670. SyntaxStack1[SymFuncPtr] = DummyIdent = AddIdent("");
  6671. GenInit();
  6672. // TODO: add BDOS path to filenames if not absolute path
  6673. compileOS = 0;
  6674. compileUserBDOS = 1;
  6675. char infilename[64];
  6676. BDOS_GetArgN(1, infilename);
  6677. if (infilename[0] == 0)
  6678. {
  6679. strcat(infilename, BDOS_GetPath());
  6680. if (infilename[strlen(infilename)-1] != '/')
  6681. {
  6682. strcat(infilename, "/");
  6683. }
  6684. strcat(infilename, "CODE.C");
  6685. //strcpy(infilename, "/TEST/TEST.C");
  6686. }
  6687. if (infilename[0] != '/')
  6688. {
  6689. char bothPath[64];
  6690. bothPath[0] = 0;
  6691. strcat(bothPath, BDOS_GetPath());
  6692. if (bothPath[strlen(bothPath)-1] != '/')
  6693. {
  6694. strcat(bothPath, "/");
  6695. }
  6696. strcat(bothPath, infilename);
  6697. strcpy(infilename, bothPath);
  6698. }
  6699. if (FileCnt == 0)
  6700. {
  6701. // If it's none of the known options,
  6702. // assume it's the source code file name
  6703. if (strlen(infilename) > MAX_FILE_NAME_LEN)
  6704. {
  6705. //error("File name too long\n");
  6706. errorFileName();
  6707. }
  6708. strcpy(FileNames[0], infilename);
  6709. Files[0] = fopen(FileNames[0], 0);
  6710. if (fcanopen(Files[0]) == EOF)
  6711. {
  6712. //error("Cannot open file \"%s\"\n", FileNames[0]);
  6713. errorFile(FileNames[0]);
  6714. }
  6715. else
  6716. {
  6717. //printf("Opened input file\n");
  6718. }
  6719. LineNos[0] = LineNo;
  6720. LinePoss[0] = LinePos;
  6721. FileCnt++;
  6722. }
  6723. char outfilename[64];
  6724. BDOS_GetArgN(2, outfilename);
  6725. if (outfilename[0] == 0)
  6726. {
  6727. strcat(outfilename, BDOS_GetPath());
  6728. if (outfilename[strlen(outfilename)-1] != '/')
  6729. {
  6730. strcat(outfilename, "/");
  6731. }
  6732. strcat(outfilename, "OUT.ASM");
  6733. //strcpy(outfilename, "/TEST/A.OUT");
  6734. }
  6735. if (outfilename[0] != '/')
  6736. {
  6737. char bothPath[64];
  6738. bothPath[0] = 0;
  6739. strcat(bothPath, BDOS_GetPath());
  6740. if (bothPath[strlen(bothPath)-1] != '/')
  6741. {
  6742. strcat(bothPath, "/");
  6743. }
  6744. strcat(bothPath, outfilename);
  6745. strcpy(outfilename, bothPath);
  6746. }
  6747. if (FileCnt == 1 && OutFile == NULL)
  6748. {
  6749. // This should be the output file name
  6750. OutFile = fopen(outfilename, 1);
  6751. if (fcanopen(OutFile) == EOF)
  6752. {
  6753. //error("Cannot open output file \"%s\"\n", argv[i]);
  6754. errorFile(outfilename);
  6755. }
  6756. else
  6757. {
  6758. //printf("Opened output file\n");
  6759. }
  6760. }
  6761. if (!FileCnt)
  6762. error("Input file not specified\n");
  6763. if (!OutFile)
  6764. error("Output file not specified\n");
  6765. GenInitFinalize();
  6766. // Define a few macros useful for conditional compilation
  6767. /*
  6768. DefineMacro("__SMALLER_C__", "0x0100");
  6769. DefineMacro("__SMALLER_C_32__", "");
  6770. DefineMacro("__SMALLER_C_SCHAR__", "");
  6771. */
  6772. // populate CharQueue[] with the initial file characters
  6773. ShiftChar();
  6774. puts2(FileHeader);
  6775. // compile
  6776. ParseBlock(NULL, 0);
  6777. GenFin();
  6778. if (doAnnotations)
  6779. {
  6780. DumpSynDecls();
  6781. DumpMacroTable();
  6782. DumpIdentTable();
  6783. }
  6784. /*
  6785. GenStartCommentLine();
  6786. printf2("Next label number: ");
  6787. printd2(LabelCnt);
  6788. printf2("\n");
  6789. */
  6790. //GenStartCommentLine();
  6791. printf("Finished compiling\n");
  6792. if (OutFile)
  6793. fclose(OutFile);
  6794. return 'q';
  6795. }
  6796. void interrupt()
  6797. {
  6798. }