1
0

bcc.c 206 KB

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