1
0

bcc.c 206 KB

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