bc.c 182 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518
  1. /* vi: set sw=4 ts=4: */
  2. /*
  3. * Licensed under GPLv2 or later, see file LICENSE in this source tree.
  4. * Adapted from https://github.com/gavinhoward/bc
  5. * Original code copyright (c) 2018 Gavin D. Howard and contributors.
  6. */
  7. //TODO:
  8. // maybe implement a^b for non-integer b?
  9. #define DEBUG_LEXER 0
  10. #define DEBUG_COMPILE 0
  11. #define DEBUG_EXEC 0
  12. // This can be left enabled for production as well:
  13. #define SANITY_CHECKS 1
  14. //config:config BC
  15. //config: bool "bc (45 kb)"
  16. //config: default y
  17. //config: select FEATURE_DC_BIG
  18. //config: help
  19. //config: bc is a command-line, arbitrary-precision calculator with a
  20. //config: Turing-complete language. See the GNU bc manual
  21. //config: (https://www.gnu.org/software/bc/manual/bc.html) and bc spec
  22. //config: (http://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html).
  23. //config:
  24. //config: This bc has five differences to the GNU bc:
  25. //config: 1) The period (.) is a shortcut for "last", as in the BSD bc.
  26. //config: 2) Arrays are copied before being passed as arguments to
  27. //config: functions. This behavior is required by the bc spec.
  28. //config: 3) Arrays can be passed to the builtin "length" function to get
  29. //config: the number of elements in the array. This prints "1":
  30. //config: a[0] = 0; length(a[])
  31. //config: 4) The precedence of the boolean "not" operator (!) is equal to
  32. //config: that of the unary minus (-) negation operator. This still
  33. //config: allows POSIX-compliant scripts to work while somewhat
  34. //config: preserving expected behavior (versus C) and making parsing
  35. //config: easier.
  36. //config: 5) "read()" accepts expressions, not only numeric literals.
  37. //config:
  38. //config:config DC
  39. //config: bool "dc (36 kb)"
  40. //config: default y
  41. //config: help
  42. //config: dc is a reverse-polish notation command-line calculator which
  43. //config: supports unlimited precision arithmetic. See the FreeBSD man page
  44. //config: (https://www.unix.com/man-page/FreeBSD/1/dc/) and GNU dc manual
  45. //config: (https://www.gnu.org/software/bc/manual/dc-1.05/html_mono/dc.html).
  46. //config:
  47. //config: This dc has a few differences from the two above:
  48. //config: 1) When printing a byte stream (command "P"), this dc follows what
  49. //config: the FreeBSD dc does.
  50. //config: 2) Implements the GNU extensions for divmod ("~") and
  51. //config: modular exponentiation ("|").
  52. //config: 3) Implements all FreeBSD extensions, except for "J" and "M".
  53. //config: 4) Like the FreeBSD dc, this dc supports extended registers.
  54. //config: However, they are implemented differently. When it encounters
  55. //config: whitespace where a register should be, it skips the whitespace.
  56. //config: If the character following is not a lowercase letter, an error
  57. //config: is issued. Otherwise, the register name is parsed by the
  58. //config: following regex: [a-z][a-z0-9_]*
  59. //config: This generally means that register names will be surrounded by
  60. //config: whitespace. Examples:
  61. //config: l idx s temp L index S temp2 < do_thing
  62. //config: Also note that, like the FreeBSD dc, extended registers are not
  63. //config: allowed unless the "-x" option is given.
  64. //config:
  65. //config:if BC || DC # for menuconfig indenting
  66. //config:
  67. //config:config FEATURE_DC_BIG
  68. //config: bool "Use bc code base for dc (larger, more features)"
  69. //config: default y
  70. //config:
  71. //config:config FEATURE_DC_LIBM
  72. //config: bool "Enable power and exp functions (requires libm)"
  73. //config: default y
  74. //config: depends on DC && !BC && !FEATURE_DC_BIG
  75. //config: help
  76. //config: Enable power and exp functions.
  77. //config: NOTE: This will require libm to be present for linking.
  78. //config:
  79. //config:config FEATURE_BC_INTERACTIVE
  80. //config: bool "Interactive mode (+4kb)"
  81. //config: default y
  82. //config: depends on BC || (DC && FEATURE_DC_BIG)
  83. //config: help
  84. //config: Enable interactive mode: when started on a tty,
  85. //config: ^C interrupts execution and returns to command line,
  86. //config: errors also return to command line instead of exiting,
  87. //config: line editing with history is available.
  88. //config:
  89. //config: With this option off, input can still be taken from tty,
  90. //config: but all errors are fatal, ^C is fatal,
  91. //config: tty is treated exactly the same as any other
  92. //config: standard input (IOW: no line editing).
  93. //config:
  94. //config:config FEATURE_BC_LONG_OPTIONS
  95. //config: bool "Enable bc/dc long options"
  96. //config: default y
  97. //config: depends on BC || (DC && FEATURE_DC_BIG)
  98. //config:
  99. //config:endif
  100. //applet:IF_BC(APPLET(bc, BB_DIR_USR_BIN, BB_SUID_DROP))
  101. //applet:IF_DC(APPLET(dc, BB_DIR_USR_BIN, BB_SUID_DROP))
  102. //kbuild:lib-$(CONFIG_BC) += bc.o
  103. //kbuild:lib-$(CONFIG_DC) += bc.o
  104. //See www.gnu.org/software/bc/manual/bc.html
  105. //usage:#define bc_trivial_usage
  106. //usage: "[-sqlw] FILE..."
  107. //usage:
  108. //usage:#define bc_full_usage "\n"
  109. //usage: "\nArbitrary precision calculator"
  110. //usage: "\n"
  111. ///////: "\n -i Interactive" - has no effect for now
  112. //usage: "\n -q Quiet"
  113. //usage: "\n -l Load standard math library"
  114. //usage: "\n -s Be POSIX compatible"
  115. //usage: "\n -w Warn if extensions are used"
  116. ///////: "\n -v Version"
  117. //usage: "\n"
  118. //usage: "\n$BC_LINE_LENGTH changes output width"
  119. //usage:
  120. //usage:#define bc_example_usage
  121. //usage: "3 + 4.129\n"
  122. //usage: "1903 - 2893\n"
  123. //usage: "-129 * 213.28935\n"
  124. //usage: "12 / -1932\n"
  125. //usage: "12 % 12\n"
  126. //usage: "34 ^ 189\n"
  127. //usage: "scale = 13\n"
  128. //usage: "ibase = 2\n"
  129. //usage: "obase = A\n"
  130. //usage:
  131. //usage:#define dc_trivial_usage
  132. //usage: IF_FEATURE_DC_BIG("[-x] ")"[-eSCRIPT]... [-fFILE]... [FILE]..."
  133. //usage:
  134. //usage:#define dc_full_usage "\n"
  135. //usage: "\nTiny RPN calculator. Operations:"
  136. //usage: "\n+, -, *, /, %, ~, ^," IF_FEATURE_DC_BIG(" |,")
  137. //usage: "\np - print top of the stack without popping"
  138. //usage: "\nf - print entire stack"
  139. //usage: "\nk - pop the value and set the precision"
  140. //usage: "\ni - pop the value and set input radix"
  141. //usage: "\no - pop the value and set output radix"
  142. //usage: "\nExamples: dc -e'2 2 + p' -> 4, dc -e'8 8 * 2 2 + / p' -> 16"
  143. //usage:
  144. //usage:#define dc_example_usage
  145. //usage: "$ dc -e'2 2 + p'\n"
  146. //usage: "4\n"
  147. //usage: "$ dc -e'8 8 \\* 2 2 + / p'\n"
  148. //usage: "16\n"
  149. //usage: "$ dc -e'0 1 & p'\n"
  150. //usage: "0\n"
  151. //usage: "$ dc -e'0 1 | p'\n"
  152. //usage: "1\n"
  153. //usage: "$ echo '72 9 / 8 * p' | dc\n"
  154. //usage: "64\n"
  155. #include "libbb.h"
  156. #include "common_bufsiz.h"
  157. #if !ENABLE_BC && !ENABLE_FEATURE_DC_BIG
  158. # include "dc.c"
  159. #else
  160. #if DEBUG_LEXER
  161. static uint8_t lex_indent;
  162. #define dbg_lex(...) \
  163. do { \
  164. fprintf(stderr, "%*s", lex_indent, ""); \
  165. bb_error_msg(__VA_ARGS__); \
  166. } while (0)
  167. #define dbg_lex_enter(...) \
  168. do { \
  169. dbg_lex(__VA_ARGS__); \
  170. lex_indent++; \
  171. } while (0)
  172. #define dbg_lex_done(...) \
  173. do { \
  174. lex_indent--; \
  175. dbg_lex(__VA_ARGS__); \
  176. } while (0)
  177. #else
  178. # define dbg_lex(...) ((void)0)
  179. # define dbg_lex_enter(...) ((void)0)
  180. # define dbg_lex_done(...) ((void)0)
  181. #endif
  182. #if DEBUG_COMPILE
  183. # define dbg_compile(...) bb_error_msg(__VA_ARGS__)
  184. #else
  185. # define dbg_compile(...) ((void)0)
  186. #endif
  187. #if DEBUG_EXEC
  188. # define dbg_exec(...) bb_error_msg(__VA_ARGS__)
  189. #else
  190. # define dbg_exec(...) ((void)0)
  191. #endif
  192. typedef enum BcStatus {
  193. BC_STATUS_SUCCESS = 0,
  194. BC_STATUS_FAILURE = 1,
  195. } BcStatus;
  196. #define BC_VEC_INVALID_IDX ((size_t) -1)
  197. #define BC_VEC_START_CAP (1 << 5)
  198. typedef void (*BcVecFree)(void *) FAST_FUNC;
  199. typedef struct BcVec {
  200. char *v;
  201. size_t len;
  202. size_t cap;
  203. size_t size;
  204. BcVecFree dtor;
  205. } BcVec;
  206. typedef signed char BcDig;
  207. typedef struct BcNum {
  208. BcDig *restrict num;
  209. size_t rdx;
  210. size_t len;
  211. size_t cap;
  212. bool neg;
  213. } BcNum;
  214. #define BC_NUM_MAX_IBASE 36
  215. // larger value might speed up BIGNUM calculations a bit:
  216. #define BC_NUM_DEF_SIZE 16
  217. #define BC_NUM_PRINT_WIDTH 69
  218. #define BC_NUM_KARATSUBA_LEN 32
  219. typedef enum BcInst {
  220. #if ENABLE_BC
  221. BC_INST_INC_PRE,
  222. BC_INST_DEC_PRE,
  223. BC_INST_INC_POST,
  224. BC_INST_DEC_POST,
  225. #endif
  226. XC_INST_NEG, // order
  227. XC_INST_REL_EQ, // should
  228. XC_INST_REL_LE, // match
  229. XC_INST_REL_GE, // LEX
  230. XC_INST_REL_NE, // constants
  231. XC_INST_REL_LT, // for
  232. XC_INST_REL_GT, // these
  233. XC_INST_POWER, // operations
  234. XC_INST_MULTIPLY, // |
  235. XC_INST_DIVIDE, // |
  236. XC_INST_MODULUS, // |
  237. XC_INST_PLUS, // |
  238. XC_INST_MINUS, // |
  239. XC_INST_BOOL_NOT, // |
  240. XC_INST_BOOL_OR, // |
  241. XC_INST_BOOL_AND, // |
  242. #if ENABLE_BC
  243. BC_INST_ASSIGN_POWER, // |
  244. BC_INST_ASSIGN_MULTIPLY,// |
  245. BC_INST_ASSIGN_DIVIDE, // |
  246. BC_INST_ASSIGN_MODULUS, // |
  247. BC_INST_ASSIGN_PLUS, // |
  248. BC_INST_ASSIGN_MINUS, // |
  249. #endif
  250. XC_INST_ASSIGN, // V
  251. XC_INST_NUM,
  252. XC_INST_VAR,
  253. XC_INST_ARRAY_ELEM,
  254. XC_INST_ARRAY,
  255. XC_INST_SCALE_FUNC,
  256. XC_INST_IBASE, // order of these constans should match other enums
  257. XC_INST_OBASE, // order of these constans should match other enums
  258. XC_INST_SCALE, // order of these constans should match other enums
  259. IF_BC(BC_INST_LAST,) // order of these constans should match other enums
  260. XC_INST_LENGTH,
  261. XC_INST_READ,
  262. XC_INST_SQRT,
  263. XC_INST_PRINT,
  264. XC_INST_PRINT_POP,
  265. XC_INST_STR,
  266. XC_INST_PRINT_STR,
  267. #if ENABLE_BC
  268. BC_INST_HALT,
  269. BC_INST_JUMP,
  270. BC_INST_JUMP_ZERO,
  271. BC_INST_CALL,
  272. BC_INST_RET0,
  273. #endif
  274. XC_INST_RET,
  275. XC_INST_POP,
  276. #if ENABLE_DC
  277. DC_INST_POP_EXEC,
  278. DC_INST_MODEXP,
  279. DC_INST_DIVMOD,
  280. DC_INST_EXECUTE,
  281. DC_INST_EXEC_COND,
  282. DC_INST_ASCIIFY,
  283. DC_INST_PRINT_STREAM,
  284. DC_INST_PRINT_STACK,
  285. DC_INST_CLEAR_STACK,
  286. DC_INST_STACK_LEN,
  287. DC_INST_DUPLICATE,
  288. DC_INST_SWAP,
  289. DC_INST_LOAD,
  290. DC_INST_PUSH_VAR,
  291. DC_INST_PUSH_TO_VAR,
  292. DC_INST_QUIT,
  293. DC_INST_NQUIT,
  294. DC_INST_INVALID = -1,
  295. #endif
  296. } BcInst;
  297. typedef struct BcId {
  298. char *name;
  299. size_t idx;
  300. } BcId;
  301. typedef struct BcFunc {
  302. BcVec code;
  303. IF_BC(BcVec labels;)
  304. IF_BC(BcVec autos;)
  305. IF_BC(BcVec strs;)
  306. IF_BC(BcVec consts;)
  307. IF_BC(size_t nparams;)
  308. IF_BC(bool voidfunc;)
  309. } BcFunc;
  310. typedef enum BcResultType {
  311. XC_RESULT_TEMP,
  312. IF_BC(BC_RESULT_VOID,) // same as TEMP, but INST_PRINT will ignore it
  313. XC_RESULT_VAR,
  314. XC_RESULT_ARRAY_ELEM,
  315. XC_RESULT_ARRAY,
  316. XC_RESULT_STR,
  317. //code uses "inst - XC_INST_IBASE + XC_RESULT_IBASE" construct,
  318. XC_RESULT_IBASE, // relative order should match for: XC_INST_IBASE
  319. XC_RESULT_OBASE, // relative order should match for: XC_INST_OBASE
  320. XC_RESULT_SCALE, // relative order should match for: XC_INST_SCALE
  321. IF_BC(BC_RESULT_LAST,) // relative order should match for: BC_INST_LAST
  322. XC_RESULT_CONSTANT,
  323. IF_BC(BC_RESULT_ONE,)
  324. } BcResultType;
  325. typedef union BcResultData {
  326. BcNum n;
  327. BcVec v;
  328. BcId id;
  329. } BcResultData;
  330. typedef struct BcResult {
  331. BcResultType t;
  332. BcResultData d;
  333. } BcResult;
  334. typedef struct BcInstPtr {
  335. size_t func;
  336. size_t inst_idx;
  337. } BcInstPtr;
  338. typedef enum BcType {
  339. BC_TYPE_VAR,
  340. BC_TYPE_ARRAY,
  341. BC_TYPE_REF,
  342. } BcType;
  343. typedef enum BcLexType {
  344. XC_LEX_EOF,
  345. XC_LEX_INVALID,
  346. XC_LEX_NLINE,
  347. XC_LEX_WHITESPACE,
  348. XC_LEX_STR,
  349. XC_LEX_NAME,
  350. XC_LEX_NUMBER,
  351. XC_LEX_1st_op,
  352. XC_LEX_NEG = XC_LEX_1st_op, // order
  353. XC_LEX_OP_REL_EQ, // should
  354. XC_LEX_OP_REL_LE, // match
  355. XC_LEX_OP_REL_GE, // INST
  356. XC_LEX_OP_REL_NE, // constants
  357. XC_LEX_OP_REL_LT, // for
  358. XC_LEX_OP_REL_GT, // these
  359. XC_LEX_OP_POWER, // operations
  360. XC_LEX_OP_MULTIPLY, // |
  361. XC_LEX_OP_DIVIDE, // |
  362. XC_LEX_OP_MODULUS, // |
  363. XC_LEX_OP_PLUS, // |
  364. XC_LEX_OP_MINUS, // |
  365. XC_LEX_OP_last = XC_LEX_OP_MINUS,
  366. #if ENABLE_BC
  367. BC_LEX_OP_BOOL_NOT, // |
  368. BC_LEX_OP_BOOL_OR, // |
  369. BC_LEX_OP_BOOL_AND, // |
  370. BC_LEX_OP_ASSIGN_POWER, // |
  371. BC_LEX_OP_ASSIGN_MULTIPLY, // |
  372. BC_LEX_OP_ASSIGN_DIVIDE, // |
  373. BC_LEX_OP_ASSIGN_MODULUS, // |
  374. BC_LEX_OP_ASSIGN_PLUS, // |
  375. BC_LEX_OP_ASSIGN_MINUS, // |
  376. BC_LEX_OP_ASSIGN, // V
  377. BC_LEX_OP_INC,
  378. BC_LEX_OP_DEC,
  379. BC_LEX_LPAREN, // () are 0x28 and 0x29
  380. BC_LEX_RPAREN, // must be LPAREN+1: code uses (c - '(' + BC_LEX_LPAREN)
  381. BC_LEX_LBRACKET, // [] are 0x5B and 0x5D
  382. BC_LEX_COMMA,
  383. BC_LEX_RBRACKET, // must be LBRACKET+2: code uses (c - '[' + BC_LEX_LBRACKET)
  384. BC_LEX_LBRACE, // {} are 0x7B and 0x7D
  385. BC_LEX_SCOLON,
  386. BC_LEX_RBRACE, // must be LBRACE+2: code uses (c - '{' + BC_LEX_LBRACE)
  387. BC_LEX_KEY_1st_keyword,
  388. BC_LEX_KEY_AUTO = BC_LEX_KEY_1st_keyword,
  389. BC_LEX_KEY_BREAK,
  390. BC_LEX_KEY_CONTINUE,
  391. BC_LEX_KEY_DEFINE,
  392. BC_LEX_KEY_ELSE,
  393. BC_LEX_KEY_FOR,
  394. BC_LEX_KEY_HALT,
  395. // code uses "type - BC_LEX_KEY_IBASE + XC_INST_IBASE" construct,
  396. BC_LEX_KEY_IBASE, // relative order should match for: XC_INST_IBASE
  397. BC_LEX_KEY_OBASE, // relative order should match for: XC_INST_OBASE
  398. BC_LEX_KEY_IF,
  399. BC_LEX_KEY_LAST, // relative order should match for: BC_INST_LAST
  400. BC_LEX_KEY_LENGTH,
  401. BC_LEX_KEY_LIMITS,
  402. BC_LEX_KEY_PRINT,
  403. BC_LEX_KEY_QUIT,
  404. BC_LEX_KEY_READ,
  405. BC_LEX_KEY_RETURN,
  406. BC_LEX_KEY_SCALE,
  407. BC_LEX_KEY_SQRT,
  408. BC_LEX_KEY_WHILE,
  409. #endif // ENABLE_BC
  410. #if ENABLE_DC
  411. DC_LEX_OP_BOOL_NOT = XC_LEX_OP_last + 1,
  412. DC_LEX_OP_ASSIGN,
  413. DC_LEX_LPAREN,
  414. DC_LEX_SCOLON,
  415. DC_LEX_READ,
  416. DC_LEX_IBASE,
  417. DC_LEX_SCALE,
  418. DC_LEX_OBASE,
  419. DC_LEX_LENGTH,
  420. DC_LEX_PRINT,
  421. DC_LEX_QUIT,
  422. DC_LEX_SQRT,
  423. DC_LEX_LBRACE,
  424. DC_LEX_EQ_NO_REG,
  425. DC_LEX_OP_MODEXP,
  426. DC_LEX_OP_DIVMOD,
  427. DC_LEX_COLON,
  428. DC_LEX_ELSE,
  429. DC_LEX_EXECUTE,
  430. DC_LEX_PRINT_STACK,
  431. DC_LEX_CLEAR_STACK,
  432. DC_LEX_STACK_LEVEL,
  433. DC_LEX_DUPLICATE,
  434. DC_LEX_SWAP,
  435. DC_LEX_POP,
  436. DC_LEX_ASCIIFY,
  437. DC_LEX_PRINT_STREAM,
  438. // code uses "t - DC_LEX_STORE_IBASE + XC_INST_IBASE" construct,
  439. DC_LEX_STORE_IBASE, // relative order should match for: XC_INST_IBASE
  440. DC_LEX_STORE_OBASE, // relative order should match for: XC_INST_OBASE
  441. DC_LEX_STORE_SCALE, // relative order should match for: XC_INST_SCALE
  442. DC_LEX_LOAD,
  443. DC_LEX_LOAD_POP,
  444. DC_LEX_STORE_PUSH,
  445. DC_LEX_PRINT_POP,
  446. DC_LEX_NQUIT,
  447. DC_LEX_SCALE_FACTOR,
  448. #endif
  449. } BcLexType;
  450. // must match order of BC_LEX_KEY_foo etc above
  451. #if ENABLE_BC
  452. struct BcLexKeyword {
  453. char name8[8];
  454. };
  455. #define LEX_KW_ENTRY(a, b) \
  456. { .name8 = a /*, .posix = b */ }
  457. static const struct BcLexKeyword bc_lex_kws[20] = {
  458. LEX_KW_ENTRY("auto" , 1), // 0
  459. LEX_KW_ENTRY("break" , 1), // 1
  460. LEX_KW_ENTRY("continue", 0), // 2 note: this one has no terminating NUL
  461. LEX_KW_ENTRY("define" , 1), // 3
  462. LEX_KW_ENTRY("else" , 0), // 4
  463. LEX_KW_ENTRY("for" , 1), // 5
  464. LEX_KW_ENTRY("halt" , 0), // 6
  465. LEX_KW_ENTRY("ibase" , 1), // 7
  466. LEX_KW_ENTRY("obase" , 1), // 8
  467. LEX_KW_ENTRY("if" , 1), // 9
  468. LEX_KW_ENTRY("last" , 0), // 10
  469. LEX_KW_ENTRY("length" , 1), // 11
  470. LEX_KW_ENTRY("limits" , 0), // 12
  471. LEX_KW_ENTRY("print" , 0), // 13
  472. LEX_KW_ENTRY("quit" , 1), // 14
  473. LEX_KW_ENTRY("read" , 0), // 15
  474. LEX_KW_ENTRY("return" , 1), // 16
  475. LEX_KW_ENTRY("scale" , 1), // 17
  476. LEX_KW_ENTRY("sqrt" , 1), // 18
  477. LEX_KW_ENTRY("while" , 1), // 19
  478. };
  479. #undef LEX_KW_ENTRY
  480. #define STRING_else (bc_lex_kws[4].name8)
  481. #define STRING_for (bc_lex_kws[5].name8)
  482. #define STRING_if (bc_lex_kws[9].name8)
  483. #define STRING_while (bc_lex_kws[19].name8)
  484. enum {
  485. POSIX_KWORD_MASK = 0
  486. | (1 << 0) // 0
  487. | (1 << 1) // 1
  488. | (0 << 2) // 2
  489. | (1 << 3) // 3
  490. | (0 << 4) // 4
  491. | (1 << 5) // 5
  492. | (0 << 6) // 6
  493. | (1 << 7) // 7
  494. | (1 << 8) // 8
  495. | (1 << 9) // 9
  496. | (0 << 10) // 10
  497. | (1 << 11) // 11
  498. | (0 << 12) // 12
  499. | (0 << 13) // 13
  500. | (1 << 14) // 14
  501. | (0 << 15) // 15
  502. | (1 << 16) // 16
  503. | (1 << 17) // 17
  504. | (1 << 18) // 18
  505. | (1 << 19) // 19
  506. };
  507. #define keyword_is_POSIX(i) ((1 << (i)) & POSIX_KWORD_MASK)
  508. // This is a bit array that corresponds to token types. An entry is
  509. // true if the token is valid in an expression, false otherwise.
  510. // Used to figure out when expr parsing should stop *without error message*
  511. // - 0 element indicates this condition. 1 means "this token is to be eaten
  512. // as part of the expression", it can then still be determined to be invalid
  513. // by later processing.
  514. enum {
  515. #define EXBITS(a,b,c,d,e,f,g,h) \
  516. ((uint64_t)((a << 0)+(b << 1)+(c << 2)+(d << 3)+(e << 4)+(f << 5)+(g << 6)+(h << 7)))
  517. BC_PARSE_EXPRS_BITS = 0 // corresponding BC_LEX_xyz:
  518. + (EXBITS(0,0,0,0,0,1,1,1) << (0*8)) // 0: EOF INVAL NL WS STR NAME NUM -
  519. + (EXBITS(1,1,1,1,1,1,1,1) << (1*8)) // 8: == <= >= != < > ^ *
  520. + (EXBITS(1,1,1,1,1,1,1,1) << (2*8)) // 16: / % + - ! || && ^=
  521. + (EXBITS(1,1,1,1,1,1,1,1) << (3*8)) // 24: *= /= %= += -= = ++ --
  522. + (EXBITS(1,1,0,0,0,0,0,0) << (4*8)) // 32: ( ) [ , ] { ; }
  523. + (EXBITS(0,0,0,0,0,0,0,1) << (5*8)) // 40: auto break cont define else for halt ibase
  524. + (EXBITS(1,0,1,1,0,0,0,1) << (6*8)) // 48: obase if last length limits print quit read
  525. + (EXBITS(0,1,1,0,0,0,0,0) << (7*8)) // 56: return scale sqrt while
  526. #undef EXBITS
  527. };
  528. static ALWAYS_INLINE long lex_allowed_in_bc_expr(unsigned i)
  529. {
  530. #if ULONG_MAX > 0xffffffff
  531. // 64-bit version (will not work correctly for 32-bit longs!)
  532. return BC_PARSE_EXPRS_BITS & (1UL << i);
  533. #else
  534. // 32-bit version
  535. unsigned long m = (uint32_t)BC_PARSE_EXPRS_BITS;
  536. if (i >= 32) {
  537. m = (uint32_t)(BC_PARSE_EXPRS_BITS >> 32);
  538. i &= 31;
  539. }
  540. return m & (1UL << i);
  541. #endif
  542. }
  543. // This is an array of data for operators that correspond to
  544. // [XC_LEX_1st_op...] token types.
  545. static const uint8_t bc_ops_prec_and_assoc[] ALIGN1 = {
  546. #define OP(p,l) ((int)(l) * 0x10 + (p))
  547. OP(1, false), // neg
  548. OP(6, true ), OP( 6, true ), OP( 6, true ), OP( 6, true ), OP( 6, true ), OP( 6, true ), // == <= >= != < >
  549. OP(2, false), // pow
  550. OP(3, true ), OP( 3, true ), OP( 3, true ), // mul div mod
  551. OP(4, true ), OP( 4, true ), // + -
  552. OP(1, false), // not
  553. OP(7, true ), OP( 7, true ), // or and
  554. OP(5, false), OP( 5, false ), OP( 5, false ), OP( 5, false ), OP( 5, false ), // ^= *= /= %= +=
  555. OP(5, false), OP( 5, false ), // -= =
  556. OP(0, false), OP( 0, false ), // inc dec
  557. #undef OP
  558. };
  559. #define bc_operation_PREC(i) (bc_ops_prec_and_assoc[i] & 0x0f)
  560. #define bc_operation_LEFT(i) (bc_ops_prec_and_assoc[i] & 0x10)
  561. #endif // ENABLE_BC
  562. #if ENABLE_DC
  563. static const //BcLexType - should be this type
  564. uint8_t
  565. dc_char_to_LEX[] ALIGN1 = {
  566. // %&'(
  567. XC_LEX_OP_MODULUS, XC_LEX_INVALID, XC_LEX_INVALID, DC_LEX_LPAREN,
  568. // )*+,
  569. XC_LEX_INVALID, XC_LEX_OP_MULTIPLY, XC_LEX_OP_PLUS, XC_LEX_INVALID,
  570. // -./
  571. XC_LEX_OP_MINUS, XC_LEX_INVALID, XC_LEX_OP_DIVIDE,
  572. // 0123456789
  573. XC_LEX_INVALID, XC_LEX_INVALID, XC_LEX_INVALID, XC_LEX_INVALID,
  574. XC_LEX_INVALID, XC_LEX_INVALID, XC_LEX_INVALID, XC_LEX_INVALID,
  575. XC_LEX_INVALID, XC_LEX_INVALID,
  576. // :;<=>?@
  577. DC_LEX_COLON, DC_LEX_SCOLON, XC_LEX_OP_REL_GT, XC_LEX_OP_REL_EQ,
  578. XC_LEX_OP_REL_LT, DC_LEX_READ, XC_LEX_INVALID,
  579. // ABCDEFGH
  580. XC_LEX_INVALID, XC_LEX_INVALID, XC_LEX_INVALID, XC_LEX_INVALID,
  581. XC_LEX_INVALID, XC_LEX_INVALID, DC_LEX_EQ_NO_REG, XC_LEX_INVALID,
  582. // IJKLMNOP
  583. DC_LEX_IBASE, XC_LEX_INVALID, DC_LEX_SCALE, DC_LEX_LOAD_POP,
  584. XC_LEX_INVALID, DC_LEX_OP_BOOL_NOT, DC_LEX_OBASE, DC_LEX_PRINT_STREAM,
  585. // QRSTUVWX
  586. DC_LEX_NQUIT, DC_LEX_POP, DC_LEX_STORE_PUSH, XC_LEX_INVALID,
  587. XC_LEX_INVALID, XC_LEX_INVALID, XC_LEX_INVALID, DC_LEX_SCALE_FACTOR,
  588. // YZ
  589. XC_LEX_INVALID, DC_LEX_LENGTH,
  590. // [\]
  591. XC_LEX_INVALID, XC_LEX_INVALID, XC_LEX_INVALID,
  592. // ^_`
  593. XC_LEX_OP_POWER, XC_LEX_NEG, XC_LEX_INVALID,
  594. // abcdefgh
  595. DC_LEX_ASCIIFY, XC_LEX_INVALID, DC_LEX_CLEAR_STACK, DC_LEX_DUPLICATE,
  596. DC_LEX_ELSE, DC_LEX_PRINT_STACK, XC_LEX_INVALID, XC_LEX_INVALID,
  597. // ijklmnop
  598. DC_LEX_STORE_IBASE, XC_LEX_INVALID, DC_LEX_STORE_SCALE, DC_LEX_LOAD,
  599. XC_LEX_INVALID, DC_LEX_PRINT_POP, DC_LEX_STORE_OBASE, DC_LEX_PRINT,
  600. // qrstuvwx
  601. DC_LEX_QUIT, DC_LEX_SWAP, DC_LEX_OP_ASSIGN, XC_LEX_INVALID,
  602. XC_LEX_INVALID, DC_LEX_SQRT, XC_LEX_INVALID, DC_LEX_EXECUTE,
  603. // yz
  604. XC_LEX_INVALID, DC_LEX_STACK_LEVEL,
  605. // {|}~
  606. DC_LEX_LBRACE, DC_LEX_OP_MODEXP, XC_LEX_INVALID, DC_LEX_OP_DIVMOD,
  607. };
  608. static const //BcInst - should be this type. Using signed narrow type since DC_INST_INVALID is -1
  609. int8_t
  610. dc_LEX_to_INST[] ALIGN1 = { //starts at XC_LEX_OP_POWER // corresponding XC/DC_LEX_xyz:
  611. XC_INST_POWER, XC_INST_MULTIPLY, // XC_LEX_OP_POWER XC_LEX_OP_MULTIPLY
  612. XC_INST_DIVIDE, XC_INST_MODULUS, // XC_LEX_OP_DIVIDE XC_LEX_OP_MODULUS
  613. XC_INST_PLUS, XC_INST_MINUS, // XC_LEX_OP_PLUS XC_LEX_OP_MINUS
  614. XC_INST_BOOL_NOT, // DC_LEX_OP_BOOL_NOT
  615. DC_INST_INVALID, // DC_LEX_OP_ASSIGN
  616. XC_INST_REL_GT, // DC_LEX_LPAREN
  617. DC_INST_INVALID, // DC_LEX_SCOLON
  618. DC_INST_INVALID, // DC_LEX_READ
  619. XC_INST_IBASE, // DC_LEX_IBASE
  620. XC_INST_SCALE, // DC_LEX_SCALE
  621. XC_INST_OBASE, // DC_LEX_OBASE
  622. XC_INST_LENGTH, // DC_LEX_LENGTH
  623. XC_INST_PRINT, // DC_LEX_PRINT
  624. DC_INST_QUIT, // DC_LEX_QUIT
  625. XC_INST_SQRT, // DC_LEX_SQRT
  626. XC_INST_REL_GE, // DC_LEX_LBRACE
  627. XC_INST_REL_EQ, // DC_LEX_EQ_NO_REG
  628. DC_INST_MODEXP, DC_INST_DIVMOD, // DC_LEX_OP_MODEXP DC_LEX_OP_DIVMOD
  629. DC_INST_INVALID, DC_INST_INVALID, // DC_LEX_COLON DC_LEX_ELSE
  630. DC_INST_EXECUTE, // DC_LEX_EXECUTE
  631. DC_INST_PRINT_STACK, DC_INST_CLEAR_STACK, // DC_LEX_PRINT_STACK DC_LEX_CLEAR_STACK
  632. DC_INST_STACK_LEN, DC_INST_DUPLICATE, // DC_LEX_STACK_LEVEL DC_LEX_DUPLICATE
  633. DC_INST_SWAP, XC_INST_POP, // DC_LEX_SWAP DC_LEX_POP
  634. DC_INST_ASCIIFY, DC_INST_PRINT_STREAM, // DC_LEX_ASCIIFY DC_LEX_PRINT_STREAM
  635. DC_INST_INVALID, DC_INST_INVALID, // DC_LEX_STORE_IBASE DC_LEX_STORE_OBASE
  636. DC_INST_INVALID, DC_INST_INVALID, // DC_LEX_STORE_SCALE DC_LEX_LOAD
  637. DC_INST_INVALID, DC_INST_INVALID, // DC_LEX_LOAD_POP DC_LEX_STORE_PUSH
  638. XC_INST_PRINT, DC_INST_NQUIT, // DC_LEX_PRINT_POP DC_LEX_NQUIT
  639. XC_INST_SCALE_FUNC, // DC_LEX_SCALE_FACTOR
  640. // DC_INST_INVALID in this table either means that corresponding LEX
  641. // is not possible for dc, or that it does not compile one-to-one
  642. // to a single INST.
  643. };
  644. #endif // ENABLE_DC
  645. typedef struct BcParse {
  646. smallint lex; // was BcLexType // first member is most used
  647. smallint lex_last; // was BcLexType
  648. size_t lex_line;
  649. const char *lex_inbuf;
  650. const char *lex_next_at; // last lex_next() was called at this string
  651. const char *lex_filename;
  652. FILE *lex_input_fp;
  653. BcVec lex_strnumbuf;
  654. BcFunc *func;
  655. size_t fidx;
  656. IF_BC(size_t in_funcdef;)
  657. IF_BC(BcVec exits;)
  658. IF_BC(BcVec conds;)
  659. IF_BC(BcVec ops;)
  660. } BcParse;
  661. typedef struct BcProgram {
  662. size_t len;
  663. size_t nchars;
  664. size_t scale;
  665. size_t ib_t;
  666. size_t ob_t;
  667. BcVec results;
  668. BcVec exestack;
  669. BcVec fns;
  670. IF_BC(BcVec fn_map;)
  671. BcVec vars;
  672. BcVec var_map;
  673. BcVec arrs;
  674. BcVec arr_map;
  675. IF_DC(BcVec strs;)
  676. IF_DC(BcVec consts;)
  677. BcNum zero;
  678. IF_BC(BcNum one;)
  679. IF_BC(BcNum last;)
  680. } BcProgram;
  681. struct globals {
  682. BcParse prs; // first member is most used
  683. // For error messages. Can be set to current parsed line,
  684. // or [TODO] to current executing line (can be before last parsed one)
  685. size_t err_line;
  686. BcVec input_buffer;
  687. IF_FEATURE_BC_INTERACTIVE(smallint ttyin;)
  688. IF_FEATURE_CLEAN_UP(smallint exiting;)
  689. BcProgram prog;
  690. BcVec files;
  691. char *env_args;
  692. #if ENABLE_FEATURE_EDITING
  693. line_input_t *line_input_state;
  694. #endif
  695. } FIX_ALIASING;
  696. #define G (*ptr_to_globals)
  697. #define INIT_G() do { \
  698. SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
  699. } while (0)
  700. #define FREE_G() do { \
  701. FREE_PTR_TO_GLOBALS(); \
  702. } while (0)
  703. #define G_posix (ENABLE_BC && (option_mask32 & BC_FLAG_S))
  704. #define G_warn (ENABLE_BC && (option_mask32 & BC_FLAG_W))
  705. #define G_exreg (ENABLE_DC && (option_mask32 & DC_FLAG_X))
  706. #if ENABLE_FEATURE_BC_INTERACTIVE
  707. # define G_interrupt bb_got_signal
  708. # define G_ttyin G.ttyin
  709. #else
  710. # define G_interrupt 0
  711. # define G_ttyin 0
  712. #endif
  713. #if ENABLE_FEATURE_CLEAN_UP
  714. # define G_exiting G.exiting
  715. #else
  716. # define G_exiting 0
  717. #endif
  718. #define IS_BC (ENABLE_BC && (!ENABLE_DC || applet_name[0] == 'b'))
  719. #define IS_DC (ENABLE_DC && (!ENABLE_BC || applet_name[0] != 'b'))
  720. #if ENABLE_BC
  721. # define BC_PARSE_REL (1 << 0)
  722. # define BC_PARSE_PRINT (1 << 1)
  723. # define BC_PARSE_ARRAY (1 << 2)
  724. # define BC_PARSE_NOCALL (1 << 3)
  725. #endif
  726. #define BC_PROG_MAIN 0
  727. #define BC_PROG_READ 1
  728. #if ENABLE_DC
  729. #define BC_PROG_REQ_FUNCS 2
  730. #endif
  731. #define BC_FLAG_W (1 << 0)
  732. #define BC_FLAG_V (1 << 1)
  733. #define BC_FLAG_S (1 << 2)
  734. #define BC_FLAG_Q (1 << 3)
  735. #define BC_FLAG_L (1 << 4)
  736. #define BC_FLAG_I ((1 << 5) * ENABLE_DC)
  737. #define DC_FLAG_X ((1 << 6) * ENABLE_DC)
  738. #define BC_MAX_OBASE ((unsigned) 999)
  739. #define BC_MAX_DIM ((unsigned) INT_MAX)
  740. #define BC_MAX_SCALE ((unsigned) UINT_MAX)
  741. #define BC_MAX_STRING ((unsigned) UINT_MAX - 1)
  742. #define BC_MAX_NUM BC_MAX_STRING
  743. // Unused apart from "limits" message. Just show a "biggish number" there.
  744. //#define BC_MAX_EXP ((unsigned long) LONG_MAX)
  745. //#define BC_MAX_VARS ((unsigned long) SIZE_MAX - 1)
  746. #define BC_MAX_EXP_STR "999999999"
  747. #define BC_MAX_VARS_STR "999999999"
  748. #define BC_MAX_OBASE_STR "999"
  749. #if INT_MAX == 2147483647
  750. # define BC_MAX_DIM_STR "2147483647"
  751. #elif INT_MAX == 9223372036854775807
  752. # define BC_MAX_DIM_STR "9223372036854775807"
  753. #else
  754. # error Strange INT_MAX
  755. #endif
  756. #if UINT_MAX == 4294967295U
  757. # define BC_MAX_SCALE_STR "4294967295"
  758. # define BC_MAX_STRING_STR "4294967294"
  759. #elif UINT_MAX == 18446744073709551615U
  760. # define BC_MAX_SCALE_STR "18446744073709551615"
  761. # define BC_MAX_STRING_STR "18446744073709551614"
  762. #else
  763. # error Strange UINT_MAX
  764. #endif
  765. #define BC_MAX_NUM_STR BC_MAX_STRING_STR
  766. // In configurations where errors abort instead of propagating error
  767. // return code up the call chain, functions returning BC_STATUS
  768. // actually don't return anything, they always succeed and return "void".
  769. // A macro wrapper is provided, which makes this statement work:
  770. // s = zbc_func(...)
  771. // and makes it visible to the compiler that s is always zero,
  772. // allowing compiler to optimize dead code after the statement.
  773. //
  774. // To make code more readable, each such function has a "z"
  775. // ("always returning zero") prefix, i.e. zbc_foo or zdc_foo.
  776. //
  777. #if ENABLE_FEATURE_BC_INTERACTIVE || ENABLE_FEATURE_CLEAN_UP
  778. # define ERRORS_ARE_FATAL 0
  779. # define ERRORFUNC /*nothing*/
  780. # define IF_ERROR_RETURN_POSSIBLE(a) a
  781. # define BC_STATUS BcStatus
  782. # define RETURN_STATUS(v) return (v)
  783. # define COMMA_SUCCESS /*nothing*/
  784. #else
  785. # define ERRORS_ARE_FATAL 1
  786. # define ERRORFUNC NORETURN
  787. # define IF_ERROR_RETURN_POSSIBLE(a) /*nothing*/
  788. # define BC_STATUS void
  789. # define RETURN_STATUS(v) do { ((void)(v)); return; } while (0)
  790. # define COMMA_SUCCESS ,BC_STATUS_SUCCESS
  791. #endif
  792. //
  793. // Utility routines
  794. //
  795. #define BC_MAX(a, b) ((a) > (b) ? (a) : (b))
  796. #define BC_MIN(a, b) ((a) < (b) ? (a) : (b))
  797. static void fflush_and_check(void)
  798. {
  799. fflush_all();
  800. if (ferror(stdout) || ferror(stderr))
  801. bb_simple_perror_msg_and_die("output error");
  802. }
  803. #if ENABLE_FEATURE_CLEAN_UP
  804. #define QUIT_OR_RETURN_TO_MAIN \
  805. do { \
  806. IF_FEATURE_BC_INTERACTIVE(G_ttyin = 0;) /* do not loop in main loop anymore */ \
  807. G_exiting = 1; \
  808. return BC_STATUS_FAILURE; \
  809. } while (0)
  810. #else
  811. static void quit(void) NORETURN;
  812. static void quit(void)
  813. {
  814. if (ferror(stdin))
  815. bb_simple_perror_msg_and_die("input error");
  816. fflush_and_check();
  817. dbg_exec("quit(): exiting with exitcode SUCCESS");
  818. exit(0);
  819. }
  820. #define QUIT_OR_RETURN_TO_MAIN quit()
  821. #endif
  822. static void bc_verror_msg(const char *fmt, va_list p)
  823. {
  824. const char *sv = sv; // for compiler
  825. if (G.prs.lex_filename) {
  826. sv = applet_name;
  827. applet_name = xasprintf("%s: %s:%lu", applet_name,
  828. G.prs.lex_filename, (unsigned long)G.err_line
  829. );
  830. }
  831. bb_verror_msg(fmt, p, NULL);
  832. if (G.prs.lex_filename) {
  833. free((char*)applet_name);
  834. applet_name = sv;
  835. }
  836. }
  837. static NOINLINE ERRORFUNC int bc_error_fmt(const char *fmt, ...)
  838. {
  839. va_list p;
  840. va_start(p, fmt);
  841. bc_verror_msg(fmt, p);
  842. va_end(p);
  843. if (ENABLE_FEATURE_CLEAN_UP || G_ttyin)
  844. IF_ERROR_RETURN_POSSIBLE(return BC_STATUS_FAILURE);
  845. exit(1);
  846. }
  847. #if ENABLE_BC
  848. static NOINLINE BC_STATUS zbc_posix_error_fmt(const char *fmt, ...)
  849. {
  850. va_list p;
  851. // Are non-POSIX constructs totally ok?
  852. if (!(option_mask32 & (BC_FLAG_S|BC_FLAG_W)))
  853. RETURN_STATUS(BC_STATUS_SUCCESS); // yes
  854. va_start(p, fmt);
  855. bc_verror_msg(fmt, p);
  856. va_end(p);
  857. // Do we treat non-POSIX constructs as errors?
  858. if (!(option_mask32 & BC_FLAG_S))
  859. RETURN_STATUS(BC_STATUS_SUCCESS); // no, it's a warning
  860. if (ENABLE_FEATURE_CLEAN_UP || G_ttyin)
  861. RETURN_STATUS(BC_STATUS_FAILURE);
  862. exit(1);
  863. }
  864. #define zbc_posix_error_fmt(...) (zbc_posix_error_fmt(__VA_ARGS__) COMMA_SUCCESS)
  865. #endif
  866. // We use error functions with "return bc_error(FMT[, PARAMS])" idiom.
  867. // This idiom begs for tail-call optimization, but for it to work,
  868. // function must not have caller-cleaned parameters on stack.
  869. // Unfortunately, vararg function API does exactly that on most arches.
  870. // Thus, use these shims for the cases when we have no vararg PARAMS:
  871. static ERRORFUNC int bc_error(const char *msg)
  872. {
  873. IF_ERROR_RETURN_POSSIBLE(return) bc_error_fmt("%s", msg);
  874. }
  875. static ERRORFUNC int bc_error_at(const char *msg)
  876. {
  877. const char *err_at = G.prs.lex_next_at;
  878. if (err_at) {
  879. IF_ERROR_RETURN_POSSIBLE(return) bc_error_fmt(
  880. "%s at '%.*s'",
  881. msg,
  882. (int)(strchrnul(err_at, '\n') - err_at),
  883. err_at
  884. );
  885. }
  886. IF_ERROR_RETURN_POSSIBLE(return) bc_error_fmt("%s", msg);
  887. }
  888. static ERRORFUNC int bc_error_bad_character(char c)
  889. {
  890. if (!c)
  891. IF_ERROR_RETURN_POSSIBLE(return) bc_error("NUL character");
  892. IF_ERROR_RETURN_POSSIBLE(return) bc_error_fmt("bad character '%c'", c);
  893. }
  894. #if ENABLE_BC
  895. static ERRORFUNC int bc_error_bad_function_definition(void)
  896. {
  897. IF_ERROR_RETURN_POSSIBLE(return) bc_error_at("bad function definition");
  898. }
  899. #endif
  900. static ERRORFUNC int bc_error_bad_expression(void)
  901. {
  902. IF_ERROR_RETURN_POSSIBLE(return) bc_error_at("bad expression");
  903. }
  904. static ERRORFUNC int bc_error_bad_assignment(void)
  905. {
  906. IF_ERROR_RETURN_POSSIBLE(return) bc_error_at(
  907. "bad assignment: left side must be variable or array element"
  908. );
  909. }
  910. static ERRORFUNC int bc_error_bad_token(void)
  911. {
  912. IF_ERROR_RETURN_POSSIBLE(return) bc_error_at("bad token");
  913. }
  914. static ERRORFUNC int bc_error_stack_has_too_few_elements(void)
  915. {
  916. IF_ERROR_RETURN_POSSIBLE(return) bc_error("stack has too few elements");
  917. }
  918. static ERRORFUNC int bc_error_variable_is_wrong_type(void)
  919. {
  920. IF_ERROR_RETURN_POSSIBLE(return) bc_error("variable is wrong type");
  921. }
  922. #if ENABLE_BC
  923. static BC_STATUS zbc_POSIX_requires(const char *msg)
  924. {
  925. RETURN_STATUS(zbc_posix_error_fmt("POSIX requires %s", msg));
  926. }
  927. #define zbc_POSIX_requires(...) (zbc_POSIX_requires(__VA_ARGS__) COMMA_SUCCESS)
  928. static BC_STATUS zbc_POSIX_does_not_allow(const char *msg)
  929. {
  930. RETURN_STATUS(zbc_posix_error_fmt("%s%s", "POSIX does not allow ", msg));
  931. }
  932. #define zbc_POSIX_does_not_allow(...) (zbc_POSIX_does_not_allow(__VA_ARGS__) COMMA_SUCCESS)
  933. static BC_STATUS zbc_POSIX_does_not_allow_bool_ops_this_is_bad(const char *msg)
  934. {
  935. RETURN_STATUS(zbc_posix_error_fmt("%s%s %s", "POSIX does not allow ", "boolean operators; this is bad:", msg));
  936. }
  937. #define zbc_POSIX_does_not_allow_bool_ops_this_is_bad(...) (zbc_POSIX_does_not_allow_bool_ops_this_is_bad(__VA_ARGS__) COMMA_SUCCESS)
  938. static BC_STATUS zbc_POSIX_does_not_allow_empty_X_expression_in_for(const char *msg)
  939. {
  940. RETURN_STATUS(zbc_posix_error_fmt("%san empty %s expression in 'for()'", "POSIX does not allow ", msg));
  941. }
  942. #define zbc_POSIX_does_not_allow_empty_X_expression_in_for(...) (zbc_POSIX_does_not_allow_empty_X_expression_in_for(__VA_ARGS__) COMMA_SUCCESS)
  943. #endif
  944. static void bc_vec_grow(BcVec *v, size_t n)
  945. {
  946. size_t cap = v->cap * 2;
  947. while (cap < v->len + n) cap *= 2;
  948. v->v = xrealloc(v->v, v->size * cap);
  949. v->cap = cap;
  950. }
  951. static void bc_vec_init(BcVec *v, size_t esize, BcVecFree dtor)
  952. {
  953. v->size = esize;
  954. v->cap = BC_VEC_START_CAP;
  955. v->len = 0;
  956. v->dtor = dtor;
  957. v->v = xmalloc(esize * BC_VEC_START_CAP);
  958. }
  959. static void bc_char_vec_init(BcVec *v)
  960. {
  961. bc_vec_init(v, sizeof(char), NULL);
  962. }
  963. static void bc_vec_expand(BcVec *v, size_t req)
  964. {
  965. if (v->cap < req) {
  966. v->v = xrealloc(v->v, v->size * req);
  967. v->cap = req;
  968. }
  969. }
  970. static void bc_vec_pop(BcVec *v)
  971. {
  972. v->len--;
  973. if (v->dtor)
  974. v->dtor(v->v + (v->size * v->len));
  975. }
  976. static void bc_vec_npop(BcVec *v, size_t n)
  977. {
  978. if (!v->dtor)
  979. v->len -= n;
  980. else {
  981. size_t len = v->len - n;
  982. while (v->len > len) v->dtor(v->v + (v->size * --v->len));
  983. }
  984. }
  985. static void bc_vec_pop_all(BcVec *v)
  986. {
  987. bc_vec_npop(v, v->len);
  988. }
  989. static size_t bc_vec_npush(BcVec *v, size_t n, const void *data)
  990. {
  991. size_t len = v->len;
  992. if (len + n > v->cap) bc_vec_grow(v, n);
  993. memmove(v->v + (v->size * len), data, v->size * n);
  994. v->len = len + n;
  995. return len;
  996. }
  997. static size_t bc_vec_push(BcVec *v, const void *data)
  998. {
  999. return bc_vec_npush(v, 1, data);
  1000. //size_t len = v->len;
  1001. //if (len >= v->cap) bc_vec_grow(v, 1);
  1002. //memmove(v->v + (v->size * len), data, v->size);
  1003. //v->len = len + 1;
  1004. //return len;
  1005. }
  1006. // G.prog.results often needs "pop old operand, push result" idiom.
  1007. // Can do this without a few extra ops
  1008. static size_t bc_result_pop_and_push(const void *data)
  1009. {
  1010. BcVec *v = &G.prog.results;
  1011. char *last;
  1012. size_t len = v->len - 1;
  1013. last = v->v + (v->size * len);
  1014. if (v->dtor)
  1015. v->dtor(last);
  1016. memmove(last, data, v->size);
  1017. return len;
  1018. }
  1019. static size_t bc_vec_pushByte(BcVec *v, char data)
  1020. {
  1021. return bc_vec_push(v, &data);
  1022. }
  1023. static size_t bc_vec_pushZeroByte(BcVec *v)
  1024. {
  1025. //return bc_vec_pushByte(v, '\0');
  1026. // better:
  1027. return bc_vec_push(v, &const_int_0);
  1028. }
  1029. static void bc_vec_pushAt(BcVec *v, const void *data, size_t idx)
  1030. {
  1031. if (idx == v->len)
  1032. bc_vec_push(v, data);
  1033. else {
  1034. char *ptr;
  1035. if (v->len == v->cap) bc_vec_grow(v, 1);
  1036. ptr = v->v + v->size * idx;
  1037. memmove(ptr + v->size, ptr, v->size * (v->len++ - idx));
  1038. memmove(ptr, data, v->size);
  1039. }
  1040. }
  1041. static void bc_vec_string(BcVec *v, size_t len, const char *str)
  1042. {
  1043. bc_vec_pop_all(v);
  1044. bc_vec_expand(v, len + 1);
  1045. memcpy(v->v, str, len);
  1046. v->len = len;
  1047. bc_vec_pushZeroByte(v);
  1048. }
  1049. static void *bc_vec_item(const BcVec *v, size_t idx)
  1050. {
  1051. return v->v + v->size * idx;
  1052. }
  1053. static void *bc_vec_item_rev(const BcVec *v, size_t idx)
  1054. {
  1055. return v->v + v->size * (v->len - idx - 1);
  1056. }
  1057. static void *bc_vec_top(const BcVec *v)
  1058. {
  1059. return v->v + v->size * (v->len - 1);
  1060. }
  1061. static FAST_FUNC void bc_vec_free(void *vec)
  1062. {
  1063. BcVec *v = (BcVec *) vec;
  1064. bc_vec_pop_all(v);
  1065. free(v->v);
  1066. }
  1067. static BcFunc* xc_program_func(size_t idx)
  1068. {
  1069. return bc_vec_item(&G.prog.fns, idx);
  1070. }
  1071. // BC_PROG_MAIN is zeroth element, so:
  1072. #define xc_program_func_BC_PROG_MAIN() ((BcFunc*)(G.prog.fns.v))
  1073. #if ENABLE_BC
  1074. static BcFunc* bc_program_current_func(void)
  1075. {
  1076. BcInstPtr *ip = bc_vec_top(&G.prog.exestack);
  1077. BcFunc *func = xc_program_func(ip->func);
  1078. return func;
  1079. }
  1080. #endif
  1081. static char** xc_program_str(size_t idx)
  1082. {
  1083. #if ENABLE_BC
  1084. if (IS_BC) {
  1085. BcFunc *func = bc_program_current_func();
  1086. return bc_vec_item(&func->strs, idx);
  1087. }
  1088. #endif
  1089. IF_DC(return bc_vec_item(&G.prog.strs, idx);)
  1090. }
  1091. static char** xc_program_const(size_t idx)
  1092. {
  1093. #if ENABLE_BC
  1094. if (IS_BC) {
  1095. BcFunc *func = bc_program_current_func();
  1096. return bc_vec_item(&func->consts, idx);
  1097. }
  1098. #endif
  1099. IF_DC(return bc_vec_item(&G.prog.consts, idx);)
  1100. }
  1101. static int bc_id_cmp(const void *e1, const void *e2)
  1102. {
  1103. return strcmp(((const BcId *) e1)->name, ((const BcId *) e2)->name);
  1104. }
  1105. static FAST_FUNC void bc_id_free(void *id)
  1106. {
  1107. free(((BcId *) id)->name);
  1108. }
  1109. static size_t bc_map_find_ge(const BcVec *v, const void *ptr)
  1110. {
  1111. size_t low = 0, high = v->len;
  1112. while (low < high) {
  1113. size_t mid = (low + high) / 2;
  1114. BcId *id = bc_vec_item(v, mid);
  1115. int result = bc_id_cmp(ptr, id);
  1116. if (result == 0)
  1117. return mid;
  1118. if (result < 0)
  1119. high = mid;
  1120. else
  1121. low = mid + 1;
  1122. }
  1123. return low;
  1124. }
  1125. static int bc_map_insert(BcVec *v, const void *ptr, size_t *i)
  1126. {
  1127. size_t n = *i = bc_map_find_ge(v, ptr);
  1128. if (n == v->len)
  1129. bc_vec_push(v, ptr);
  1130. else if (!bc_id_cmp(ptr, bc_vec_item(v, n)))
  1131. return 0; // "was not inserted"
  1132. else
  1133. bc_vec_pushAt(v, ptr, n);
  1134. return 1; // "was inserted"
  1135. }
  1136. static size_t bc_map_find_exact(const BcVec *v, const void *ptr)
  1137. {
  1138. size_t i = bc_map_find_ge(v, ptr);
  1139. if (i >= v->len) return BC_VEC_INVALID_IDX;
  1140. return bc_id_cmp(ptr, bc_vec_item(v, i)) ? BC_VEC_INVALID_IDX : i;
  1141. }
  1142. static void bc_num_setToZero(BcNum *n, size_t scale)
  1143. {
  1144. n->len = 0;
  1145. n->neg = false;
  1146. n->rdx = scale;
  1147. }
  1148. static void bc_num_zero(BcNum *n)
  1149. {
  1150. bc_num_setToZero(n, 0);
  1151. }
  1152. static void bc_num_one(BcNum *n)
  1153. {
  1154. bc_num_setToZero(n, 0);
  1155. n->len = 1;
  1156. n->num[0] = 1;
  1157. }
  1158. // Note: this also sets BcNum to zero
  1159. static void bc_num_init(BcNum *n, size_t req)
  1160. {
  1161. req = req >= BC_NUM_DEF_SIZE ? req : BC_NUM_DEF_SIZE;
  1162. //memset(n, 0, sizeof(BcNum)); - cleared by assignments below
  1163. n->num = xmalloc(req);
  1164. n->cap = req;
  1165. n->rdx = 0;
  1166. n->len = 0;
  1167. n->neg = false;
  1168. }
  1169. static void bc_num_init_DEF_SIZE(BcNum *n)
  1170. {
  1171. bc_num_init(n, BC_NUM_DEF_SIZE);
  1172. }
  1173. static void bc_num_expand(BcNum *n, size_t req)
  1174. {
  1175. req = req >= BC_NUM_DEF_SIZE ? req : BC_NUM_DEF_SIZE;
  1176. if (req > n->cap) {
  1177. n->num = xrealloc(n->num, req);
  1178. n->cap = req;
  1179. }
  1180. }
  1181. static FAST_FUNC void bc_num_free(void *num)
  1182. {
  1183. free(((BcNum *) num)->num);
  1184. }
  1185. static void bc_num_copy(BcNum *d, BcNum *s)
  1186. {
  1187. if (d != s) {
  1188. bc_num_expand(d, s->cap);
  1189. d->len = s->len;
  1190. d->neg = s->neg;
  1191. d->rdx = s->rdx;
  1192. memcpy(d->num, s->num, sizeof(BcDig) * d->len);
  1193. }
  1194. }
  1195. static BC_STATUS zbc_num_ulong_abs(BcNum *n, unsigned long *result_p)
  1196. {
  1197. size_t i;
  1198. unsigned long result;
  1199. result = 0;
  1200. i = n->len;
  1201. while (i > n->rdx) {
  1202. unsigned long prev = result;
  1203. result = result * 10 + n->num[--i];
  1204. // Even overflowed N*10 can still satisfy N*10>=N. For example,
  1205. // 0x1ff00000 * 10 is 0x13f600000,
  1206. // or 0x3f600000 truncated to 32 bits. Which is larger.
  1207. // However, (N*10)/8 < N check is always correct.
  1208. if ((result / 8) < prev)
  1209. RETURN_STATUS(bc_error("overflow"));
  1210. }
  1211. *result_p = result;
  1212. RETURN_STATUS(BC_STATUS_SUCCESS);
  1213. }
  1214. #define zbc_num_ulong_abs(...) (zbc_num_ulong_abs(__VA_ARGS__) COMMA_SUCCESS)
  1215. static BC_STATUS zbc_num_ulong(BcNum *n, unsigned long *result_p)
  1216. {
  1217. if (n->neg) RETURN_STATUS(bc_error("negative number"));
  1218. RETURN_STATUS(zbc_num_ulong_abs(n, result_p));
  1219. }
  1220. #define zbc_num_ulong(...) (zbc_num_ulong(__VA_ARGS__) COMMA_SUCCESS)
  1221. #if ULONG_MAX == 0xffffffffUL // 10 digits: 4294967295
  1222. # define ULONG_NUM_BUFSIZE (10 > BC_NUM_DEF_SIZE ? 10 : BC_NUM_DEF_SIZE)
  1223. #elif ULONG_MAX == 0xffffffffffffffffULL // 20 digits: 18446744073709551615
  1224. # define ULONG_NUM_BUFSIZE (20 > BC_NUM_DEF_SIZE ? 20 : BC_NUM_DEF_SIZE)
  1225. #endif
  1226. // minimum BC_NUM_DEF_SIZE, so that bc_num_expand() in bc_num_ulong2num()
  1227. // would not hit realloc() code path - not good if num[] is not malloced
  1228. static void bc_num_ulong2num(BcNum *n, unsigned long val)
  1229. {
  1230. BcDig *ptr;
  1231. bc_num_zero(n);
  1232. if (val == 0) return;
  1233. bc_num_expand(n, ULONG_NUM_BUFSIZE);
  1234. ptr = n->num;
  1235. for (;;) {
  1236. n->len++;
  1237. *ptr++ = val % 10;
  1238. val /= 10;
  1239. if (val == 0) break;
  1240. }
  1241. }
  1242. static void bc_num_subArrays(BcDig *restrict a, BcDig *restrict b, size_t len)
  1243. {
  1244. size_t i, j;
  1245. for (i = 0; i < len; ++i) {
  1246. a[i] -= b[i];
  1247. for (j = i; a[j] < 0;) {
  1248. a[j++] += 10;
  1249. a[j] -= 1;
  1250. }
  1251. }
  1252. }
  1253. static ssize_t bc_num_compare(BcDig *restrict a, BcDig *restrict b, size_t len)
  1254. {
  1255. size_t i = len;
  1256. for (;;) {
  1257. int c;
  1258. if (i == 0)
  1259. return 0;
  1260. i--;
  1261. c = a[i] - b[i];
  1262. if (c != 0) {
  1263. i++;
  1264. if (c < 0)
  1265. return -i;
  1266. return i;
  1267. }
  1268. }
  1269. }
  1270. #define BC_NUM_NEG(n, neg) ((((ssize_t)(n)) ^ -((ssize_t)(neg))) + (neg))
  1271. #define BC_NUM_ONE(n) ((n)->len == 1 && (n)->rdx == 0 && (n)->num[0] == 1)
  1272. #define BC_NUM_INT(n) ((n)->len - (n)->rdx)
  1273. //#define BC_NUM_AREQ(a, b) (BC_MAX((a)->rdx, (b)->rdx) + BC_MAX(BC_NUM_INT(a), BC_NUM_INT(b)) + 1)
  1274. static /*ALWAYS_INLINE*/ size_t BC_NUM_AREQ(BcNum *a, BcNum *b)
  1275. {
  1276. return BC_MAX(a->rdx, b->rdx) + BC_MAX(BC_NUM_INT(a), BC_NUM_INT(b)) + 1;
  1277. }
  1278. //#define BC_NUM_MREQ(a, b, scale) (BC_NUM_INT(a) + BC_NUM_INT(b) + BC_MAX((scale), (a)->rdx + (b)->rdx) + 1)
  1279. static /*ALWAYS_INLINE*/ size_t BC_NUM_MREQ(BcNum *a, BcNum *b, size_t scale)
  1280. {
  1281. return BC_NUM_INT(a) + BC_NUM_INT(b) + BC_MAX(scale, a->rdx + b->rdx) + 1;
  1282. }
  1283. static ssize_t bc_num_cmp(BcNum *a, BcNum *b)
  1284. {
  1285. size_t i, min, a_int, b_int, diff;
  1286. BcDig *max_num, *min_num;
  1287. bool a_max, neg;
  1288. ssize_t cmp;
  1289. if (a == b) return 0;
  1290. if (a->len == 0) return BC_NUM_NEG(!!b->len, !b->neg);
  1291. if (b->len == 0) return BC_NUM_NEG(1, a->neg);
  1292. if (a->neg != b->neg) // signs of a and b differ
  1293. // +a,-b = a>b = 1 or -a,+b = a<b = -1
  1294. return (int)b->neg - (int)a->neg;
  1295. neg = a->neg; // 1 if both negative, 0 if both positive
  1296. a_int = BC_NUM_INT(a);
  1297. b_int = BC_NUM_INT(b);
  1298. a_int -= b_int;
  1299. if (a_int != 0) {
  1300. if (neg) return - (ssize_t) a_int;
  1301. return (ssize_t) a_int;
  1302. }
  1303. a_max = (a->rdx > b->rdx);
  1304. if (a_max) {
  1305. min = b->rdx;
  1306. diff = a->rdx - b->rdx;
  1307. max_num = a->num + diff;
  1308. min_num = b->num;
  1309. // neg = (a_max == neg); - NOP (maps 1->1 and 0->0)
  1310. } else {
  1311. min = a->rdx;
  1312. diff = b->rdx - a->rdx;
  1313. max_num = b->num + diff;
  1314. min_num = a->num;
  1315. neg = !neg; // same as "neg = (a_max == neg)"
  1316. }
  1317. cmp = bc_num_compare(max_num, min_num, b_int + min);
  1318. if (cmp != 0) return BC_NUM_NEG(cmp, neg);
  1319. for (max_num -= diff, i = diff - 1; i < diff; --i) {
  1320. if (max_num[i]) return BC_NUM_NEG(1, neg);
  1321. }
  1322. return 0;
  1323. }
  1324. static void bc_num_truncate(BcNum *n, size_t places)
  1325. {
  1326. if (places == 0) return;
  1327. n->rdx -= places;
  1328. if (n->len != 0) {
  1329. n->len -= places;
  1330. memmove(n->num, n->num + places, n->len * sizeof(BcDig));
  1331. }
  1332. }
  1333. static void bc_num_extend(BcNum *n, size_t places)
  1334. {
  1335. size_t len = n->len + places;
  1336. if (places != 0) {
  1337. if (n->cap < len) bc_num_expand(n, len);
  1338. memmove(n->num + places, n->num, sizeof(BcDig) * n->len);
  1339. memset(n->num, 0, sizeof(BcDig) * places);
  1340. n->len += places;
  1341. n->rdx += places;
  1342. }
  1343. }
  1344. static void bc_num_clean(BcNum *n)
  1345. {
  1346. while (n->len > 0 && n->num[n->len - 1] == 0) --n->len;
  1347. if (n->len == 0)
  1348. n->neg = false;
  1349. else if (n->len < n->rdx)
  1350. n->len = n->rdx;
  1351. }
  1352. static void bc_num_retireMul(BcNum *n, size_t scale, bool neg1, bool neg2)
  1353. {
  1354. if (n->rdx < scale)
  1355. bc_num_extend(n, scale - n->rdx);
  1356. else
  1357. bc_num_truncate(n, n->rdx - scale);
  1358. bc_num_clean(n);
  1359. if (n->len != 0) n->neg = !neg1 != !neg2;
  1360. }
  1361. static void bc_num_split(BcNum *restrict n, size_t idx, BcNum *restrict a,
  1362. BcNum *restrict b)
  1363. {
  1364. if (idx < n->len) {
  1365. b->len = n->len - idx;
  1366. a->len = idx;
  1367. a->rdx = b->rdx = 0;
  1368. memcpy(b->num, n->num + idx, b->len * sizeof(BcDig));
  1369. memcpy(a->num, n->num, idx * sizeof(BcDig));
  1370. } else {
  1371. bc_num_zero(b);
  1372. bc_num_copy(a, n);
  1373. }
  1374. bc_num_clean(a);
  1375. bc_num_clean(b);
  1376. }
  1377. static BC_STATUS zbc_num_shift(BcNum *n, size_t places)
  1378. {
  1379. if (places == 0 || n->len == 0) RETURN_STATUS(BC_STATUS_SUCCESS);
  1380. // This check makes sense only if size_t is (much) larger than BC_MAX_NUM.
  1381. if (SIZE_MAX > (BC_MAX_NUM | 0xff)) {
  1382. if (places + n->len > BC_MAX_NUM)
  1383. RETURN_STATUS(bc_error("number too long: must be [1,"BC_MAX_NUM_STR"]"));
  1384. }
  1385. if (n->rdx >= places)
  1386. n->rdx -= places;
  1387. else {
  1388. bc_num_extend(n, places - n->rdx);
  1389. n->rdx = 0;
  1390. }
  1391. bc_num_clean(n);
  1392. RETURN_STATUS(BC_STATUS_SUCCESS);
  1393. }
  1394. #define zbc_num_shift(...) (zbc_num_shift(__VA_ARGS__) COMMA_SUCCESS)
  1395. typedef BC_STATUS (*BcNumBinaryOp)(BcNum *, BcNum *, BcNum *, size_t) FAST_FUNC;
  1396. static BC_STATUS zbc_num_binary(BcNum *a, BcNum *b, BcNum *c, size_t scale,
  1397. BcNumBinaryOp op, size_t req)
  1398. {
  1399. BcStatus s;
  1400. BcNum num2, *ptr_a, *ptr_b;
  1401. bool init = false;
  1402. if (c == a) {
  1403. ptr_a = &num2;
  1404. memcpy(ptr_a, c, sizeof(BcNum));
  1405. init = true;
  1406. } else
  1407. ptr_a = a;
  1408. if (c == b) {
  1409. ptr_b = &num2;
  1410. if (c != a) {
  1411. memcpy(ptr_b, c, sizeof(BcNum));
  1412. init = true;
  1413. }
  1414. } else
  1415. ptr_b = b;
  1416. if (init)
  1417. bc_num_init(c, req);
  1418. else
  1419. bc_num_expand(c, req);
  1420. s = BC_STATUS_SUCCESS;
  1421. IF_ERROR_RETURN_POSSIBLE(s =) op(ptr_a, ptr_b, c, scale);
  1422. if (init) bc_num_free(&num2);
  1423. RETURN_STATUS(s);
  1424. }
  1425. #define zbc_num_binary(...) (zbc_num_binary(__VA_ARGS__) COMMA_SUCCESS)
  1426. static FAST_FUNC BC_STATUS zbc_num_a(BcNum *a, BcNum *b, BcNum *restrict c, size_t scale);
  1427. static FAST_FUNC BC_STATUS zbc_num_s(BcNum *a, BcNum *b, BcNum *restrict c, size_t scale);
  1428. static FAST_FUNC BC_STATUS zbc_num_p(BcNum *a, BcNum *b, BcNum *restrict c, size_t scale);
  1429. static FAST_FUNC BC_STATUS zbc_num_m(BcNum *a, BcNum *b, BcNum *restrict c, size_t scale);
  1430. static FAST_FUNC BC_STATUS zbc_num_d(BcNum *a, BcNum *b, BcNum *restrict c, size_t scale);
  1431. static FAST_FUNC BC_STATUS zbc_num_rem(BcNum *a, BcNum *b, BcNum *restrict c, size_t scale);
  1432. static FAST_FUNC BC_STATUS zbc_num_add(BcNum *a, BcNum *b, BcNum *c, size_t scale)
  1433. {
  1434. BcNumBinaryOp op = (!a->neg == !b->neg) ? zbc_num_a : zbc_num_s;
  1435. (void) scale;
  1436. RETURN_STATUS(zbc_num_binary(a, b, c, false, op, BC_NUM_AREQ(a, b)));
  1437. }
  1438. static FAST_FUNC BC_STATUS zbc_num_sub(BcNum *a, BcNum *b, BcNum *c, size_t scale)
  1439. {
  1440. BcNumBinaryOp op = (!a->neg == !b->neg) ? zbc_num_s : zbc_num_a;
  1441. (void) scale;
  1442. RETURN_STATUS(zbc_num_binary(a, b, c, true, op, BC_NUM_AREQ(a, b)));
  1443. }
  1444. static FAST_FUNC BC_STATUS zbc_num_mul(BcNum *a, BcNum *b, BcNum *c, size_t scale)
  1445. {
  1446. size_t req = BC_NUM_MREQ(a, b, scale);
  1447. RETURN_STATUS(zbc_num_binary(a, b, c, scale, zbc_num_m, req));
  1448. }
  1449. static FAST_FUNC BC_STATUS zbc_num_div(BcNum *a, BcNum *b, BcNum *c, size_t scale)
  1450. {
  1451. size_t req = BC_NUM_MREQ(a, b, scale);
  1452. RETURN_STATUS(zbc_num_binary(a, b, c, scale, zbc_num_d, req));
  1453. }
  1454. static FAST_FUNC BC_STATUS zbc_num_mod(BcNum *a, BcNum *b, BcNum *c, size_t scale)
  1455. {
  1456. size_t req = BC_NUM_MREQ(a, b, scale);
  1457. RETURN_STATUS(zbc_num_binary(a, b, c, scale, zbc_num_rem, req));
  1458. }
  1459. static FAST_FUNC BC_STATUS zbc_num_pow(BcNum *a, BcNum *b, BcNum *c, size_t scale)
  1460. {
  1461. RETURN_STATUS(zbc_num_binary(a, b, c, scale, zbc_num_p, a->len * b->len + 1));
  1462. }
  1463. static const BcNumBinaryOp zxc_program_ops[] = {
  1464. zbc_num_pow, zbc_num_mul, zbc_num_div, zbc_num_mod, zbc_num_add, zbc_num_sub,
  1465. };
  1466. #define zbc_num_add(...) (zbc_num_add(__VA_ARGS__) COMMA_SUCCESS)
  1467. #define zbc_num_sub(...) (zbc_num_sub(__VA_ARGS__) COMMA_SUCCESS)
  1468. #define zbc_num_mul(...) (zbc_num_mul(__VA_ARGS__) COMMA_SUCCESS)
  1469. #define zbc_num_div(...) (zbc_num_div(__VA_ARGS__) COMMA_SUCCESS)
  1470. #define zbc_num_mod(...) (zbc_num_mod(__VA_ARGS__) COMMA_SUCCESS)
  1471. #define zbc_num_pow(...) (zbc_num_pow(__VA_ARGS__) COMMA_SUCCESS)
  1472. static BC_STATUS zbc_num_inv(BcNum *a, BcNum *b, size_t scale)
  1473. {
  1474. BcNum one;
  1475. BcDig num[2];
  1476. one.cap = 2;
  1477. one.num = num;
  1478. bc_num_one(&one);
  1479. RETURN_STATUS(zbc_num_div(&one, a, b, scale));
  1480. }
  1481. #define zbc_num_inv(...) (zbc_num_inv(__VA_ARGS__) COMMA_SUCCESS)
  1482. static FAST_FUNC BC_STATUS zbc_num_a(BcNum *a, BcNum *b, BcNum *restrict c, size_t sub)
  1483. {
  1484. BcDig *ptr, *ptr_a, *ptr_b, *ptr_c;
  1485. size_t i, max, min_rdx, min_int, diff, a_int, b_int;
  1486. unsigned carry;
  1487. // Because this function doesn't need to use scale (per the bc spec),
  1488. // I am hijacking it to say whether it's doing an add or a subtract.
  1489. if (a->len == 0) {
  1490. bc_num_copy(c, b);
  1491. if (sub && c->len) c->neg = !c->neg;
  1492. RETURN_STATUS(BC_STATUS_SUCCESS);
  1493. }
  1494. if (b->len == 0) {
  1495. bc_num_copy(c, a);
  1496. RETURN_STATUS(BC_STATUS_SUCCESS);
  1497. }
  1498. c->neg = a->neg;
  1499. c->rdx = BC_MAX(a->rdx, b->rdx);
  1500. min_rdx = BC_MIN(a->rdx, b->rdx);
  1501. c->len = 0;
  1502. if (a->rdx > b->rdx) {
  1503. diff = a->rdx - b->rdx;
  1504. ptr = a->num;
  1505. ptr_a = a->num + diff;
  1506. ptr_b = b->num;
  1507. } else {
  1508. diff = b->rdx - a->rdx;
  1509. ptr = b->num;
  1510. ptr_a = a->num;
  1511. ptr_b = b->num + diff;
  1512. }
  1513. ptr_c = c->num;
  1514. for (i = 0; i < diff; ++i, ++c->len)
  1515. ptr_c[i] = ptr[i];
  1516. ptr_c += diff;
  1517. a_int = BC_NUM_INT(a);
  1518. b_int = BC_NUM_INT(b);
  1519. if (a_int > b_int) {
  1520. min_int = b_int;
  1521. max = a_int;
  1522. ptr = ptr_a;
  1523. } else {
  1524. min_int = a_int;
  1525. max = b_int;
  1526. ptr = ptr_b;
  1527. }
  1528. carry = 0;
  1529. for (i = 0; i < min_rdx + min_int; ++i) {
  1530. unsigned in = (unsigned)ptr_a[i] + (unsigned)ptr_b[i] + carry;
  1531. carry = in / 10;
  1532. ptr_c[i] = (BcDig)(in % 10);
  1533. }
  1534. for (; i < max + min_rdx; ++i) {
  1535. unsigned in = (unsigned)ptr[i] + carry;
  1536. carry = in / 10;
  1537. ptr_c[i] = (BcDig)(in % 10);
  1538. }
  1539. c->len += i;
  1540. if (carry != 0) c->num[c->len++] = (BcDig) carry;
  1541. RETURN_STATUS(BC_STATUS_SUCCESS); // can't make void, see zbc_num_binary()
  1542. }
  1543. static FAST_FUNC BC_STATUS zbc_num_s(BcNum *a, BcNum *b, BcNum *restrict c, size_t sub)
  1544. {
  1545. ssize_t cmp;
  1546. BcNum *minuend, *subtrahend;
  1547. size_t start;
  1548. bool aneg, bneg, neg;
  1549. // Because this function doesn't need to use scale (per the bc spec),
  1550. // I am hijacking it to say whether it's doing an add or a subtract.
  1551. if (a->len == 0) {
  1552. bc_num_copy(c, b);
  1553. if (sub && c->len) c->neg = !c->neg;
  1554. RETURN_STATUS(BC_STATUS_SUCCESS);
  1555. }
  1556. if (b->len == 0) {
  1557. bc_num_copy(c, a);
  1558. RETURN_STATUS(BC_STATUS_SUCCESS);
  1559. }
  1560. aneg = a->neg;
  1561. bneg = b->neg;
  1562. a->neg = b->neg = false;
  1563. cmp = bc_num_cmp(a, b);
  1564. a->neg = aneg;
  1565. b->neg = bneg;
  1566. if (cmp == 0) {
  1567. bc_num_setToZero(c, BC_MAX(a->rdx, b->rdx));
  1568. RETURN_STATUS(BC_STATUS_SUCCESS);
  1569. }
  1570. if (cmp > 0) {
  1571. neg = a->neg;
  1572. minuend = a;
  1573. subtrahend = b;
  1574. } else {
  1575. neg = b->neg;
  1576. if (sub) neg = !neg;
  1577. minuend = b;
  1578. subtrahend = a;
  1579. }
  1580. bc_num_copy(c, minuend);
  1581. c->neg = neg;
  1582. if (c->rdx < subtrahend->rdx) {
  1583. bc_num_extend(c, subtrahend->rdx - c->rdx);
  1584. start = 0;
  1585. } else
  1586. start = c->rdx - subtrahend->rdx;
  1587. bc_num_subArrays(c->num + start, subtrahend->num, subtrahend->len);
  1588. bc_num_clean(c);
  1589. RETURN_STATUS(BC_STATUS_SUCCESS); // can't make void, see zbc_num_binary()
  1590. }
  1591. static FAST_FUNC BC_STATUS zbc_num_k(BcNum *restrict a, BcNum *restrict b,
  1592. BcNum *restrict c)
  1593. #define zbc_num_k(...) (zbc_num_k(__VA_ARGS__) COMMA_SUCCESS)
  1594. {
  1595. BcStatus s;
  1596. size_t max = BC_MAX(a->len, b->len), max2 = (max + 1) / 2;
  1597. BcNum l1, h1, l2, h2, m2, m1, z0, z1, z2, temp;
  1598. bool aone;
  1599. if (a->len == 0 || b->len == 0) {
  1600. bc_num_zero(c);
  1601. RETURN_STATUS(BC_STATUS_SUCCESS);
  1602. }
  1603. aone = BC_NUM_ONE(a);
  1604. if (aone || BC_NUM_ONE(b)) {
  1605. bc_num_copy(c, aone ? b : a);
  1606. RETURN_STATUS(BC_STATUS_SUCCESS);
  1607. }
  1608. if (a->len + b->len < BC_NUM_KARATSUBA_LEN
  1609. || a->len < BC_NUM_KARATSUBA_LEN
  1610. || b->len < BC_NUM_KARATSUBA_LEN
  1611. ) {
  1612. size_t i, j, len;
  1613. bc_num_expand(c, a->len + b->len + 1);
  1614. memset(c->num, 0, sizeof(BcDig) * c->cap);
  1615. c->len = len = 0;
  1616. for (i = 0; i < b->len; ++i) {
  1617. unsigned carry = 0;
  1618. for (j = 0; j < a->len; ++j) {
  1619. unsigned in = c->num[i + j];
  1620. in += (unsigned)a->num[j] * (unsigned)b->num[i] + carry;
  1621. // note: compilers prefer _unsigned_ div/const
  1622. carry = in / 10;
  1623. c->num[i + j] = (BcDig)(in % 10);
  1624. }
  1625. c->num[i + j] += (BcDig) carry;
  1626. len = BC_MAX(len, i + j + !!carry);
  1627. #if ENABLE_FEATURE_BC_INTERACTIVE
  1628. // a=2^1000000
  1629. // a*a <- without check below, this will not be interruptible
  1630. if (G_interrupt) return BC_STATUS_FAILURE;
  1631. #endif
  1632. }
  1633. c->len = len;
  1634. RETURN_STATUS(BC_STATUS_SUCCESS);
  1635. }
  1636. bc_num_init(&l1, max);
  1637. bc_num_init(&h1, max);
  1638. bc_num_init(&l2, max);
  1639. bc_num_init(&h2, max);
  1640. bc_num_init(&m1, max);
  1641. bc_num_init(&m2, max);
  1642. bc_num_init(&z0, max);
  1643. bc_num_init(&z1, max);
  1644. bc_num_init(&z2, max);
  1645. bc_num_init(&temp, max + max);
  1646. bc_num_split(a, max2, &l1, &h1);
  1647. bc_num_split(b, max2, &l2, &h2);
  1648. s = zbc_num_add(&h1, &l1, &m1, 0);
  1649. if (s) goto err;
  1650. s = zbc_num_add(&h2, &l2, &m2, 0);
  1651. if (s) goto err;
  1652. s = zbc_num_k(&h1, &h2, &z0);
  1653. if (s) goto err;
  1654. s = zbc_num_k(&m1, &m2, &z1);
  1655. if (s) goto err;
  1656. s = zbc_num_k(&l1, &l2, &z2);
  1657. if (s) goto err;
  1658. s = zbc_num_sub(&z1, &z0, &temp, 0);
  1659. if (s) goto err;
  1660. s = zbc_num_sub(&temp, &z2, &z1, 0);
  1661. if (s) goto err;
  1662. s = zbc_num_shift(&z0, max2 * 2);
  1663. if (s) goto err;
  1664. s = zbc_num_shift(&z1, max2);
  1665. if (s) goto err;
  1666. s = zbc_num_add(&z0, &z1, &temp, 0);
  1667. if (s) goto err;
  1668. s = zbc_num_add(&temp, &z2, c, 0);
  1669. err:
  1670. bc_num_free(&temp);
  1671. bc_num_free(&z2);
  1672. bc_num_free(&z1);
  1673. bc_num_free(&z0);
  1674. bc_num_free(&m2);
  1675. bc_num_free(&m1);
  1676. bc_num_free(&h2);
  1677. bc_num_free(&l2);
  1678. bc_num_free(&h1);
  1679. bc_num_free(&l1);
  1680. RETURN_STATUS(s);
  1681. }
  1682. static FAST_FUNC BC_STATUS zbc_num_m(BcNum *a, BcNum *b, BcNum *restrict c, size_t scale)
  1683. {
  1684. BcStatus s;
  1685. BcNum cpa, cpb;
  1686. size_t maxrdx = BC_MAX(a->rdx, b->rdx);
  1687. scale = BC_MAX(scale, a->rdx);
  1688. scale = BC_MAX(scale, b->rdx);
  1689. scale = BC_MIN(a->rdx + b->rdx, scale);
  1690. maxrdx = BC_MAX(maxrdx, scale);
  1691. bc_num_init(&cpa, a->len);
  1692. bc_num_init(&cpb, b->len);
  1693. bc_num_copy(&cpa, a);
  1694. bc_num_copy(&cpb, b);
  1695. cpa.neg = cpb.neg = false;
  1696. s = zbc_num_shift(&cpa, maxrdx);
  1697. if (s) goto err;
  1698. s = zbc_num_shift(&cpb, maxrdx);
  1699. if (s) goto err;
  1700. s = zbc_num_k(&cpa, &cpb, c);
  1701. if (s) goto err;
  1702. maxrdx += scale;
  1703. bc_num_expand(c, c->len + maxrdx);
  1704. if (c->len < maxrdx) {
  1705. memset(c->num + c->len, 0, (c->cap - c->len) * sizeof(BcDig));
  1706. c->len += maxrdx;
  1707. }
  1708. c->rdx = maxrdx;
  1709. bc_num_retireMul(c, scale, a->neg, b->neg);
  1710. err:
  1711. bc_num_free(&cpb);
  1712. bc_num_free(&cpa);
  1713. RETURN_STATUS(s);
  1714. }
  1715. #define zbc_num_m(...) (zbc_num_m(__VA_ARGS__) COMMA_SUCCESS)
  1716. static FAST_FUNC BC_STATUS zbc_num_d(BcNum *a, BcNum *b, BcNum *restrict c, size_t scale)
  1717. {
  1718. BcStatus s;
  1719. size_t len, end, i;
  1720. BcNum cp;
  1721. if (b->len == 0)
  1722. RETURN_STATUS(bc_error("divide by zero"));
  1723. if (a->len == 0) {
  1724. bc_num_setToZero(c, scale);
  1725. RETURN_STATUS(BC_STATUS_SUCCESS);
  1726. }
  1727. if (BC_NUM_ONE(b)) {
  1728. bc_num_copy(c, a);
  1729. bc_num_retireMul(c, scale, a->neg, b->neg);
  1730. RETURN_STATUS(BC_STATUS_SUCCESS);
  1731. }
  1732. bc_num_init(&cp, BC_NUM_MREQ(a, b, scale));
  1733. bc_num_copy(&cp, a);
  1734. len = b->len;
  1735. if (len > cp.len) {
  1736. bc_num_expand(&cp, len + 2);
  1737. bc_num_extend(&cp, len - cp.len);
  1738. }
  1739. if (b->rdx > cp.rdx) bc_num_extend(&cp, b->rdx - cp.rdx);
  1740. cp.rdx -= b->rdx;
  1741. if (scale > cp.rdx) bc_num_extend(&cp, scale - cp.rdx);
  1742. if (b->rdx == b->len) {
  1743. for (;;) {
  1744. if (len == 0) break;
  1745. len--;
  1746. if (b->num[len] != 0)
  1747. break;
  1748. }
  1749. len++;
  1750. }
  1751. if (cp.cap == cp.len) bc_num_expand(&cp, cp.len + 1);
  1752. // We want an extra zero in front to make things simpler.
  1753. cp.num[cp.len++] = 0;
  1754. end = cp.len - len;
  1755. bc_num_expand(c, cp.len);
  1756. bc_num_zero(c);
  1757. memset(c->num + end, 0, (c->cap - end) * sizeof(BcDig));
  1758. c->rdx = cp.rdx;
  1759. c->len = cp.len;
  1760. s = BC_STATUS_SUCCESS;
  1761. for (i = end - 1; i < end; --i) {
  1762. BcDig *n, q;
  1763. n = cp.num + i;
  1764. for (q = 0; n[len] != 0 || bc_num_compare(n, b->num, len) >= 0; ++q)
  1765. bc_num_subArrays(n, b->num, len);
  1766. c->num[i] = q;
  1767. #if ENABLE_FEATURE_BC_INTERACTIVE
  1768. // a=2^100000
  1769. // scale=40000
  1770. // 1/a <- without check below, this will not be interruptible
  1771. if (G_interrupt) {
  1772. s = BC_STATUS_FAILURE;
  1773. break;
  1774. }
  1775. #endif
  1776. }
  1777. bc_num_retireMul(c, scale, a->neg, b->neg);
  1778. bc_num_free(&cp);
  1779. RETURN_STATUS(s);
  1780. }
  1781. #define zbc_num_d(...) (zbc_num_d(__VA_ARGS__) COMMA_SUCCESS)
  1782. static FAST_FUNC BC_STATUS zbc_num_r(BcNum *a, BcNum *b, BcNum *restrict c,
  1783. BcNum *restrict d, size_t scale, size_t ts)
  1784. {
  1785. BcStatus s;
  1786. BcNum temp;
  1787. bool neg;
  1788. if (b->len == 0)
  1789. RETURN_STATUS(bc_error("divide by zero"));
  1790. if (a->len == 0) {
  1791. bc_num_setToZero(d, ts);
  1792. RETURN_STATUS(BC_STATUS_SUCCESS);
  1793. }
  1794. bc_num_init(&temp, d->cap);
  1795. s = zbc_num_d(a, b, c, scale);
  1796. if (s) goto err;
  1797. if (scale != 0) scale = ts;
  1798. s = zbc_num_m(c, b, &temp, scale);
  1799. if (s) goto err;
  1800. s = zbc_num_sub(a, &temp, d, scale);
  1801. if (s) goto err;
  1802. if (ts > d->rdx && d->len) bc_num_extend(d, ts - d->rdx);
  1803. neg = d->neg;
  1804. bc_num_retireMul(d, ts, a->neg, b->neg);
  1805. d->neg = neg;
  1806. err:
  1807. bc_num_free(&temp);
  1808. RETURN_STATUS(s);
  1809. }
  1810. #define zbc_num_r(...) (zbc_num_r(__VA_ARGS__) COMMA_SUCCESS)
  1811. static FAST_FUNC BC_STATUS zbc_num_rem(BcNum *a, BcNum *b, BcNum *restrict c, size_t scale)
  1812. {
  1813. BcStatus s;
  1814. BcNum c1;
  1815. size_t ts = BC_MAX(scale + b->rdx, a->rdx), len = BC_NUM_MREQ(a, b, ts);
  1816. bc_num_init(&c1, len);
  1817. s = zbc_num_r(a, b, &c1, c, scale, ts);
  1818. bc_num_free(&c1);
  1819. RETURN_STATUS(s);
  1820. }
  1821. #define zbc_num_rem(...) (zbc_num_rem(__VA_ARGS__) COMMA_SUCCESS)
  1822. static FAST_FUNC BC_STATUS zbc_num_p(BcNum *a, BcNum *b, BcNum *restrict c, size_t scale)
  1823. {
  1824. BcStatus s = BC_STATUS_SUCCESS;
  1825. BcNum copy;
  1826. unsigned long pow;
  1827. size_t i, powrdx, resrdx;
  1828. bool neg;
  1829. // GNU bc does not allow 2^2.0 - we do
  1830. for (i = 0; i < b->rdx; i++)
  1831. if (b->num[i] != 0)
  1832. RETURN_STATUS(bc_error("not an integer"));
  1833. if (b->len == 0) {
  1834. bc_num_one(c);
  1835. RETURN_STATUS(BC_STATUS_SUCCESS);
  1836. }
  1837. if (a->len == 0) {
  1838. bc_num_setToZero(c, scale);
  1839. RETURN_STATUS(BC_STATUS_SUCCESS);
  1840. }
  1841. if (BC_NUM_ONE(b)) {
  1842. if (!b->neg)
  1843. bc_num_copy(c, a);
  1844. else
  1845. s = zbc_num_inv(a, c, scale);
  1846. RETURN_STATUS(s);
  1847. }
  1848. neg = b->neg;
  1849. s = zbc_num_ulong_abs(b, &pow);
  1850. if (s) RETURN_STATUS(s);
  1851. // b is not used beyond this point
  1852. bc_num_init(&copy, a->len);
  1853. bc_num_copy(&copy, a);
  1854. if (!neg) {
  1855. if (a->rdx > scale)
  1856. scale = a->rdx;
  1857. if (a->rdx * pow < scale)
  1858. scale = a->rdx * pow;
  1859. }
  1860. for (powrdx = a->rdx; !(pow & 1); pow >>= 1) {
  1861. powrdx <<= 1;
  1862. s = zbc_num_mul(&copy, &copy, &copy, powrdx);
  1863. if (s) goto err;
  1864. // Not needed: zbc_num_mul() has a check for ^C:
  1865. //if (G_interrupt) {
  1866. // s = BC_STATUS_FAILURE;
  1867. // goto err;
  1868. //}
  1869. }
  1870. bc_num_copy(c, &copy);
  1871. for (resrdx = powrdx, pow >>= 1; pow != 0; pow >>= 1) {
  1872. powrdx <<= 1;
  1873. s = zbc_num_mul(&copy, &copy, &copy, powrdx);
  1874. if (s) goto err;
  1875. if (pow & 1) {
  1876. resrdx += powrdx;
  1877. s = zbc_num_mul(c, &copy, c, resrdx);
  1878. if (s) goto err;
  1879. }
  1880. // Not needed: zbc_num_mul() has a check for ^C:
  1881. //if (G_interrupt) {
  1882. // s = BC_STATUS_FAILURE;
  1883. // goto err;
  1884. //}
  1885. }
  1886. if (neg) {
  1887. s = zbc_num_inv(c, c, scale);
  1888. if (s) goto err;
  1889. }
  1890. if (c->rdx > scale) bc_num_truncate(c, c->rdx - scale);
  1891. // We can't use bc_num_clean() here.
  1892. for (i = 0; i < c->len; ++i)
  1893. if (c->num[i] != 0)
  1894. goto skip;
  1895. bc_num_setToZero(c, scale);
  1896. skip:
  1897. err:
  1898. bc_num_free(&copy);
  1899. RETURN_STATUS(s);
  1900. }
  1901. #define zbc_num_p(...) (zbc_num_p(__VA_ARGS__) COMMA_SUCCESS)
  1902. static BC_STATUS zbc_num_sqrt(BcNum *a, BcNum *restrict b, size_t scale)
  1903. {
  1904. BcStatus s;
  1905. BcNum num1, num2, half, f, fprime, *x0, *x1, *temp;
  1906. BcDig half_digs[1];
  1907. size_t pow, len, digs, digs1, resrdx, req, times = 0;
  1908. ssize_t cmp = 1, cmp1 = SSIZE_MAX, cmp2 = SSIZE_MAX;
  1909. req = BC_MAX(scale, a->rdx) + ((BC_NUM_INT(a) + 1) >> 1) + 1;
  1910. bc_num_expand(b, req);
  1911. if (a->len == 0) {
  1912. bc_num_setToZero(b, scale);
  1913. RETURN_STATUS(BC_STATUS_SUCCESS);
  1914. }
  1915. if (a->neg) {
  1916. RETURN_STATUS(bc_error("negative number"));
  1917. }
  1918. if (BC_NUM_ONE(a)) {
  1919. bc_num_one(b);
  1920. bc_num_extend(b, scale);
  1921. RETURN_STATUS(BC_STATUS_SUCCESS);
  1922. }
  1923. scale = BC_MAX(scale, a->rdx) + 1;
  1924. len = a->len + scale;
  1925. bc_num_init(&num1, len);
  1926. bc_num_init(&num2, len);
  1927. half.cap = ARRAY_SIZE(half_digs);
  1928. half.num = half_digs;
  1929. bc_num_one(&half);
  1930. half_digs[0] = 5;
  1931. half.rdx = 1;
  1932. bc_num_init(&f, len);
  1933. bc_num_init(&fprime, len);
  1934. x0 = &num1;
  1935. x1 = &num2;
  1936. bc_num_one(x0);
  1937. pow = BC_NUM_INT(a);
  1938. if (pow) {
  1939. if (pow & 1)
  1940. x0->num[0] = 2;
  1941. else
  1942. x0->num[0] = 6;
  1943. pow -= 2 - (pow & 1);
  1944. bc_num_extend(x0, pow);
  1945. // Make sure to move the radix back.
  1946. x0->rdx -= pow;
  1947. }
  1948. x0->rdx = digs = digs1 = 0;
  1949. resrdx = scale + 2;
  1950. len = BC_NUM_INT(x0) + resrdx - 1;
  1951. while (cmp != 0 || digs < len) {
  1952. s = zbc_num_div(a, x0, &f, resrdx);
  1953. if (s) goto err;
  1954. s = zbc_num_add(x0, &f, &fprime, resrdx);
  1955. if (s) goto err;
  1956. s = zbc_num_mul(&fprime, &half, x1, resrdx);
  1957. if (s) goto err;
  1958. cmp = bc_num_cmp(x1, x0);
  1959. digs = x1->len - (unsigned long long) llabs(cmp);
  1960. if (cmp == cmp2 && digs == digs1)
  1961. times += 1;
  1962. else
  1963. times = 0;
  1964. resrdx += times > 4;
  1965. cmp2 = cmp1;
  1966. cmp1 = cmp;
  1967. digs1 = digs;
  1968. temp = x0;
  1969. x0 = x1;
  1970. x1 = temp;
  1971. }
  1972. bc_num_copy(b, x0);
  1973. scale -= 1;
  1974. if (b->rdx > scale) bc_num_truncate(b, b->rdx - scale);
  1975. err:
  1976. bc_num_free(&fprime);
  1977. bc_num_free(&f);
  1978. bc_num_free(&num2);
  1979. bc_num_free(&num1);
  1980. RETURN_STATUS(s);
  1981. }
  1982. #define zbc_num_sqrt(...) (zbc_num_sqrt(__VA_ARGS__) COMMA_SUCCESS)
  1983. static BC_STATUS zbc_num_divmod(BcNum *a, BcNum *b, BcNum *c, BcNum *d,
  1984. size_t scale)
  1985. {
  1986. BcStatus s;
  1987. BcNum num2, *ptr_a;
  1988. bool init = false;
  1989. size_t ts = BC_MAX(scale + b->rdx, a->rdx), len = BC_NUM_MREQ(a, b, ts);
  1990. if (c == a) {
  1991. memcpy(&num2, c, sizeof(BcNum));
  1992. ptr_a = &num2;
  1993. bc_num_init(c, len);
  1994. init = true;
  1995. } else {
  1996. ptr_a = a;
  1997. bc_num_expand(c, len);
  1998. }
  1999. s = zbc_num_r(ptr_a, b, c, d, scale, ts);
  2000. if (init) bc_num_free(&num2);
  2001. RETURN_STATUS(s);
  2002. }
  2003. #define zbc_num_divmod(...) (zbc_num_divmod(__VA_ARGS__) COMMA_SUCCESS)
  2004. #if ENABLE_DC
  2005. static BC_STATUS zdc_num_modexp(BcNum *a, BcNum *b, BcNum *c, BcNum *restrict d)
  2006. {
  2007. BcStatus s;
  2008. BcNum base, exp, two, temp;
  2009. BcDig two_digs[1];
  2010. if (c->len == 0)
  2011. RETURN_STATUS(bc_error("divide by zero"));
  2012. if (a->rdx || b->rdx || c->rdx)
  2013. RETURN_STATUS(bc_error("not an integer"));
  2014. if (b->neg)
  2015. RETURN_STATUS(bc_error("negative number"));
  2016. bc_num_expand(d, c->len);
  2017. bc_num_init(&base, c->len);
  2018. bc_num_init(&exp, b->len);
  2019. bc_num_init(&temp, b->len);
  2020. two.cap = ARRAY_SIZE(two_digs);
  2021. two.num = two_digs;
  2022. bc_num_one(&two);
  2023. two_digs[0] = 2;
  2024. bc_num_one(d);
  2025. s = zbc_num_rem(a, c, &base, 0);
  2026. if (s) goto err;
  2027. bc_num_copy(&exp, b);
  2028. while (exp.len != 0) {
  2029. s = zbc_num_divmod(&exp, &two, &exp, &temp, 0);
  2030. if (s) goto err;
  2031. if (BC_NUM_ONE(&temp)) {
  2032. s = zbc_num_mul(d, &base, &temp, 0);
  2033. if (s) goto err;
  2034. s = zbc_num_rem(&temp, c, d, 0);
  2035. if (s) goto err;
  2036. }
  2037. s = zbc_num_mul(&base, &base, &temp, 0);
  2038. if (s) goto err;
  2039. s = zbc_num_rem(&temp, c, &base, 0);
  2040. if (s) goto err;
  2041. }
  2042. err:
  2043. bc_num_free(&temp);
  2044. bc_num_free(&exp);
  2045. bc_num_free(&base);
  2046. RETURN_STATUS(s);
  2047. }
  2048. #define zdc_num_modexp(...) (zdc_num_modexp(__VA_ARGS__) COMMA_SUCCESS)
  2049. #endif // ENABLE_DC
  2050. static FAST_FUNC void bc_string_free(void *string)
  2051. {
  2052. free(*(char**)string);
  2053. }
  2054. static void bc_func_init(BcFunc *f)
  2055. {
  2056. bc_char_vec_init(&f->code);
  2057. IF_BC(bc_vec_init(&f->labels, sizeof(size_t), NULL);)
  2058. IF_BC(bc_vec_init(&f->autos, sizeof(BcId), bc_id_free);)
  2059. IF_BC(bc_vec_init(&f->strs, sizeof(char *), bc_string_free);)
  2060. IF_BC(bc_vec_init(&f->consts, sizeof(char *), bc_string_free);)
  2061. IF_BC(f->nparams = 0;)
  2062. }
  2063. static FAST_FUNC void bc_func_free(void *func)
  2064. {
  2065. BcFunc *f = (BcFunc *) func;
  2066. bc_vec_free(&f->code);
  2067. IF_BC(bc_vec_free(&f->labels);)
  2068. IF_BC(bc_vec_free(&f->autos);)
  2069. IF_BC(bc_vec_free(&f->strs);)
  2070. IF_BC(bc_vec_free(&f->consts);)
  2071. }
  2072. static void bc_array_expand(BcVec *a, size_t len);
  2073. static void bc_array_init(BcVec *a, bool nums)
  2074. {
  2075. if (nums)
  2076. bc_vec_init(a, sizeof(BcNum), bc_num_free);
  2077. else
  2078. bc_vec_init(a, sizeof(BcVec), bc_vec_free);
  2079. bc_array_expand(a, 1);
  2080. }
  2081. static void bc_array_expand(BcVec *a, size_t len)
  2082. {
  2083. if (a->dtor == bc_num_free
  2084. // && a->size == sizeof(BcNum) - always true
  2085. ) {
  2086. BcNum n;
  2087. while (len > a->len) {
  2088. bc_num_init_DEF_SIZE(&n);
  2089. bc_vec_push(a, &n);
  2090. }
  2091. } else {
  2092. BcVec v;
  2093. while (len > a->len) {
  2094. bc_array_init(&v, true);
  2095. bc_vec_push(a, &v);
  2096. }
  2097. }
  2098. }
  2099. static void bc_array_copy(BcVec *d, const BcVec *s)
  2100. {
  2101. BcNum *dnum, *snum;
  2102. size_t i;
  2103. bc_vec_pop_all(d);
  2104. bc_vec_expand(d, s->cap);
  2105. d->len = s->len;
  2106. dnum = (void*)d->v;
  2107. snum = (void*)s->v;
  2108. for (i = 0; i < s->len; i++, dnum++, snum++) {
  2109. bc_num_init(dnum, snum->len);
  2110. bc_num_copy(dnum, snum);
  2111. }
  2112. }
  2113. #if ENABLE_DC
  2114. static void dc_result_copy(BcResult *d, BcResult *src)
  2115. {
  2116. d->t = src->t;
  2117. switch (d->t) {
  2118. case XC_RESULT_TEMP:
  2119. case XC_RESULT_IBASE:
  2120. case XC_RESULT_SCALE:
  2121. case XC_RESULT_OBASE:
  2122. bc_num_init(&d->d.n, src->d.n.len);
  2123. bc_num_copy(&d->d.n, &src->d.n);
  2124. break;
  2125. case XC_RESULT_VAR:
  2126. case XC_RESULT_ARRAY:
  2127. case XC_RESULT_ARRAY_ELEM:
  2128. d->d.id.name = xstrdup(src->d.id.name);
  2129. break;
  2130. case XC_RESULT_CONSTANT:
  2131. case XC_RESULT_STR:
  2132. memcpy(&d->d.n, &src->d.n, sizeof(BcNum));
  2133. break;
  2134. default: // placate compiler
  2135. // BC_RESULT_VOID, BC_RESULT_LAST, BC_RESULT_ONE - do not happen
  2136. break;
  2137. }
  2138. }
  2139. #endif // ENABLE_DC
  2140. static FAST_FUNC void bc_result_free(void *result)
  2141. {
  2142. BcResult *r = (BcResult *) result;
  2143. switch (r->t) {
  2144. case XC_RESULT_TEMP:
  2145. IF_BC(case BC_RESULT_VOID:)
  2146. case XC_RESULT_IBASE:
  2147. case XC_RESULT_SCALE:
  2148. case XC_RESULT_OBASE:
  2149. bc_num_free(&r->d.n);
  2150. break;
  2151. case XC_RESULT_VAR:
  2152. case XC_RESULT_ARRAY:
  2153. case XC_RESULT_ARRAY_ELEM:
  2154. free(r->d.id.name);
  2155. break;
  2156. default:
  2157. // Do nothing.
  2158. break;
  2159. }
  2160. }
  2161. static int bad_input_byte(char c)
  2162. {
  2163. if ((c < ' ' && c != '\t' && c != '\r' && c != '\n') // also allow '\v' '\f'?
  2164. || c > 0x7e
  2165. ) {
  2166. bc_error_fmt("illegal character 0x%02x", c);
  2167. return 1;
  2168. }
  2169. return 0;
  2170. }
  2171. static void xc_read_line(BcVec *vec, FILE *fp)
  2172. {
  2173. again:
  2174. bc_vec_pop_all(vec);
  2175. fflush_and_check();
  2176. #if ENABLE_FEATURE_BC_INTERACTIVE
  2177. if (G_interrupt) { // ^C was pressed
  2178. # if ENABLE_FEATURE_EDITING
  2179. intr:
  2180. # endif
  2181. if (fp != stdin) {
  2182. // ^C while running a script (bc SCRIPT): die.
  2183. // We do not return to interactive prompt:
  2184. // user might be running us from a shell,
  2185. // and SCRIPT might be intended to terminate
  2186. // (e.g. contain a "halt" stmt).
  2187. // ^C dropping user into a bc prompt instead of
  2188. // the shell would be unexpected.
  2189. xfunc_die();
  2190. }
  2191. // ^C while interactive input
  2192. G_interrupt = 0;
  2193. // GNU bc says "interrupted execution."
  2194. // GNU dc says "Interrupt!"
  2195. fputs("\ninterrupted execution\n", stderr);
  2196. }
  2197. # if ENABLE_FEATURE_EDITING
  2198. if (G_ttyin && fp == stdin) {
  2199. int n, i;
  2200. # define line_buf bb_common_bufsiz1
  2201. n = read_line_input(G.line_input_state, "", line_buf, COMMON_BUFSIZE);
  2202. if (n <= 0) { // read errors or EOF, or ^D, or ^C
  2203. if (n == 0) // ^C
  2204. goto intr;
  2205. bc_vec_pushZeroByte(vec); // ^D or EOF (or error)
  2206. return;
  2207. }
  2208. i = 0;
  2209. for (;;) {
  2210. char c = line_buf[i++];
  2211. if (c == '\0') break;
  2212. if (bad_input_byte(c)) goto again;
  2213. }
  2214. bc_vec_string(vec, n, line_buf);
  2215. # undef line_buf
  2216. } else
  2217. # endif
  2218. #endif
  2219. {
  2220. int c;
  2221. bool bad_chars = 0;
  2222. do {
  2223. get_char:
  2224. #if ENABLE_FEATURE_BC_INTERACTIVE
  2225. if (G_interrupt) {
  2226. // ^C was pressed: ignore entire line, get another one
  2227. goto again;
  2228. }
  2229. #endif
  2230. c = fgetc(fp);
  2231. if (c == '\0')
  2232. goto get_char;
  2233. if (c == EOF) {
  2234. if (ferror(fp))
  2235. bb_simple_perror_msg_and_die("input error");
  2236. // Note: EOF does not append '\n'
  2237. break;
  2238. }
  2239. bad_chars |= bad_input_byte(c);
  2240. bc_vec_pushByte(vec, (char)c);
  2241. } while (c != '\n');
  2242. if (bad_chars) {
  2243. // Bad chars on this line
  2244. if (!G.prs.lex_filename) { // stdin
  2245. // ignore entire line, get another one
  2246. goto again;
  2247. }
  2248. bb_perror_msg_and_die("file '%s' is not text", G.prs.lex_filename);
  2249. }
  2250. bc_vec_pushZeroByte(vec);
  2251. }
  2252. }
  2253. //
  2254. // Parsing routines
  2255. //
  2256. // "Input numbers may contain the characters 0-9 and A-Z.
  2257. // (Note: They must be capitals. Lower case letters are variable names.)
  2258. // Single digit numbers always have the value of the digit regardless of
  2259. // the value of ibase. (i.e. A = 10.) For multi-digit numbers, bc changes
  2260. // all input digits greater or equal to ibase to the value of ibase-1.
  2261. // This makes the number ZZZ always be the largest 3 digit number of the
  2262. // input base."
  2263. static bool xc_num_strValid(const char *val)
  2264. {
  2265. bool radix = false;
  2266. for (;;) {
  2267. BcDig c = *val++;
  2268. if (c == '\0')
  2269. break;
  2270. if (c == '.') {
  2271. if (radix) return false;
  2272. radix = true;
  2273. continue;
  2274. }
  2275. if ((c < '0' || c > '9') && (c < 'A' || c > 'Z'))
  2276. return false;
  2277. }
  2278. return true;
  2279. }
  2280. // Note: n is already "bc_num_zero()"ed,
  2281. // leading zeroes in "val" are removed
  2282. static void bc_num_parseDecimal(BcNum *n, const char *val)
  2283. {
  2284. size_t len, i;
  2285. const char *ptr;
  2286. len = strlen(val);
  2287. if (len == 0)
  2288. return;
  2289. bc_num_expand(n, len + 1); // +1 for e.g. "A" converting into 10
  2290. ptr = strchr(val, '.');
  2291. n->rdx = 0;
  2292. if (ptr != NULL)
  2293. n->rdx = (size_t)((val + len) - (ptr + 1));
  2294. for (i = 0; val[i]; ++i) {
  2295. if (val[i] != '0' && val[i] != '.') {
  2296. // Not entirely zero value - convert it, and exit
  2297. if (len == 1) {
  2298. unsigned c = val[0] - '0';
  2299. n->len = 1;
  2300. if (c > 9) { // A-Z => 10-36
  2301. n->len = 2;
  2302. c -= ('A' - '9' - 1);
  2303. n->num[1] = c/10;
  2304. c = c%10;
  2305. }
  2306. n->num[0] = c;
  2307. break;
  2308. }
  2309. i = len - 1;
  2310. for (;;) {
  2311. char c = val[i] - '0';
  2312. if (c > 9) // A-Z => 9
  2313. c = 9;
  2314. n->num[n->len] = c;
  2315. n->len++;
  2316. skip_dot:
  2317. if (i == 0) break;
  2318. if (val[--i] == '.') goto skip_dot;
  2319. }
  2320. break;
  2321. }
  2322. }
  2323. // if for() exits without hitting if(), the value is entirely zero
  2324. }
  2325. // Note: n is already "bc_num_zero()"ed,
  2326. // leading zeroes in "val" are removed
  2327. static void bc_num_parseBase(BcNum *n, const char *val, unsigned base_t)
  2328. {
  2329. BcStatus s;
  2330. BcNum mult, result;
  2331. BcNum temp;
  2332. BcNum base;
  2333. BcDig temp_digs[ULONG_NUM_BUFSIZE];
  2334. BcDig base_digs[ULONG_NUM_BUFSIZE];
  2335. size_t digits;
  2336. bc_num_init_DEF_SIZE(&mult);
  2337. temp.cap = ARRAY_SIZE(temp_digs);
  2338. temp.num = temp_digs;
  2339. base.cap = ARRAY_SIZE(base_digs);
  2340. base.num = base_digs;
  2341. bc_num_ulong2num(&base, base_t);
  2342. base_t--;
  2343. for (;;) {
  2344. unsigned v;
  2345. char c;
  2346. c = *val++;
  2347. if (c == '\0') goto int_err;
  2348. if (c == '.') break;
  2349. v = (unsigned)(c <= '9' ? c - '0' : c - 'A' + 10);
  2350. if (v > base_t) v = base_t;
  2351. s = zbc_num_mul(n, &base, &mult, 0);
  2352. if (s) goto int_err;
  2353. bc_num_ulong2num(&temp, v);
  2354. s = zbc_num_add(&mult, &temp, n, 0);
  2355. if (s) goto int_err;
  2356. }
  2357. bc_num_init(&result, base.len);
  2358. //bc_num_zero(&result); - already is
  2359. bc_num_one(&mult);
  2360. digits = 0;
  2361. for (;;) {
  2362. unsigned v;
  2363. char c;
  2364. c = *val++;
  2365. if (c == '\0') break;
  2366. digits++;
  2367. v = (unsigned)(c <= '9' ? c - '0' : c - 'A' + 10);
  2368. if (v > base_t) v = base_t;
  2369. s = zbc_num_mul(&result, &base, &result, 0);
  2370. if (s) goto err;
  2371. bc_num_ulong2num(&temp, v);
  2372. s = zbc_num_add(&result, &temp, &result, 0);
  2373. if (s) goto err;
  2374. s = zbc_num_mul(&mult, &base, &mult, 0);
  2375. if (s) goto err;
  2376. }
  2377. s = zbc_num_div(&result, &mult, &result, digits);
  2378. if (s) goto err;
  2379. s = zbc_num_add(n, &result, n, digits);
  2380. if (s) goto err;
  2381. if (n->len != 0) {
  2382. if (n->rdx < digits)
  2383. bc_num_extend(n, digits - n->rdx);
  2384. } else
  2385. bc_num_zero(n);
  2386. err:
  2387. bc_num_free(&result);
  2388. int_err:
  2389. bc_num_free(&mult);
  2390. }
  2391. static BC_STATUS zxc_num_parse(BcNum *n, const char *val, unsigned base_t)
  2392. {
  2393. size_t i;
  2394. if (!xc_num_strValid(val))
  2395. RETURN_STATUS(bc_error("bad number string"));
  2396. bc_num_zero(n);
  2397. while (*val == '0')
  2398. val++;
  2399. for (i = 0; ; ++i) {
  2400. if (val[i] == '\0')
  2401. RETURN_STATUS(BC_STATUS_SUCCESS);
  2402. if (val[i] != '.' && val[i] != '0')
  2403. break;
  2404. }
  2405. if (base_t == 10 || val[1] == '\0')
  2406. // Decimal, or single-digit number
  2407. bc_num_parseDecimal(n, val);
  2408. else
  2409. bc_num_parseBase(n, val, base_t);
  2410. RETURN_STATUS(BC_STATUS_SUCCESS);
  2411. }
  2412. #define zxc_num_parse(...) (zxc_num_parse(__VA_ARGS__) COMMA_SUCCESS)
  2413. // p->lex_inbuf points to the current string to be parsed.
  2414. // if p->lex_inbuf points to '\0', it's either EOF or it points after
  2415. // last processed line's terminating '\n' (and more reading needs to be done
  2416. // to get next character).
  2417. //
  2418. // If you are in a situation where that is a possibility, call peek_inbuf().
  2419. // If necessary, it performs more reading and changes p->lex_inbuf,
  2420. // then it returns *p->lex_inbuf (which will be '\0' only if it's EOF).
  2421. // After it, just referencing *p->lex_inbuf is valid, and if it wasn't '\0',
  2422. // it's ok to do p->lex_inbuf++ once without end-of-buffer checking.
  2423. //
  2424. // eat_inbuf() is equvalent to "peek_inbuf(); if (c) p->lex_inbuf++":
  2425. // it returns current char and advances the pointer (if not EOF).
  2426. // After eat_inbuf(), referencing p->lex_inbuf[-1] and *p->lex_inbuf is valid.
  2427. //
  2428. // In many cases, you can use fast *p->lex_inbuf instead of peek_inbuf():
  2429. // unless prev char might have been '\n', *p->lex_inbuf is '\0' ONLY
  2430. // on real EOF, not end-of-buffer.
  2431. //
  2432. // bc cases to test interactively:
  2433. // 1 #comment\ - prints "1<newline>" at once (comment is not continued)
  2434. // 1 #comment/* - prints "1<newline>" at once
  2435. // 1 #comment" - prints "1<newline>" at once
  2436. // 1\#comment - error at once (\ is not a line continuation)
  2437. // 1 + /*"*/2 - prints "3<newline>" at once
  2438. // 1 + /*#*/2 - prints "3<newline>" at once
  2439. // "str\" - prints "str\" at once
  2440. // "str#" - prints "str#" at once
  2441. // "str/*" - prints "str/*" at once
  2442. // "str#\ - waits for second line
  2443. // end" - ...prints "str#\<newline>end"
  2444. static char peek_inbuf(void)
  2445. {
  2446. if (*G.prs.lex_inbuf == '\0'
  2447. && G.prs.lex_input_fp
  2448. ) {
  2449. xc_read_line(&G.input_buffer, G.prs.lex_input_fp);
  2450. G.prs.lex_inbuf = G.input_buffer.v;
  2451. if (G.input_buffer.len <= 1) // on EOF, len is 1 (NUL byte)
  2452. G.prs.lex_input_fp = NULL;
  2453. }
  2454. return *G.prs.lex_inbuf;
  2455. }
  2456. static char eat_inbuf(void)
  2457. {
  2458. char c = peek_inbuf();
  2459. if (c) G.prs.lex_inbuf++;
  2460. return c;
  2461. }
  2462. static void xc_lex_lineComment(void)
  2463. {
  2464. BcParse *p = &G.prs;
  2465. char c;
  2466. // Try: echo -n '#foo' | bc
  2467. p->lex = XC_LEX_WHITESPACE;
  2468. // Not peek_inbuf(): we depend on input being done in whole lines:
  2469. // '\0' which isn't the EOF can only be seen after '\n'.
  2470. while ((c = *p->lex_inbuf) != '\n' && c != '\0')
  2471. p->lex_inbuf++;
  2472. }
  2473. static void xc_lex_whitespace(void)
  2474. {
  2475. BcParse *p = &G.prs;
  2476. p->lex = XC_LEX_WHITESPACE;
  2477. for (;;) {
  2478. // We depend here on input being done in whole lines:
  2479. // '\0' which isn't the EOF can only be seen after '\n'.
  2480. char c = *p->lex_inbuf;
  2481. if (c == '\n') // this is XC_LEX_NLINE, not XC_LEX_WHITESPACE
  2482. break;
  2483. if (!isspace(c))
  2484. break;
  2485. p->lex_inbuf++;
  2486. }
  2487. }
  2488. static BC_STATUS zxc_lex_number(char last)
  2489. {
  2490. BcParse *p = &G.prs;
  2491. bool pt;
  2492. char last_valid_ch;
  2493. bc_vec_pop_all(&p->lex_strnumbuf);
  2494. bc_vec_pushByte(&p->lex_strnumbuf, last);
  2495. // bc: "Input numbers may contain the characters 0-9 and A-Z.
  2496. // (Note: They must be capitals. Lower case letters are variable names.)
  2497. // Single digit numbers always have the value of the digit regardless of
  2498. // the value of ibase. (i.e. A = 10.) For multi-digit numbers, bc changes
  2499. // all input digits greater or equal to ibase to the value of ibase-1.
  2500. // This makes the number ZZZ always be the largest 3 digit number of the
  2501. // input base."
  2502. // dc only allows A-F, the rules about single-char and multi-char are the same.
  2503. last_valid_ch = (IS_BC ? 'Z' : 'F');
  2504. pt = (last == '.');
  2505. p->lex = XC_LEX_NUMBER;
  2506. for (;;) {
  2507. // We depend here on input being done in whole lines:
  2508. // '\0' which isn't the EOF can only be seen after '\n'.
  2509. char c = *p->lex_inbuf;
  2510. check_c:
  2511. if (c == '\0')
  2512. break;
  2513. if (c == '\\' && p->lex_inbuf[1] == '\n') {
  2514. p->lex_inbuf += 2;
  2515. p->lex_line++;
  2516. dbg_lex("++p->lex_line=%zd", p->lex_line);
  2517. c = peek_inbuf(); // force next line to be read
  2518. goto check_c;
  2519. }
  2520. if (!isdigit(c) && (c < 'A' || c > last_valid_ch)) {
  2521. if (c != '.') break;
  2522. // if '.' was already seen, stop on second one:
  2523. if (pt) break;
  2524. pt = true;
  2525. }
  2526. // c is one of "0-9A-Z."
  2527. last = c;
  2528. bc_vec_push(&p->lex_strnumbuf, p->lex_inbuf);
  2529. p->lex_inbuf++;
  2530. }
  2531. if (last == '.') // remove trailing '.' if any
  2532. bc_vec_pop(&p->lex_strnumbuf);
  2533. bc_vec_pushZeroByte(&p->lex_strnumbuf);
  2534. G.err_line = G.prs.lex_line;
  2535. RETURN_STATUS(BC_STATUS_SUCCESS);
  2536. }
  2537. #define zxc_lex_number(...) (zxc_lex_number(__VA_ARGS__) COMMA_SUCCESS)
  2538. static void xc_lex_name(void)
  2539. {
  2540. BcParse *p = &G.prs;
  2541. size_t i;
  2542. const char *buf;
  2543. p->lex = XC_LEX_NAME;
  2544. // Since names can't cross lines with \<newline>,
  2545. // we depend on the fact that whole line is in the buffer
  2546. i = 0;
  2547. buf = p->lex_inbuf - 1;
  2548. for (;;) {
  2549. char c = buf[i];
  2550. if ((c < 'a' || c > 'z') && !isdigit(c) && c != '_') break;
  2551. i++;
  2552. }
  2553. #if 0 // We do not protect against people with gigabyte-long names
  2554. // This check makes sense only if size_t is (much) larger than BC_MAX_STRING.
  2555. if (SIZE_MAX > (BC_MAX_STRING | 0xff)) {
  2556. if (i > BC_MAX_STRING)
  2557. return bc_error("name too long: must be [1,"BC_MAX_STRING_STR"]");
  2558. }
  2559. #endif
  2560. bc_vec_string(&p->lex_strnumbuf, i, buf);
  2561. // Increment the index. We minus 1 because it has already been incremented.
  2562. p->lex_inbuf += i - 1;
  2563. //return BC_STATUS_SUCCESS;
  2564. }
  2565. IF_BC(static BC_STATUS zbc_lex_token(void);)
  2566. IF_DC(static BC_STATUS zdc_lex_token(void);)
  2567. #define zbc_lex_token(...) (zbc_lex_token(__VA_ARGS__) COMMA_SUCCESS)
  2568. #define zdc_lex_token(...) (zdc_lex_token(__VA_ARGS__) COMMA_SUCCESS)
  2569. static BC_STATUS zxc_lex_next(void)
  2570. {
  2571. BcParse *p = &G.prs;
  2572. BcStatus s;
  2573. G.err_line = p->lex_line;
  2574. p->lex_last = p->lex;
  2575. //why?
  2576. // if (p->lex_last == XC_LEX_EOF)
  2577. // RETURN_STATUS(bc_error("end of file"));
  2578. // Loop until failure or we don't have whitespace. This
  2579. // is so the parser doesn't get inundated with whitespace.
  2580. // Comments are also XC_LEX_WHITESPACE tokens and eaten here.
  2581. s = BC_STATUS_SUCCESS;
  2582. do {
  2583. if (*p->lex_inbuf == '\0') {
  2584. p->lex = XC_LEX_EOF;
  2585. if (peek_inbuf() == '\0')
  2586. RETURN_STATUS(BC_STATUS_SUCCESS);
  2587. }
  2588. p->lex_next_at = p->lex_inbuf;
  2589. dbg_lex("next string to parse:'%.*s'",
  2590. (int)(strchrnul(p->lex_next_at, '\n') - p->lex_next_at),
  2591. p->lex_next_at
  2592. );
  2593. if (IS_BC) {
  2594. IF_BC(s = zbc_lex_token());
  2595. } else {
  2596. IF_DC(s = zdc_lex_token());
  2597. }
  2598. } while (!s && p->lex == XC_LEX_WHITESPACE);
  2599. dbg_lex("p->lex from string:%d", p->lex);
  2600. RETURN_STATUS(s);
  2601. }
  2602. #define zxc_lex_next(...) (zxc_lex_next(__VA_ARGS__) COMMA_SUCCESS)
  2603. #if ENABLE_BC
  2604. static BC_STATUS zbc_lex_skip_if_at_NLINE(void)
  2605. {
  2606. if (G.prs.lex == XC_LEX_NLINE)
  2607. RETURN_STATUS(zxc_lex_next());
  2608. RETURN_STATUS(BC_STATUS_SUCCESS);
  2609. }
  2610. #define zbc_lex_skip_if_at_NLINE(...) (zbc_lex_skip_if_at_NLINE(__VA_ARGS__) COMMA_SUCCESS)
  2611. static BC_STATUS zbc_lex_next_and_skip_NLINE(void)
  2612. {
  2613. BcStatus s;
  2614. s = zxc_lex_next();
  2615. if (s) RETURN_STATUS(s);
  2616. // if(cond)<newline>stmt is accepted too (but not 2+ newlines)
  2617. s = zbc_lex_skip_if_at_NLINE();
  2618. RETURN_STATUS(s);
  2619. }
  2620. #define zbc_lex_next_and_skip_NLINE(...) (zbc_lex_next_and_skip_NLINE(__VA_ARGS__) COMMA_SUCCESS)
  2621. static BC_STATUS zbc_lex_identifier(void)
  2622. {
  2623. BcParse *p = &G.prs;
  2624. BcStatus s;
  2625. unsigned i;
  2626. const char *buf = p->lex_inbuf - 1;
  2627. for (i = 0; i < ARRAY_SIZE(bc_lex_kws); ++i) {
  2628. const char *keyword8 = bc_lex_kws[i].name8;
  2629. unsigned j = 0;
  2630. while (buf[j] != '\0' && buf[j] == keyword8[j]) {
  2631. j++;
  2632. if (j == 8) goto match;
  2633. }
  2634. if (keyword8[j] != '\0')
  2635. continue;
  2636. match:
  2637. // buf starts with keyword bc_lex_kws[i]
  2638. if (isalnum(buf[j]) || buf[j]=='_')
  2639. continue; // "ifz" does not match "if" keyword, "if." does
  2640. p->lex = BC_LEX_KEY_1st_keyword + i;
  2641. if (!keyword_is_POSIX(i)) {
  2642. s = zbc_posix_error_fmt("%sthe '%.8s' keyword", "POSIX does not allow ", bc_lex_kws[i].name8);
  2643. if (s) RETURN_STATUS(s);
  2644. }
  2645. // We minus 1 because the index has already been incremented.
  2646. p->lex_inbuf += j - 1;
  2647. RETURN_STATUS(BC_STATUS_SUCCESS);
  2648. }
  2649. xc_lex_name();
  2650. s = BC_STATUS_SUCCESS;
  2651. if (p->lex_strnumbuf.len > 2) {
  2652. // Prevent this:
  2653. // >>> qwe=1
  2654. // bc: POSIX only allows one character names; this is bad: 'qwe=1
  2655. // '
  2656. unsigned len = strchrnul(buf, '\n') - buf;
  2657. s = zbc_posix_error_fmt("POSIX only allows one character names; this is bad: '%.*s'", len, buf);
  2658. }
  2659. RETURN_STATUS(s);
  2660. }
  2661. #define zbc_lex_identifier(...) (zbc_lex_identifier(__VA_ARGS__) COMMA_SUCCESS)
  2662. static BC_STATUS zbc_lex_string(void)
  2663. {
  2664. BcParse *p = &G.prs;
  2665. p->lex = XC_LEX_STR;
  2666. bc_vec_pop_all(&p->lex_strnumbuf);
  2667. for (;;) {
  2668. char c = peek_inbuf(); // strings can cross lines
  2669. if (c == '\0') {
  2670. RETURN_STATUS(bc_error("unterminated string"));
  2671. }
  2672. if (c == '"')
  2673. break;
  2674. if (c == '\n') {
  2675. p->lex_line++;
  2676. dbg_lex("++p->lex_line=%zd", p->lex_line);
  2677. }
  2678. bc_vec_push(&p->lex_strnumbuf, p->lex_inbuf);
  2679. p->lex_inbuf++;
  2680. }
  2681. bc_vec_pushZeroByte(&p->lex_strnumbuf);
  2682. p->lex_inbuf++;
  2683. G.err_line = p->lex_line;
  2684. RETURN_STATUS(BC_STATUS_SUCCESS);
  2685. }
  2686. #define zbc_lex_string(...) (zbc_lex_string(__VA_ARGS__) COMMA_SUCCESS)
  2687. static void parse_lex_by_checking_eq_sign(unsigned with_and_without)
  2688. {
  2689. BcParse *p = &G.prs;
  2690. if (*p->lex_inbuf == '=') {
  2691. // ^^^ not using peek_inbuf() since '==' etc can't be split across lines
  2692. p->lex_inbuf++;
  2693. with_and_without >>= 8; // store "with" value
  2694. } // else store "without" value
  2695. p->lex = (with_and_without & 0xff);
  2696. }
  2697. #define parse_lex_by_checking_eq_sign(with, without) \
  2698. parse_lex_by_checking_eq_sign(((with)<<8)|(without))
  2699. static BC_STATUS zbc_lex_comment(void)
  2700. {
  2701. BcParse *p = &G.prs;
  2702. p->lex = XC_LEX_WHITESPACE;
  2703. // here lex_inbuf is at '*' of opening comment delimiter
  2704. for (;;) {
  2705. char c;
  2706. p->lex_inbuf++;
  2707. c = peek_inbuf();
  2708. check_star:
  2709. if (c == '*') {
  2710. p->lex_inbuf++;
  2711. c = *p->lex_inbuf; // no need to peek_inbuf()
  2712. if (c == '/')
  2713. break;
  2714. goto check_star;
  2715. }
  2716. if (c == '\0') {
  2717. RETURN_STATUS(bc_error("unterminated comment"));
  2718. }
  2719. if (c == '\n') {
  2720. p->lex_line++;
  2721. dbg_lex("++p->lex_line=%zd", p->lex_line);
  2722. }
  2723. }
  2724. p->lex_inbuf++; // skip trailing '/'
  2725. G.err_line = p->lex_line;
  2726. RETURN_STATUS(BC_STATUS_SUCCESS);
  2727. }
  2728. #define zbc_lex_comment(...) (zbc_lex_comment(__VA_ARGS__) COMMA_SUCCESS)
  2729. #undef zbc_lex_token
  2730. static BC_STATUS zbc_lex_token(void)
  2731. {
  2732. BcParse *p = &G.prs;
  2733. BcStatus s = BC_STATUS_SUCCESS;
  2734. char c = eat_inbuf();
  2735. char c2;
  2736. // This is the workhorse of the lexer.
  2737. switch (c) {
  2738. // case '\0': // probably never reached
  2739. // p->lex_inbuf--;
  2740. // p->lex = XC_LEX_EOF;
  2741. // break;
  2742. case '\n':
  2743. p->lex_line++;
  2744. dbg_lex("++p->lex_line=%zd", p->lex_line);
  2745. p->lex = XC_LEX_NLINE;
  2746. break;
  2747. case '\t':
  2748. case '\v':
  2749. case '\f':
  2750. case '\r':
  2751. case ' ':
  2752. xc_lex_whitespace();
  2753. break;
  2754. case '!':
  2755. parse_lex_by_checking_eq_sign(XC_LEX_OP_REL_NE, BC_LEX_OP_BOOL_NOT);
  2756. if (p->lex == BC_LEX_OP_BOOL_NOT) {
  2757. s = zbc_POSIX_does_not_allow_bool_ops_this_is_bad("!");
  2758. if (s) RETURN_STATUS(s);
  2759. }
  2760. break;
  2761. case '"':
  2762. s = zbc_lex_string();
  2763. break;
  2764. case '#':
  2765. s = zbc_POSIX_does_not_allow("'#' script comments");
  2766. if (s) RETURN_STATUS(s);
  2767. xc_lex_lineComment();
  2768. break;
  2769. case '%':
  2770. parse_lex_by_checking_eq_sign(BC_LEX_OP_ASSIGN_MODULUS, XC_LEX_OP_MODULUS);
  2771. break;
  2772. case '&':
  2773. c2 = *p->lex_inbuf;
  2774. if (c2 == '&') {
  2775. s = zbc_POSIX_does_not_allow_bool_ops_this_is_bad("&&");
  2776. if (s) RETURN_STATUS(s);
  2777. p->lex_inbuf++;
  2778. p->lex = BC_LEX_OP_BOOL_AND;
  2779. } else {
  2780. p->lex = XC_LEX_INVALID;
  2781. s = bc_error_bad_character('&');
  2782. }
  2783. break;
  2784. case '(':
  2785. case ')':
  2786. p->lex = (BcLexType)(c - '(' + BC_LEX_LPAREN);
  2787. break;
  2788. case '*':
  2789. parse_lex_by_checking_eq_sign(BC_LEX_OP_ASSIGN_MULTIPLY, XC_LEX_OP_MULTIPLY);
  2790. break;
  2791. case '+':
  2792. c2 = *p->lex_inbuf;
  2793. if (c2 == '+') {
  2794. p->lex_inbuf++;
  2795. p->lex = BC_LEX_OP_INC;
  2796. } else
  2797. parse_lex_by_checking_eq_sign(BC_LEX_OP_ASSIGN_PLUS, XC_LEX_OP_PLUS);
  2798. break;
  2799. case ',':
  2800. p->lex = BC_LEX_COMMA;
  2801. break;
  2802. case '-':
  2803. c2 = *p->lex_inbuf;
  2804. if (c2 == '-') {
  2805. p->lex_inbuf++;
  2806. p->lex = BC_LEX_OP_DEC;
  2807. } else
  2808. parse_lex_by_checking_eq_sign(BC_LEX_OP_ASSIGN_MINUS, XC_LEX_OP_MINUS);
  2809. break;
  2810. case '.':
  2811. if (isdigit(*p->lex_inbuf))
  2812. s = zxc_lex_number(c);
  2813. else {
  2814. p->lex = BC_LEX_KEY_LAST;
  2815. s = zbc_POSIX_does_not_allow("'.' as 'last'");
  2816. }
  2817. break;
  2818. case '/':
  2819. c2 = *p->lex_inbuf;
  2820. if (c2 == '*')
  2821. s = zbc_lex_comment();
  2822. else
  2823. parse_lex_by_checking_eq_sign(BC_LEX_OP_ASSIGN_DIVIDE, XC_LEX_OP_DIVIDE);
  2824. break;
  2825. case '0':
  2826. case '1':
  2827. case '2':
  2828. case '3':
  2829. case '4':
  2830. case '5':
  2831. case '6':
  2832. case '7':
  2833. case '8':
  2834. case '9':
  2835. case 'A':
  2836. case 'B':
  2837. case 'C':
  2838. case 'D':
  2839. case 'E':
  2840. case 'F':
  2841. case 'G':
  2842. case 'H':
  2843. case 'I':
  2844. case 'J':
  2845. case 'K':
  2846. case 'L':
  2847. case 'M':
  2848. case 'N':
  2849. case 'O':
  2850. case 'P':
  2851. case 'Q':
  2852. case 'R':
  2853. case 'S':
  2854. case 'T':
  2855. case 'U':
  2856. case 'V':
  2857. case 'W':
  2858. case 'X':
  2859. case 'Y':
  2860. case 'Z':
  2861. s = zxc_lex_number(c);
  2862. break;
  2863. case ';':
  2864. p->lex = BC_LEX_SCOLON;
  2865. break;
  2866. case '<':
  2867. parse_lex_by_checking_eq_sign(XC_LEX_OP_REL_LE, XC_LEX_OP_REL_LT);
  2868. break;
  2869. case '=':
  2870. parse_lex_by_checking_eq_sign(XC_LEX_OP_REL_EQ, BC_LEX_OP_ASSIGN);
  2871. break;
  2872. case '>':
  2873. parse_lex_by_checking_eq_sign(XC_LEX_OP_REL_GE, XC_LEX_OP_REL_GT);
  2874. break;
  2875. case '[':
  2876. case ']':
  2877. p->lex = (BcLexType)(c - '[' + BC_LEX_LBRACKET);
  2878. break;
  2879. case '\\':
  2880. if (*p->lex_inbuf == '\n') {
  2881. p->lex = XC_LEX_WHITESPACE;
  2882. p->lex_inbuf++;
  2883. } else
  2884. s = bc_error_bad_character(c);
  2885. break;
  2886. case '^':
  2887. parse_lex_by_checking_eq_sign(BC_LEX_OP_ASSIGN_POWER, XC_LEX_OP_POWER);
  2888. break;
  2889. case 'a':
  2890. case 'b':
  2891. case 'c':
  2892. case 'd':
  2893. case 'e':
  2894. case 'f':
  2895. case 'g':
  2896. case 'h':
  2897. case 'i':
  2898. case 'j':
  2899. case 'k':
  2900. case 'l':
  2901. case 'm':
  2902. case 'n':
  2903. case 'o':
  2904. case 'p':
  2905. case 'q':
  2906. case 'r':
  2907. case 's':
  2908. case 't':
  2909. case 'u':
  2910. case 'v':
  2911. case 'w':
  2912. case 'x':
  2913. case 'y':
  2914. case 'z':
  2915. s = zbc_lex_identifier();
  2916. break;
  2917. case '{':
  2918. case '}':
  2919. p->lex = (BcLexType)(c - '{' + BC_LEX_LBRACE);
  2920. break;
  2921. case '|':
  2922. c2 = *p->lex_inbuf;
  2923. if (c2 == '|') {
  2924. s = zbc_POSIX_does_not_allow_bool_ops_this_is_bad("||");
  2925. if (s) RETURN_STATUS(s);
  2926. p->lex_inbuf++;
  2927. p->lex = BC_LEX_OP_BOOL_OR;
  2928. } else {
  2929. p->lex = XC_LEX_INVALID;
  2930. s = bc_error_bad_character(c);
  2931. }
  2932. break;
  2933. default:
  2934. p->lex = XC_LEX_INVALID;
  2935. s = bc_error_bad_character(c);
  2936. break;
  2937. }
  2938. RETURN_STATUS(s);
  2939. }
  2940. #define zbc_lex_token(...) (zbc_lex_token(__VA_ARGS__) COMMA_SUCCESS)
  2941. #endif // ENABLE_BC
  2942. #if ENABLE_DC
  2943. static BC_STATUS zdc_lex_register(void)
  2944. {
  2945. BcParse *p = &G.prs;
  2946. if (G_exreg && isspace(*p->lex_inbuf)) {
  2947. xc_lex_whitespace(); // eats whitespace (but not newline)
  2948. p->lex_inbuf++; // xc_lex_name() expects this
  2949. xc_lex_name();
  2950. } else {
  2951. bc_vec_pop_all(&p->lex_strnumbuf);
  2952. bc_vec_push(&p->lex_strnumbuf, p->lex_inbuf++);
  2953. bc_vec_pushZeroByte(&p->lex_strnumbuf);
  2954. p->lex = XC_LEX_NAME;
  2955. }
  2956. RETURN_STATUS(BC_STATUS_SUCCESS);
  2957. }
  2958. #define zdc_lex_register(...) (zdc_lex_register(__VA_ARGS__) COMMA_SUCCESS)
  2959. static BC_STATUS zdc_lex_string(void)
  2960. {
  2961. BcParse *p = &G.prs;
  2962. size_t depth;
  2963. p->lex = XC_LEX_STR;
  2964. bc_vec_pop_all(&p->lex_strnumbuf);
  2965. depth = 1;
  2966. for (;;) {
  2967. char c = peek_inbuf();
  2968. if (c == '\0') {
  2969. RETURN_STATUS(bc_error("unterminated string"));
  2970. }
  2971. if (c == '[') depth++;
  2972. if (c == ']')
  2973. if (--depth == 0)
  2974. break;
  2975. if (c == '\n') {
  2976. p->lex_line++;
  2977. dbg_lex("++p->lex_line=%zd", p->lex_line);
  2978. }
  2979. bc_vec_push(&p->lex_strnumbuf, p->lex_inbuf);
  2980. p->lex_inbuf++;
  2981. }
  2982. bc_vec_pushZeroByte(&p->lex_strnumbuf);
  2983. p->lex_inbuf++; // skip trailing ']'
  2984. G.err_line = p->lex_line;
  2985. RETURN_STATUS(BC_STATUS_SUCCESS);
  2986. }
  2987. #define zdc_lex_string(...) (zdc_lex_string(__VA_ARGS__) COMMA_SUCCESS)
  2988. #undef zdc_lex_token
  2989. static BC_STATUS zdc_lex_token(void)
  2990. {
  2991. static const //BcLexType - should be this type, but narrower type saves size:
  2992. uint8_t
  2993. dc_lex_regs[] ALIGN1 = {
  2994. XC_LEX_OP_REL_EQ, XC_LEX_OP_REL_LE, XC_LEX_OP_REL_GE, XC_LEX_OP_REL_NE,
  2995. XC_LEX_OP_REL_LT, XC_LEX_OP_REL_GT, DC_LEX_SCOLON, DC_LEX_COLON,
  2996. DC_LEX_ELSE, DC_LEX_LOAD, DC_LEX_LOAD_POP, DC_LEX_OP_ASSIGN,
  2997. DC_LEX_STORE_PUSH,
  2998. };
  2999. BcParse *p = &G.prs;
  3000. BcStatus s;
  3001. char c, c2;
  3002. size_t i;
  3003. for (i = 0; i < ARRAY_SIZE(dc_lex_regs); ++i) {
  3004. if (p->lex_last == dc_lex_regs[i])
  3005. RETURN_STATUS(zdc_lex_register());
  3006. }
  3007. s = BC_STATUS_SUCCESS;
  3008. c = eat_inbuf();
  3009. if (c >= '%' && c <= '~'
  3010. && (p->lex = dc_char_to_LEX[c - '%']) != XC_LEX_INVALID
  3011. ) {
  3012. RETURN_STATUS(s);
  3013. }
  3014. // This is the workhorse of the lexer.
  3015. switch (c) {
  3016. // case '\0': // probably never reached
  3017. // p->lex = XC_LEX_EOF;
  3018. // break;
  3019. case '\n':
  3020. // '\n' is XC_LEX_NLINE, not XC_LEX_WHITESPACE
  3021. // (and "case '\n':" is not just empty here)
  3022. // only to allow interactive dc have a way to exit
  3023. // "parse" stage of "parse,execute" loop
  3024. // on <enter>, not on _next_ token (which would mean
  3025. // commands are not executed on pressing <enter>).
  3026. // IOW: typing "1p<enter>" should print "1" _at once_,
  3027. // not after some more input.
  3028. p->lex_line++;
  3029. dbg_lex("++p->lex_line=%zd", p->lex_line);
  3030. p->lex = XC_LEX_NLINE;
  3031. break;
  3032. case '\t':
  3033. case '\v':
  3034. case '\f':
  3035. case '\r':
  3036. case ' ':
  3037. xc_lex_whitespace();
  3038. break;
  3039. case '!':
  3040. c2 = *p->lex_inbuf;
  3041. if (c2 == '=')
  3042. p->lex = XC_LEX_OP_REL_NE;
  3043. else if (c2 == '<')
  3044. p->lex = XC_LEX_OP_REL_LE;
  3045. else if (c2 == '>')
  3046. p->lex = XC_LEX_OP_REL_GE;
  3047. else
  3048. RETURN_STATUS(bc_error_bad_character(c));
  3049. p->lex_inbuf++;
  3050. break;
  3051. case '#':
  3052. xc_lex_lineComment();
  3053. break;
  3054. case '.':
  3055. if (isdigit(*p->lex_inbuf))
  3056. s = zxc_lex_number(c);
  3057. else
  3058. s = bc_error_bad_character(c);
  3059. break;
  3060. case '0':
  3061. case '1':
  3062. case '2':
  3063. case '3':
  3064. case '4':
  3065. case '5':
  3066. case '6':
  3067. case '7':
  3068. case '8':
  3069. case '9':
  3070. case 'A':
  3071. case 'B':
  3072. case 'C':
  3073. case 'D':
  3074. case 'E':
  3075. case 'F':
  3076. s = zxc_lex_number(c);
  3077. break;
  3078. case '[':
  3079. s = zdc_lex_string();
  3080. break;
  3081. default:
  3082. p->lex = XC_LEX_INVALID;
  3083. s = bc_error_bad_character(c);
  3084. break;
  3085. }
  3086. RETURN_STATUS(s);
  3087. }
  3088. #define zdc_lex_token(...) (zdc_lex_token(__VA_ARGS__) COMMA_SUCCESS)
  3089. #endif // ENABLE_DC
  3090. static void xc_parse_push(unsigned i)
  3091. {
  3092. BcVec *code = &G.prs.func->code;
  3093. dbg_compile("%s:%d pushing bytecode %zd:%d", __func__, __LINE__, code->len, i);
  3094. bc_vec_pushByte(code, (uint8_t)i);
  3095. }
  3096. static void xc_parse_pushName(char *name)
  3097. {
  3098. #if 1
  3099. BcVec *code = &G.prs.func->code;
  3100. size_t pos = code->len;
  3101. size_t len = strlen(name) + 1;
  3102. bc_vec_expand(code, pos + len);
  3103. strcpy(code->v + pos, name);
  3104. code->len = pos + len;
  3105. #else
  3106. // Smaller code, but way slow:
  3107. do {
  3108. xc_parse_push(*name);
  3109. } while (*name++);
  3110. #endif
  3111. }
  3112. // Indexes < 0xfc are encoded verbatim, else first byte is
  3113. // 0xfc, 0xfd, 0xfe or 0xff, encoding "1..4 bytes",
  3114. // followed by that many bytes, lsb first.
  3115. // (The above describes 32-bit case).
  3116. #define SMALL_INDEX_LIMIT (0x100 - sizeof(size_t))
  3117. static void bc_vec_pushIndex(BcVec *v, size_t idx)
  3118. {
  3119. size_t mask;
  3120. unsigned amt;
  3121. dbg_lex("%s:%d pushing index %zd", __func__, __LINE__, idx);
  3122. if (idx < SMALL_INDEX_LIMIT) {
  3123. bc_vec_pushByte(v, idx);
  3124. return;
  3125. }
  3126. mask = ((size_t)0xff) << (sizeof(idx) * 8 - 8);
  3127. amt = sizeof(idx);
  3128. for (;;) {
  3129. if (idx & mask) break;
  3130. mask >>= 8;
  3131. amt--;
  3132. }
  3133. // amt is at least 1 here - "one byte of length data follows"
  3134. bc_vec_pushByte(v, (SMALL_INDEX_LIMIT - 1) + amt);
  3135. do {
  3136. bc_vec_pushByte(v, (unsigned char)idx);
  3137. idx >>= 8;
  3138. } while (idx != 0);
  3139. }
  3140. static void xc_parse_pushIndex(size_t idx)
  3141. {
  3142. bc_vec_pushIndex(&G.prs.func->code, idx);
  3143. }
  3144. static void xc_parse_pushInst_and_Index(unsigned inst, size_t idx)
  3145. {
  3146. xc_parse_push(inst);
  3147. xc_parse_pushIndex(idx);
  3148. }
  3149. #if ENABLE_BC
  3150. static void bc_parse_pushJUMP(size_t idx)
  3151. {
  3152. xc_parse_pushInst_and_Index(BC_INST_JUMP, idx);
  3153. }
  3154. static void bc_parse_pushJUMP_ZERO(size_t idx)
  3155. {
  3156. xc_parse_pushInst_and_Index(BC_INST_JUMP_ZERO, idx);
  3157. }
  3158. static BC_STATUS zbc_parse_pushSTR(void)
  3159. {
  3160. BcParse *p = &G.prs;
  3161. char *str = xstrdup(p->lex_strnumbuf.v);
  3162. xc_parse_pushInst_and_Index(XC_INST_STR, p->func->strs.len);
  3163. bc_vec_push(&p->func->strs, &str);
  3164. RETURN_STATUS(zxc_lex_next());
  3165. }
  3166. #define zbc_parse_pushSTR(...) (zbc_parse_pushSTR(__VA_ARGS__) COMMA_SUCCESS)
  3167. #endif
  3168. static void xc_parse_pushNUM(void)
  3169. {
  3170. BcParse *p = &G.prs;
  3171. char *num = xstrdup(p->lex_strnumbuf.v);
  3172. #if ENABLE_BC && ENABLE_DC
  3173. size_t idx = bc_vec_push(IS_BC ? &p->func->consts : &G.prog.consts, &num);
  3174. #elif ENABLE_BC
  3175. size_t idx = bc_vec_push(&p->func->consts, &num);
  3176. #else // DC
  3177. size_t idx = bc_vec_push(&G.prog.consts, &num);
  3178. #endif
  3179. xc_parse_pushInst_and_Index(XC_INST_NUM, idx);
  3180. }
  3181. static BC_STATUS zxc_parse_text_init(const char *text)
  3182. {
  3183. G.prs.func = xc_program_func(G.prs.fidx);
  3184. G.prs.lex_inbuf = text;
  3185. G.prs.lex = G.prs.lex_last = XC_LEX_INVALID;
  3186. RETURN_STATUS(zxc_lex_next());
  3187. }
  3188. #define zxc_parse_text_init(...) (zxc_parse_text_init(__VA_ARGS__) COMMA_SUCCESS)
  3189. // Called when parsing or execution detects a failure,
  3190. // resets execution structures.
  3191. static void xc_program_reset(void)
  3192. {
  3193. BcFunc *f;
  3194. BcInstPtr *ip;
  3195. bc_vec_npop(&G.prog.exestack, G.prog.exestack.len - 1);
  3196. bc_vec_pop_all(&G.prog.results);
  3197. f = xc_program_func_BC_PROG_MAIN();
  3198. ip = bc_vec_top(&G.prog.exestack);
  3199. ip->inst_idx = f->code.len;
  3200. }
  3201. // Called when parsing code detects a failure,
  3202. // resets parsing structures.
  3203. static void xc_parse_reset(void)
  3204. {
  3205. BcParse *p = &G.prs;
  3206. if (p->fidx != BC_PROG_MAIN) {
  3207. bc_func_free(p->func);
  3208. bc_func_init(p->func);
  3209. p->fidx = BC_PROG_MAIN;
  3210. p->func = xc_program_func_BC_PROG_MAIN();
  3211. }
  3212. p->lex_inbuf += strlen(p->lex_inbuf);
  3213. p->lex = XC_LEX_EOF;
  3214. IF_BC(bc_vec_pop_all(&p->exits);)
  3215. IF_BC(bc_vec_pop_all(&p->conds);)
  3216. IF_BC(bc_vec_pop_all(&p->ops);)
  3217. xc_program_reset();
  3218. }
  3219. static void xc_parse_free(void)
  3220. {
  3221. IF_BC(bc_vec_free(&G.prs.exits);)
  3222. IF_BC(bc_vec_free(&G.prs.conds);)
  3223. IF_BC(bc_vec_free(&G.prs.ops);)
  3224. bc_vec_free(&G.prs.lex_strnumbuf);
  3225. }
  3226. static void xc_parse_create(size_t fidx)
  3227. {
  3228. BcParse *p = &G.prs;
  3229. memset(p, 0, sizeof(BcParse));
  3230. bc_char_vec_init(&p->lex_strnumbuf);
  3231. IF_BC(bc_vec_init(&p->exits, sizeof(size_t), NULL);)
  3232. IF_BC(bc_vec_init(&p->conds, sizeof(size_t), NULL);)
  3233. IF_BC(bc_vec_init(&p->ops, sizeof(BcLexType), NULL);)
  3234. p->fidx = fidx;
  3235. p->func = xc_program_func(fidx);
  3236. }
  3237. static void xc_program_add_fn(void)
  3238. {
  3239. //size_t idx;
  3240. BcFunc f;
  3241. bc_func_init(&f);
  3242. //idx =
  3243. bc_vec_push(&G.prog.fns, &f);
  3244. //return idx;
  3245. }
  3246. #if ENABLE_BC
  3247. // Note: takes ownership of 'name' (must be malloced)
  3248. static size_t bc_program_addFunc(char *name)
  3249. {
  3250. size_t idx;
  3251. BcId entry, *entry_ptr;
  3252. int inserted;
  3253. entry.name = name;
  3254. entry.idx = G.prog.fns.len;
  3255. inserted = bc_map_insert(&G.prog.fn_map, &entry, &idx);
  3256. if (!inserted) free(name);
  3257. entry_ptr = bc_vec_item(&G.prog.fn_map, idx);
  3258. idx = entry_ptr->idx;
  3259. if (!inserted) {
  3260. // There is already a function with this name.
  3261. // It'll be redefined now, clear old definition.
  3262. BcFunc *func = xc_program_func(entry_ptr->idx);
  3263. bc_func_free(func);
  3264. bc_func_init(func);
  3265. } else {
  3266. xc_program_add_fn();
  3267. }
  3268. return idx;
  3269. }
  3270. #define BC_PARSE_TOP_OP(p) (*(BcLexType*)bc_vec_top(&(p)->ops))
  3271. // We can calculate the conversion between tokens and exprs by subtracting the
  3272. // position of the first operator in the lex enum and adding the position of the
  3273. // first in the expr enum. Note: This only works for binary operators.
  3274. #define BC_TOKEN_2_INST(t) ((char) ((t) - XC_LEX_OP_POWER + XC_INST_POWER))
  3275. static BC_STATUS zbc_parse_expr(uint8_t flags);
  3276. #define zbc_parse_expr(...) (zbc_parse_expr(__VA_ARGS__) COMMA_SUCCESS)
  3277. static BC_STATUS zbc_parse_stmt_possibly_auto(bool auto_allowed);
  3278. #define zbc_parse_stmt_possibly_auto(...) (zbc_parse_stmt_possibly_auto(__VA_ARGS__) COMMA_SUCCESS)
  3279. static BC_STATUS zbc_parse_stmt(void)
  3280. {
  3281. RETURN_STATUS(zbc_parse_stmt_possibly_auto(false));
  3282. }
  3283. #define zbc_parse_stmt(...) (zbc_parse_stmt(__VA_ARGS__) COMMA_SUCCESS)
  3284. static BC_STATUS zbc_parse_stmt_allow_NLINE_before(const char *after_X)
  3285. {
  3286. BcParse *p = &G.prs;
  3287. // "if(cond)<newline>stmt" is accepted too, but not 2+ newlines.
  3288. // Same for "else", "while()", "for()".
  3289. BcStatus s = zbc_lex_next_and_skip_NLINE();
  3290. if (s) RETURN_STATUS(s);
  3291. if (p->lex == XC_LEX_NLINE)
  3292. RETURN_STATUS(bc_error_fmt("no statement after '%s'", after_X));
  3293. RETURN_STATUS(zbc_parse_stmt());
  3294. }
  3295. #define zbc_parse_stmt_allow_NLINE_before(...) (zbc_parse_stmt_allow_NLINE_before(__VA_ARGS__) COMMA_SUCCESS)
  3296. static void bc_parse_operator(BcLexType type, size_t start, size_t *nexprs)
  3297. {
  3298. BcParse *p = &G.prs;
  3299. char l, r = bc_operation_PREC(type - XC_LEX_1st_op);
  3300. bool left = bc_operation_LEFT(type - XC_LEX_1st_op);
  3301. while (p->ops.len > start) {
  3302. BcLexType t = BC_PARSE_TOP_OP(p);
  3303. if (t == BC_LEX_LPAREN) break;
  3304. l = bc_operation_PREC(t - XC_LEX_1st_op);
  3305. if (l >= r && (l != r || !left)) break;
  3306. xc_parse_push(BC_TOKEN_2_INST(t));
  3307. bc_vec_pop(&p->ops);
  3308. *nexprs -= (t != BC_LEX_OP_BOOL_NOT && t != XC_LEX_NEG);
  3309. }
  3310. bc_vec_push(&p->ops, &type);
  3311. }
  3312. static BC_STATUS zbc_parse_rightParen(size_t ops_bgn, size_t *nexs)
  3313. {
  3314. BcParse *p = &G.prs;
  3315. BcLexType top;
  3316. if (p->ops.len <= ops_bgn)
  3317. RETURN_STATUS(bc_error_bad_expression());
  3318. top = BC_PARSE_TOP_OP(p);
  3319. while (top != BC_LEX_LPAREN) {
  3320. xc_parse_push(BC_TOKEN_2_INST(top));
  3321. bc_vec_pop(&p->ops);
  3322. *nexs -= (top != BC_LEX_OP_BOOL_NOT && top != XC_LEX_NEG);
  3323. if (p->ops.len <= ops_bgn)
  3324. RETURN_STATUS(bc_error_bad_expression());
  3325. top = BC_PARSE_TOP_OP(p);
  3326. }
  3327. bc_vec_pop(&p->ops);
  3328. RETURN_STATUS(BC_STATUS_SUCCESS);
  3329. }
  3330. #define zbc_parse_rightParen(...) (zbc_parse_rightParen(__VA_ARGS__) COMMA_SUCCESS)
  3331. static BC_STATUS zbc_parse_params(uint8_t flags)
  3332. {
  3333. BcParse *p = &G.prs;
  3334. BcStatus s;
  3335. size_t nparams;
  3336. dbg_lex("%s:%d p->lex:%d", __func__, __LINE__, p->lex);
  3337. flags = (flags & ~(BC_PARSE_PRINT | BC_PARSE_REL)) | BC_PARSE_ARRAY;
  3338. s = zxc_lex_next();
  3339. if (s) RETURN_STATUS(s);
  3340. nparams = 0;
  3341. if (p->lex != BC_LEX_RPAREN) {
  3342. for (;;) {
  3343. s = zbc_parse_expr(flags);
  3344. if (s) RETURN_STATUS(s);
  3345. nparams++;
  3346. if (p->lex != BC_LEX_COMMA) {
  3347. if (p->lex == BC_LEX_RPAREN)
  3348. break;
  3349. RETURN_STATUS(bc_error_bad_token());
  3350. }
  3351. s = zxc_lex_next();
  3352. if (s) RETURN_STATUS(s);
  3353. }
  3354. }
  3355. xc_parse_pushInst_and_Index(BC_INST_CALL, nparams);
  3356. RETURN_STATUS(BC_STATUS_SUCCESS);
  3357. }
  3358. #define zbc_parse_params(...) (zbc_parse_params(__VA_ARGS__) COMMA_SUCCESS)
  3359. // Note: takes ownership of 'name' (must be malloced)
  3360. static BC_STATUS zbc_parse_call(char *name, uint8_t flags)
  3361. {
  3362. BcParse *p = &G.prs;
  3363. BcStatus s;
  3364. BcId entry, *entry_ptr;
  3365. size_t idx;
  3366. entry.name = name;
  3367. s = zbc_parse_params(flags);
  3368. if (s) goto err;
  3369. if (p->lex != BC_LEX_RPAREN) {
  3370. s = bc_error_bad_token();
  3371. goto err;
  3372. }
  3373. idx = bc_map_find_exact(&G.prog.fn_map, &entry);
  3374. if (idx == BC_VEC_INVALID_IDX) {
  3375. // No such function exists, create an empty one
  3376. bc_program_addFunc(name);
  3377. idx = bc_map_find_exact(&G.prog.fn_map, &entry);
  3378. } else
  3379. free(name);
  3380. entry_ptr = bc_vec_item(&G.prog.fn_map, idx);
  3381. xc_parse_pushIndex(entry_ptr->idx);
  3382. RETURN_STATUS(zxc_lex_next());
  3383. err:
  3384. free(name);
  3385. RETURN_STATUS(s);
  3386. }
  3387. #define zbc_parse_call(...) (zbc_parse_call(__VA_ARGS__) COMMA_SUCCESS)
  3388. static BC_STATUS zbc_parse_name(BcInst *type, uint8_t flags)
  3389. {
  3390. BcParse *p = &G.prs;
  3391. BcStatus s;
  3392. char *name;
  3393. name = xstrdup(p->lex_strnumbuf.v);
  3394. s = zxc_lex_next();
  3395. if (s) goto err;
  3396. if (p->lex == BC_LEX_LBRACKET) {
  3397. s = zxc_lex_next();
  3398. if (s) goto err;
  3399. if (p->lex == BC_LEX_RBRACKET) {
  3400. if (!(flags & BC_PARSE_ARRAY)) {
  3401. s = bc_error_bad_expression();
  3402. goto err;
  3403. }
  3404. *type = XC_INST_ARRAY;
  3405. } else {
  3406. *type = XC_INST_ARRAY_ELEM;
  3407. flags &= ~(BC_PARSE_PRINT | BC_PARSE_REL);
  3408. s = zbc_parse_expr(flags);
  3409. if (s) goto err;
  3410. }
  3411. s = zxc_lex_next();
  3412. if (s) goto err;
  3413. xc_parse_push(*type);
  3414. xc_parse_pushName(name);
  3415. free(name);
  3416. } else if (p->lex == BC_LEX_LPAREN) {
  3417. if (flags & BC_PARSE_NOCALL) {
  3418. s = bc_error_bad_token();
  3419. goto err;
  3420. }
  3421. *type = BC_INST_CALL;
  3422. s = zbc_parse_call(name, flags);
  3423. } else {
  3424. *type = XC_INST_VAR;
  3425. xc_parse_push(XC_INST_VAR);
  3426. xc_parse_pushName(name);
  3427. free(name);
  3428. }
  3429. RETURN_STATUS(s);
  3430. err:
  3431. free(name);
  3432. RETURN_STATUS(s);
  3433. }
  3434. #define zbc_parse_name(...) (zbc_parse_name(__VA_ARGS__) COMMA_SUCCESS)
  3435. static BC_STATUS zbc_parse_read(void)
  3436. {
  3437. BcParse *p = &G.prs;
  3438. BcStatus s;
  3439. s = zxc_lex_next();
  3440. if (s) RETURN_STATUS(s);
  3441. if (p->lex != BC_LEX_LPAREN) RETURN_STATUS(bc_error_bad_token());
  3442. s = zxc_lex_next();
  3443. if (s) RETURN_STATUS(s);
  3444. if (p->lex != BC_LEX_RPAREN) RETURN_STATUS(bc_error_bad_token());
  3445. xc_parse_push(XC_INST_READ);
  3446. RETURN_STATUS(s);
  3447. }
  3448. #define zbc_parse_read(...) (zbc_parse_read(__VA_ARGS__) COMMA_SUCCESS)
  3449. static BC_STATUS zbc_parse_builtin(BcLexType type, uint8_t flags, BcInst *prev)
  3450. {
  3451. BcParse *p = &G.prs;
  3452. BcStatus s;
  3453. s = zxc_lex_next();
  3454. if (s) RETURN_STATUS(s);
  3455. if (p->lex != BC_LEX_LPAREN) RETURN_STATUS(bc_error_bad_token());
  3456. flags = (flags & ~(BC_PARSE_PRINT | BC_PARSE_REL)) | BC_PARSE_ARRAY;
  3457. s = zxc_lex_next();
  3458. if (s) RETURN_STATUS(s);
  3459. s = zbc_parse_expr(flags);
  3460. if (s) RETURN_STATUS(s);
  3461. if (p->lex != BC_LEX_RPAREN) RETURN_STATUS(bc_error_bad_token());
  3462. *prev = (type == BC_LEX_KEY_LENGTH) ? XC_INST_LENGTH : XC_INST_SQRT;
  3463. xc_parse_push(*prev);
  3464. RETURN_STATUS(s);
  3465. }
  3466. #define zbc_parse_builtin(...) (zbc_parse_builtin(__VA_ARGS__) COMMA_SUCCESS)
  3467. static BC_STATUS zbc_parse_scale(BcInst *type, uint8_t flags)
  3468. {
  3469. BcParse *p = &G.prs;
  3470. BcStatus s;
  3471. s = zxc_lex_next();
  3472. if (s) RETURN_STATUS(s);
  3473. if (p->lex != BC_LEX_LPAREN) {
  3474. *type = XC_INST_SCALE;
  3475. xc_parse_push(XC_INST_SCALE);
  3476. RETURN_STATUS(BC_STATUS_SUCCESS);
  3477. }
  3478. *type = XC_INST_SCALE_FUNC;
  3479. flags &= ~(BC_PARSE_PRINT | BC_PARSE_REL);
  3480. s = zxc_lex_next();
  3481. if (s) RETURN_STATUS(s);
  3482. s = zbc_parse_expr(flags);
  3483. if (s) RETURN_STATUS(s);
  3484. if (p->lex != BC_LEX_RPAREN)
  3485. RETURN_STATUS(bc_error_bad_token());
  3486. xc_parse_push(XC_INST_SCALE_FUNC);
  3487. RETURN_STATUS(zxc_lex_next());
  3488. }
  3489. #define zbc_parse_scale(...) (zbc_parse_scale(__VA_ARGS__) COMMA_SUCCESS)
  3490. static BC_STATUS zbc_parse_incdec(BcInst *prev, size_t *nexs, uint8_t flags)
  3491. {
  3492. BcParse *p = &G.prs;
  3493. BcStatus s;
  3494. BcLexType type;
  3495. char inst;
  3496. BcInst etype = *prev;
  3497. if (etype == XC_INST_VAR || etype == XC_INST_ARRAY_ELEM
  3498. || etype == XC_INST_SCALE || etype == BC_INST_LAST
  3499. || etype == XC_INST_IBASE || etype == XC_INST_OBASE
  3500. ) {
  3501. *prev = inst = BC_INST_INC_POST + (p->lex != BC_LEX_OP_INC);
  3502. xc_parse_push(inst);
  3503. s = zxc_lex_next();
  3504. } else {
  3505. *prev = inst = BC_INST_INC_PRE + (p->lex != BC_LEX_OP_INC);
  3506. s = zxc_lex_next();
  3507. if (s) RETURN_STATUS(s);
  3508. type = p->lex;
  3509. // Because we parse the next part of the expression
  3510. // right here, we need to increment this.
  3511. *nexs = *nexs + 1;
  3512. switch (type) {
  3513. case XC_LEX_NAME:
  3514. s = zbc_parse_name(prev, flags | BC_PARSE_NOCALL);
  3515. break;
  3516. case BC_LEX_KEY_IBASE:
  3517. case BC_LEX_KEY_LAST:
  3518. case BC_LEX_KEY_OBASE:
  3519. xc_parse_push(type - BC_LEX_KEY_IBASE + XC_INST_IBASE);
  3520. s = zxc_lex_next();
  3521. break;
  3522. case BC_LEX_KEY_SCALE:
  3523. s = zxc_lex_next();
  3524. if (s) RETURN_STATUS(s);
  3525. if (p->lex == BC_LEX_LPAREN)
  3526. s = bc_error_bad_token();
  3527. else
  3528. xc_parse_push(XC_INST_SCALE);
  3529. break;
  3530. default:
  3531. s = bc_error_bad_token();
  3532. break;
  3533. }
  3534. if (!s) xc_parse_push(inst);
  3535. }
  3536. RETURN_STATUS(s);
  3537. }
  3538. #define zbc_parse_incdec(...) (zbc_parse_incdec(__VA_ARGS__) COMMA_SUCCESS)
  3539. static int bc_parse_inst_isLeaf(BcInst p)
  3540. {
  3541. return (p >= XC_INST_NUM && p <= XC_INST_SQRT)
  3542. || p == BC_INST_INC_POST
  3543. || p == BC_INST_DEC_POST
  3544. ;
  3545. }
  3546. #define BC_PARSE_LEAF(prev, bin_last, rparen) \
  3547. (!(bin_last) && ((rparen) || bc_parse_inst_isLeaf(prev)))
  3548. static BC_STATUS zbc_parse_minus(BcInst *prev, size_t ops_bgn,
  3549. bool rparen, bool bin_last, size_t *nexprs)
  3550. {
  3551. BcParse *p = &G.prs;
  3552. BcStatus s;
  3553. BcLexType type;
  3554. s = zxc_lex_next();
  3555. if (s) RETURN_STATUS(s);
  3556. type = BC_PARSE_LEAF(*prev, bin_last, rparen) ? XC_LEX_OP_MINUS : XC_LEX_NEG;
  3557. *prev = BC_TOKEN_2_INST(type);
  3558. // We can just push onto the op stack because this is the largest
  3559. // precedence operator that gets pushed. Inc/dec does not.
  3560. if (type != XC_LEX_OP_MINUS)
  3561. bc_vec_push(&p->ops, &type);
  3562. else
  3563. bc_parse_operator(type, ops_bgn, nexprs);
  3564. RETURN_STATUS(s);
  3565. }
  3566. #define zbc_parse_minus(...) (zbc_parse_minus(__VA_ARGS__) COMMA_SUCCESS)
  3567. static BC_STATUS zbc_parse_print(void)
  3568. {
  3569. BcParse *p = &G.prs;
  3570. BcStatus s;
  3571. BcLexType type;
  3572. for (;;) {
  3573. s = zxc_lex_next();
  3574. if (s) RETURN_STATUS(s);
  3575. type = p->lex;
  3576. if (type == XC_LEX_STR) {
  3577. s = zbc_parse_pushSTR();
  3578. } else {
  3579. s = zbc_parse_expr(0);
  3580. }
  3581. if (s) RETURN_STATUS(s);
  3582. xc_parse_push(XC_INST_PRINT_POP);
  3583. if (p->lex != BC_LEX_COMMA)
  3584. break;
  3585. }
  3586. RETURN_STATUS(s);
  3587. }
  3588. #define zbc_parse_print(...) (zbc_parse_print(__VA_ARGS__) COMMA_SUCCESS)
  3589. static BC_STATUS zbc_parse_return(void)
  3590. {
  3591. BcParse *p = &G.prs;
  3592. BcStatus s;
  3593. BcLexType t;
  3594. dbg_lex_enter("%s:%d entered", __func__, __LINE__);
  3595. s = zxc_lex_next();
  3596. if (s) RETURN_STATUS(s);
  3597. t = p->lex;
  3598. if (t == XC_LEX_NLINE || t == BC_LEX_SCOLON || t == BC_LEX_RBRACE)
  3599. xc_parse_push(BC_INST_RET0);
  3600. else {
  3601. //TODO: if (p->func->voidfunc) ERROR
  3602. s = zbc_parse_expr(0);
  3603. if (s) RETURN_STATUS(s);
  3604. if (t != BC_LEX_LPAREN // "return EXPR", no ()
  3605. || p->lex_last != BC_LEX_RPAREN // example: "return (a) + b"
  3606. ) {
  3607. s = zbc_POSIX_requires("parentheses around return expressions");
  3608. if (s) RETURN_STATUS(s);
  3609. }
  3610. xc_parse_push(XC_INST_RET);
  3611. }
  3612. dbg_lex_done("%s:%d done", __func__, __LINE__);
  3613. RETURN_STATUS(s);
  3614. }
  3615. #define zbc_parse_return(...) (zbc_parse_return(__VA_ARGS__) COMMA_SUCCESS)
  3616. static void rewrite_label_to_current(size_t idx)
  3617. {
  3618. BcParse *p = &G.prs;
  3619. size_t *label = bc_vec_item(&p->func->labels, idx);
  3620. *label = p->func->code.len;
  3621. }
  3622. static BC_STATUS zbc_parse_if(void)
  3623. {
  3624. BcParse *p = &G.prs;
  3625. BcStatus s;
  3626. size_t ip_idx;
  3627. dbg_lex_enter("%s:%d entered", __func__, __LINE__);
  3628. s = zxc_lex_next();
  3629. if (s) RETURN_STATUS(s);
  3630. if (p->lex != BC_LEX_LPAREN) RETURN_STATUS(bc_error_bad_token());
  3631. s = zxc_lex_next();
  3632. if (s) RETURN_STATUS(s);
  3633. s = zbc_parse_expr(BC_PARSE_REL);
  3634. if (s) RETURN_STATUS(s);
  3635. if (p->lex != BC_LEX_RPAREN) RETURN_STATUS(bc_error_bad_token());
  3636. // Encode "if zero, jump to ..."
  3637. // Pushed value (destination of the jump) is uninitialized,
  3638. // will be rewritten to be address of "end of if()" or of "else".
  3639. ip_idx = bc_vec_push(&p->func->labels, &ip_idx);
  3640. bc_parse_pushJUMP_ZERO(ip_idx);
  3641. s = zbc_parse_stmt_allow_NLINE_before(STRING_if);
  3642. if (s) RETURN_STATUS(s);
  3643. dbg_lex("%s:%d in if after stmt: p->lex:%d", __func__, __LINE__, p->lex);
  3644. if (p->lex == BC_LEX_KEY_ELSE) {
  3645. size_t ip2_idx;
  3646. // Encode "after then_stmt, jump to end of if()"
  3647. ip2_idx = bc_vec_push(&p->func->labels, &ip2_idx);
  3648. dbg_lex("%s:%d after if() then_stmt: BC_INST_JUMP to %zd", __func__, __LINE__, ip2_idx);
  3649. bc_parse_pushJUMP(ip2_idx);
  3650. dbg_lex("%s:%d rewriting 'if_zero' label to jump to 'else'-> %zd", __func__, __LINE__, p->func->code.len);
  3651. rewrite_label_to_current(ip_idx);
  3652. ip_idx = ip2_idx;
  3653. s = zbc_parse_stmt_allow_NLINE_before(STRING_else);
  3654. if (s) RETURN_STATUS(s);
  3655. }
  3656. dbg_lex("%s:%d rewriting label to jump after 'if' body-> %zd", __func__, __LINE__, p->func->code.len);
  3657. rewrite_label_to_current(ip_idx);
  3658. dbg_lex_done("%s:%d done", __func__, __LINE__);
  3659. RETURN_STATUS(s);
  3660. }
  3661. #define zbc_parse_if(...) (zbc_parse_if(__VA_ARGS__) COMMA_SUCCESS)
  3662. static BC_STATUS zbc_parse_while(void)
  3663. {
  3664. BcParse *p = &G.prs;
  3665. BcStatus s;
  3666. size_t cond_idx;
  3667. size_t ip_idx;
  3668. s = zxc_lex_next();
  3669. if (s) RETURN_STATUS(s);
  3670. if (p->lex != BC_LEX_LPAREN) RETURN_STATUS(bc_error_bad_token());
  3671. s = zxc_lex_next();
  3672. if (s) RETURN_STATUS(s);
  3673. cond_idx = bc_vec_push(&p->func->labels, &p->func->code.len);
  3674. ip_idx = cond_idx + 1;
  3675. bc_vec_push(&p->conds, &cond_idx);
  3676. bc_vec_push(&p->exits, &ip_idx);
  3677. bc_vec_push(&p->func->labels, &ip_idx);
  3678. s = zbc_parse_expr(BC_PARSE_REL);
  3679. if (s) RETURN_STATUS(s);
  3680. if (p->lex != BC_LEX_RPAREN) RETURN_STATUS(bc_error_bad_token());
  3681. bc_parse_pushJUMP_ZERO(ip_idx);
  3682. s = zbc_parse_stmt_allow_NLINE_before(STRING_while);
  3683. if (s) RETURN_STATUS(s);
  3684. dbg_lex("%s:%d BC_INST_JUMP to %zd", __func__, __LINE__, cond_idx);
  3685. bc_parse_pushJUMP(cond_idx);
  3686. dbg_lex("%s:%d rewriting label-> %zd", __func__, __LINE__, p->func->code.len);
  3687. rewrite_label_to_current(ip_idx);
  3688. bc_vec_pop(&p->exits);
  3689. bc_vec_pop(&p->conds);
  3690. RETURN_STATUS(s);
  3691. }
  3692. #define zbc_parse_while(...) (zbc_parse_while(__VA_ARGS__) COMMA_SUCCESS)
  3693. static BC_STATUS zbc_parse_for(void)
  3694. {
  3695. BcParse *p = &G.prs;
  3696. BcStatus s;
  3697. size_t cond_idx, exit_idx, body_idx, update_idx;
  3698. dbg_lex("%s:%d p->lex:%d", __func__, __LINE__, p->lex);
  3699. s = zxc_lex_next();
  3700. if (s) RETURN_STATUS(s);
  3701. if (p->lex != BC_LEX_LPAREN) RETURN_STATUS(bc_error_bad_token());
  3702. s = zxc_lex_next();
  3703. if (s) RETURN_STATUS(s);
  3704. if (p->lex != BC_LEX_SCOLON) {
  3705. s = zbc_parse_expr(0);
  3706. xc_parse_push(XC_INST_POP);
  3707. if (s) RETURN_STATUS(s);
  3708. } else {
  3709. s = zbc_POSIX_does_not_allow_empty_X_expression_in_for("init");
  3710. if (s) RETURN_STATUS(s);
  3711. }
  3712. if (p->lex != BC_LEX_SCOLON) RETURN_STATUS(bc_error_bad_token());
  3713. s = zxc_lex_next();
  3714. if (s) RETURN_STATUS(s);
  3715. cond_idx = bc_vec_push(&p->func->labels, &p->func->code.len);
  3716. update_idx = cond_idx + 1;
  3717. body_idx = update_idx + 1;
  3718. exit_idx = body_idx + 1;
  3719. if (p->lex != BC_LEX_SCOLON)
  3720. s = zbc_parse_expr(BC_PARSE_REL);
  3721. else {
  3722. // Set this for the next call to xc_parse_pushNUM().
  3723. // This is safe to set because the current token is a semicolon,
  3724. // which has no string requirement.
  3725. bc_vec_string(&p->lex_strnumbuf, 1, "1");
  3726. xc_parse_pushNUM();
  3727. s = zbc_POSIX_does_not_allow_empty_X_expression_in_for("condition");
  3728. }
  3729. if (s) RETURN_STATUS(s);
  3730. if (p->lex != BC_LEX_SCOLON) RETURN_STATUS(bc_error_bad_token());
  3731. s = zxc_lex_next();
  3732. if (s) RETURN_STATUS(s);
  3733. bc_parse_pushJUMP_ZERO(exit_idx);
  3734. bc_parse_pushJUMP(body_idx);
  3735. bc_vec_push(&p->conds, &update_idx);
  3736. bc_vec_push(&p->func->labels, &p->func->code.len);
  3737. if (p->lex != BC_LEX_RPAREN) {
  3738. s = zbc_parse_expr(0);
  3739. if (s) RETURN_STATUS(s);
  3740. if (p->lex != BC_LEX_RPAREN) RETURN_STATUS(bc_error_bad_token());
  3741. xc_parse_push(XC_INST_POP);
  3742. } else {
  3743. s = zbc_POSIX_does_not_allow_empty_X_expression_in_for("update");
  3744. if (s) RETURN_STATUS(s);
  3745. }
  3746. bc_parse_pushJUMP(cond_idx);
  3747. bc_vec_push(&p->func->labels, &p->func->code.len);
  3748. bc_vec_push(&p->exits, &exit_idx);
  3749. bc_vec_push(&p->func->labels, &exit_idx);
  3750. s = zbc_parse_stmt_allow_NLINE_before(STRING_for);
  3751. if (s) RETURN_STATUS(s);
  3752. dbg_lex("%s:%d BC_INST_JUMP to %zd", __func__, __LINE__, update_idx);
  3753. bc_parse_pushJUMP(update_idx);
  3754. dbg_lex("%s:%d rewriting label-> %zd", __func__, __LINE__, p->func->code.len);
  3755. rewrite_label_to_current(exit_idx);
  3756. bc_vec_pop(&p->exits);
  3757. bc_vec_pop(&p->conds);
  3758. RETURN_STATUS(BC_STATUS_SUCCESS);
  3759. }
  3760. #define zbc_parse_for(...) (zbc_parse_for(__VA_ARGS__) COMMA_SUCCESS)
  3761. static BC_STATUS zbc_parse_break_or_continue(BcLexType type)
  3762. {
  3763. BcParse *p = &G.prs;
  3764. size_t i;
  3765. if (type == BC_LEX_KEY_BREAK) {
  3766. if (p->exits.len == 0) // none of the enclosing blocks is a loop
  3767. RETURN_STATUS(bc_error_bad_token());
  3768. i = *(size_t*)bc_vec_top(&p->exits);
  3769. } else {
  3770. i = *(size_t*)bc_vec_top(&p->conds);
  3771. }
  3772. bc_parse_pushJUMP(i);
  3773. RETURN_STATUS(zxc_lex_next());
  3774. }
  3775. #define zbc_parse_break_or_continue(...) (zbc_parse_break_or_continue(__VA_ARGS__) COMMA_SUCCESS)
  3776. static BC_STATUS zbc_func_insert(BcFunc *f, char *name, BcType type)
  3777. {
  3778. BcId *autoid;
  3779. BcId a;
  3780. size_t i;
  3781. autoid = (void*)f->autos.v;
  3782. for (i = 0; i < f->autos.len; i++, autoid++) {
  3783. if (strcmp(name, autoid->name) == 0
  3784. && type == (BcType) autoid->idx
  3785. ) {
  3786. RETURN_STATUS(bc_error("duplicate function parameter or auto name"));
  3787. }
  3788. }
  3789. a.idx = type;
  3790. a.name = name;
  3791. bc_vec_push(&f->autos, &a);
  3792. RETURN_STATUS(BC_STATUS_SUCCESS);
  3793. }
  3794. #define zbc_func_insert(...) (zbc_func_insert(__VA_ARGS__) COMMA_SUCCESS)
  3795. static BC_STATUS zbc_parse_funcdef(void)
  3796. {
  3797. BcParse *p = &G.prs;
  3798. BcStatus s;
  3799. bool comma, voidfunc;
  3800. char *name;
  3801. dbg_lex_enter("%s:%d entered", __func__, __LINE__);
  3802. s = zxc_lex_next();
  3803. if (s) RETURN_STATUS(s);
  3804. if (p->lex != XC_LEX_NAME)
  3805. RETURN_STATUS(bc_error_bad_function_definition());
  3806. // To be maximally both POSIX and GNU-compatible,
  3807. // "void" is not treated as a normal keyword:
  3808. // you can have variable named "void", and even a function
  3809. // named "void": "define void() { return 6; }" is ok.
  3810. // _Only_ "define void f() ..." syntax treats "void"
  3811. // specially.
  3812. voidfunc = (strcmp(p->lex_strnumbuf.v, "void") == 0);
  3813. s = zxc_lex_next();
  3814. if (s) RETURN_STATUS(s);
  3815. voidfunc = (voidfunc && p->lex == XC_LEX_NAME);
  3816. if (voidfunc) {
  3817. s = zxc_lex_next();
  3818. if (s) RETURN_STATUS(s);
  3819. }
  3820. if (p->lex != BC_LEX_LPAREN)
  3821. RETURN_STATUS(bc_error_bad_function_definition());
  3822. p->fidx = bc_program_addFunc(xstrdup(p->lex_strnumbuf.v));
  3823. p->func = xc_program_func(p->fidx);
  3824. p->func->voidfunc = voidfunc;
  3825. s = zxc_lex_next();
  3826. if (s) RETURN_STATUS(s);
  3827. comma = false;
  3828. while (p->lex != BC_LEX_RPAREN) {
  3829. BcType t = BC_TYPE_VAR;
  3830. if (p->lex == XC_LEX_OP_MULTIPLY) {
  3831. t = BC_TYPE_REF;
  3832. s = zxc_lex_next();
  3833. if (s) RETURN_STATUS(s);
  3834. s = zbc_POSIX_does_not_allow("references");
  3835. if (s) RETURN_STATUS(s);
  3836. }
  3837. if (p->lex != XC_LEX_NAME)
  3838. RETURN_STATUS(bc_error_bad_function_definition());
  3839. ++p->func->nparams;
  3840. name = xstrdup(p->lex_strnumbuf.v);
  3841. s = zxc_lex_next();
  3842. if (s) goto err;
  3843. if (p->lex == BC_LEX_LBRACKET) {
  3844. if (t == BC_TYPE_VAR) t = BC_TYPE_ARRAY;
  3845. s = zxc_lex_next();
  3846. if (s) goto err;
  3847. if (p->lex != BC_LEX_RBRACKET) {
  3848. s = bc_error_bad_function_definition();
  3849. goto err;
  3850. }
  3851. s = zxc_lex_next();
  3852. if (s) goto err;
  3853. }
  3854. else if (t == BC_TYPE_REF) {
  3855. s = bc_error_at("vars can't be references");
  3856. goto err;
  3857. }
  3858. comma = p->lex == BC_LEX_COMMA;
  3859. if (comma) {
  3860. s = zxc_lex_next();
  3861. if (s) goto err;
  3862. }
  3863. s = zbc_func_insert(p->func, name, t);
  3864. if (s) goto err;
  3865. }
  3866. if (comma) RETURN_STATUS(bc_error_bad_function_definition());
  3867. s = zxc_lex_next();
  3868. if (s) RETURN_STATUS(s);
  3869. if (p->lex != BC_LEX_LBRACE) {
  3870. s = zbc_POSIX_requires("the left brace be on the same line as the function header");
  3871. if (s) RETURN_STATUS(s);
  3872. }
  3873. // Prevent "define z()<newline>" from being interpreted as function with empty stmt as body
  3874. s = zbc_lex_skip_if_at_NLINE();
  3875. if (s) RETURN_STATUS(s);
  3876. // GNU bc requires a {} block even if function body has single stmt, enforce this
  3877. if (p->lex != BC_LEX_LBRACE)
  3878. RETURN_STATUS(bc_error("function { body } expected"));
  3879. p->in_funcdef++; // to determine whether "return" stmt is allowed, and such
  3880. s = zbc_parse_stmt_possibly_auto(true);
  3881. p->in_funcdef--;
  3882. if (s) RETURN_STATUS(s);
  3883. xc_parse_push(BC_INST_RET0);
  3884. // Subsequent code generation is into main program
  3885. p->fidx = BC_PROG_MAIN;
  3886. p->func = xc_program_func_BC_PROG_MAIN();
  3887. dbg_lex_done("%s:%d done", __func__, __LINE__);
  3888. RETURN_STATUS(s);
  3889. err:
  3890. dbg_lex_done("%s:%d done (error)", __func__, __LINE__);
  3891. free(name);
  3892. RETURN_STATUS(s);
  3893. }
  3894. #define zbc_parse_funcdef(...) (zbc_parse_funcdef(__VA_ARGS__) COMMA_SUCCESS)
  3895. static BC_STATUS zbc_parse_auto(void)
  3896. {
  3897. BcParse *p = &G.prs;
  3898. BcStatus s;
  3899. char *name;
  3900. dbg_lex_enter("%s:%d entered", __func__, __LINE__);
  3901. s = zxc_lex_next();
  3902. if (s) RETURN_STATUS(s);
  3903. for (;;) {
  3904. BcType t;
  3905. if (p->lex != XC_LEX_NAME)
  3906. RETURN_STATUS(bc_error_at("bad 'auto' syntax"));
  3907. name = xstrdup(p->lex_strnumbuf.v);
  3908. s = zxc_lex_next();
  3909. if (s) goto err;
  3910. t = BC_TYPE_VAR;
  3911. if (p->lex == BC_LEX_LBRACKET) {
  3912. t = BC_TYPE_ARRAY;
  3913. s = zxc_lex_next();
  3914. if (s) goto err;
  3915. if (p->lex != BC_LEX_RBRACKET) {
  3916. s = bc_error_at("bad 'auto' syntax");
  3917. goto err;
  3918. }
  3919. s = zxc_lex_next();
  3920. if (s) goto err;
  3921. }
  3922. s = zbc_func_insert(p->func, name, t);
  3923. if (s) goto err;
  3924. if (p->lex == XC_LEX_NLINE
  3925. || p->lex == BC_LEX_SCOLON
  3926. //|| p->lex == BC_LEX_RBRACE // allow "define f() {auto a}"
  3927. ) {
  3928. break;
  3929. }
  3930. if (p->lex != BC_LEX_COMMA)
  3931. RETURN_STATUS(bc_error_at("bad 'auto' syntax"));
  3932. s = zxc_lex_next(); // skip comma
  3933. if (s) RETURN_STATUS(s);
  3934. }
  3935. dbg_lex_done("%s:%d done", __func__, __LINE__);
  3936. RETURN_STATUS(BC_STATUS_SUCCESS);
  3937. err:
  3938. free(name);
  3939. dbg_lex_done("%s:%d done (ERROR)", __func__, __LINE__);
  3940. RETURN_STATUS(s);
  3941. }
  3942. #define zbc_parse_auto(...) (zbc_parse_auto(__VA_ARGS__) COMMA_SUCCESS)
  3943. #undef zbc_parse_stmt_possibly_auto
  3944. static BC_STATUS zbc_parse_stmt_possibly_auto(bool auto_allowed)
  3945. {
  3946. BcParse *p = &G.prs;
  3947. BcStatus s = BC_STATUS_SUCCESS;
  3948. dbg_lex_enter("%s:%d entered, p->lex:%d", __func__, __LINE__, p->lex);
  3949. if (p->lex == XC_LEX_NLINE) {
  3950. dbg_lex_done("%s:%d done (seen XC_LEX_NLINE)", __func__, __LINE__);
  3951. RETURN_STATUS(s);
  3952. }
  3953. if (p->lex == BC_LEX_SCOLON) {
  3954. dbg_lex_done("%s:%d done (seen BC_LEX_SCOLON)", __func__, __LINE__);
  3955. RETURN_STATUS(s);
  3956. }
  3957. if (p->lex == BC_LEX_LBRACE) {
  3958. dbg_lex("%s:%d BC_LEX_LBRACE: (auto_allowed:%d)", __func__, __LINE__, auto_allowed);
  3959. do {
  3960. s = zxc_lex_next();
  3961. if (s) RETURN_STATUS(s);
  3962. } while (p->lex == XC_LEX_NLINE);
  3963. if (auto_allowed && p->lex == BC_LEX_KEY_AUTO) {
  3964. dbg_lex("%s:%d calling zbc_parse_auto()", __func__, __LINE__);
  3965. s = zbc_parse_auto();
  3966. if (s) RETURN_STATUS(s);
  3967. }
  3968. while (p->lex != BC_LEX_RBRACE) {
  3969. dbg_lex("%s:%d block parsing loop", __func__, __LINE__);
  3970. s = zbc_parse_stmt();
  3971. if (s) RETURN_STATUS(s);
  3972. // Check that next token is a correct stmt delimiter -
  3973. // disallows "print 1 print 2" and such.
  3974. if (p->lex == BC_LEX_RBRACE)
  3975. break;
  3976. if (p->lex != BC_LEX_SCOLON
  3977. && p->lex != XC_LEX_NLINE
  3978. ) {
  3979. RETURN_STATUS(bc_error_at("bad statement terminator"));
  3980. }
  3981. s = zxc_lex_next();
  3982. if (s) RETURN_STATUS(s);
  3983. }
  3984. s = zxc_lex_next();
  3985. dbg_lex_done("%s:%d done (seen BC_LEX_RBRACE)", __func__, __LINE__);
  3986. RETURN_STATUS(s);
  3987. }
  3988. dbg_lex("%s:%d p->lex:%d", __func__, __LINE__, p->lex);
  3989. switch (p->lex) {
  3990. case XC_LEX_OP_MINUS:
  3991. case BC_LEX_OP_INC:
  3992. case BC_LEX_OP_DEC:
  3993. case BC_LEX_OP_BOOL_NOT:
  3994. case BC_LEX_LPAREN:
  3995. case XC_LEX_NAME:
  3996. case XC_LEX_NUMBER:
  3997. case BC_LEX_KEY_IBASE:
  3998. case BC_LEX_KEY_LAST:
  3999. case BC_LEX_KEY_LENGTH:
  4000. case BC_LEX_KEY_OBASE:
  4001. case BC_LEX_KEY_READ:
  4002. case BC_LEX_KEY_SCALE:
  4003. case BC_LEX_KEY_SQRT:
  4004. s = zbc_parse_expr(BC_PARSE_PRINT);
  4005. break;
  4006. case XC_LEX_STR:
  4007. s = zbc_parse_pushSTR();
  4008. xc_parse_push(XC_INST_PRINT_STR);
  4009. break;
  4010. case BC_LEX_KEY_BREAK:
  4011. case BC_LEX_KEY_CONTINUE:
  4012. s = zbc_parse_break_or_continue(p->lex);
  4013. break;
  4014. case BC_LEX_KEY_FOR:
  4015. s = zbc_parse_for();
  4016. break;
  4017. case BC_LEX_KEY_HALT:
  4018. xc_parse_push(BC_INST_HALT);
  4019. s = zxc_lex_next();
  4020. break;
  4021. case BC_LEX_KEY_IF:
  4022. s = zbc_parse_if();
  4023. break;
  4024. case BC_LEX_KEY_LIMITS:
  4025. // "limits" is a compile-time command,
  4026. // the output is produced at _parse time_.
  4027. printf(
  4028. "BC_BASE_MAX = "BC_MAX_OBASE_STR "\n"
  4029. "BC_DIM_MAX = "BC_MAX_DIM_STR "\n"
  4030. "BC_SCALE_MAX = "BC_MAX_SCALE_STR "\n"
  4031. "BC_STRING_MAX = "BC_MAX_STRING_STR"\n"
  4032. // "BC_NUM_MAX = "BC_MAX_NUM_STR "\n" - GNU bc does not show this
  4033. "MAX Exponent = "BC_MAX_EXP_STR "\n"
  4034. "Number of vars = "BC_MAX_VARS_STR "\n"
  4035. );
  4036. s = zxc_lex_next();
  4037. break;
  4038. case BC_LEX_KEY_PRINT:
  4039. s = zbc_parse_print();
  4040. break;
  4041. case BC_LEX_KEY_QUIT:
  4042. // "quit" is a compile-time command. For example,
  4043. // "if (0 == 1) quit" terminates when parsing the statement,
  4044. // not when it is executed
  4045. QUIT_OR_RETURN_TO_MAIN;
  4046. case BC_LEX_KEY_RETURN:
  4047. if (!p->in_funcdef)
  4048. RETURN_STATUS(bc_error("'return' not in a function"));
  4049. s = zbc_parse_return();
  4050. break;
  4051. case BC_LEX_KEY_WHILE:
  4052. s = zbc_parse_while();
  4053. break;
  4054. default:
  4055. s = bc_error_bad_token();
  4056. break;
  4057. }
  4058. dbg_lex_done("%s:%d done", __func__, __LINE__);
  4059. RETURN_STATUS(s);
  4060. }
  4061. #define zbc_parse_stmt_possibly_auto(...) (zbc_parse_stmt_possibly_auto(__VA_ARGS__) COMMA_SUCCESS)
  4062. static BC_STATUS zbc_parse_stmt_or_funcdef(void)
  4063. {
  4064. BcParse *p = &G.prs;
  4065. BcStatus s;
  4066. dbg_lex_enter("%s:%d entered", __func__, __LINE__);
  4067. //why?
  4068. // if (p->lex == XC_LEX_EOF)
  4069. // s = bc_error("end of file");
  4070. // else
  4071. if (p->lex == BC_LEX_KEY_DEFINE) {
  4072. dbg_lex("%s:%d p->lex:BC_LEX_KEY_DEFINE", __func__, __LINE__);
  4073. s = zbc_parse_funcdef();
  4074. } else {
  4075. dbg_lex("%s:%d p->lex:%d (not BC_LEX_KEY_DEFINE)", __func__, __LINE__, p->lex);
  4076. s = zbc_parse_stmt();
  4077. }
  4078. dbg_lex_done("%s:%d done", __func__, __LINE__);
  4079. RETURN_STATUS(s);
  4080. }
  4081. #define zbc_parse_stmt_or_funcdef(...) (zbc_parse_stmt_or_funcdef(__VA_ARGS__) COMMA_SUCCESS)
  4082. #undef zbc_parse_expr
  4083. static BC_STATUS zbc_parse_expr(uint8_t flags)
  4084. {
  4085. BcParse *p = &G.prs;
  4086. BcInst prev = XC_INST_PRINT;
  4087. size_t nexprs = 0, ops_bgn = p->ops.len;
  4088. unsigned nparens, nrelops;
  4089. bool paren_first, rprn, assign, bin_last, incdec;
  4090. dbg_lex_enter("%s:%d entered", __func__, __LINE__);
  4091. paren_first = (p->lex == BC_LEX_LPAREN);
  4092. nparens = nrelops = 0;
  4093. rprn = assign = incdec = false;
  4094. bin_last = true;
  4095. for (;;) {
  4096. bool get_token;
  4097. BcStatus s;
  4098. BcLexType t = p->lex;
  4099. if (!lex_allowed_in_bc_expr(t))
  4100. break;
  4101. dbg_lex("%s:%d t:%d", __func__, __LINE__, t);
  4102. get_token = false;
  4103. s = BC_STATUS_SUCCESS;
  4104. switch (t) {
  4105. case BC_LEX_OP_INC:
  4106. case BC_LEX_OP_DEC:
  4107. dbg_lex("%s:%d LEX_OP_INC/DEC", __func__, __LINE__);
  4108. if (incdec) RETURN_STATUS(bc_error_bad_assignment());
  4109. s = zbc_parse_incdec(&prev, &nexprs, flags);
  4110. incdec = true;
  4111. rprn = bin_last = false;
  4112. //get_token = false; - already is
  4113. break;
  4114. case XC_LEX_OP_MINUS:
  4115. dbg_lex("%s:%d LEX_OP_MINUS", __func__, __LINE__);
  4116. s = zbc_parse_minus(&prev, ops_bgn, rprn, bin_last, &nexprs);
  4117. rprn = false;
  4118. //get_token = false; - already is
  4119. bin_last = (prev == XC_INST_MINUS);
  4120. if (bin_last) incdec = false;
  4121. break;
  4122. case BC_LEX_OP_ASSIGN_POWER:
  4123. case BC_LEX_OP_ASSIGN_MULTIPLY:
  4124. case BC_LEX_OP_ASSIGN_DIVIDE:
  4125. case BC_LEX_OP_ASSIGN_MODULUS:
  4126. case BC_LEX_OP_ASSIGN_PLUS:
  4127. case BC_LEX_OP_ASSIGN_MINUS:
  4128. case BC_LEX_OP_ASSIGN:
  4129. dbg_lex("%s:%d LEX_ASSIGNxyz", __func__, __LINE__);
  4130. if (prev != XC_INST_VAR && prev != XC_INST_ARRAY_ELEM
  4131. && prev != XC_INST_SCALE && prev != XC_INST_IBASE
  4132. && prev != XC_INST_OBASE && prev != BC_INST_LAST
  4133. ) {
  4134. RETURN_STATUS(bc_error_bad_assignment());
  4135. }
  4136. // Fallthrough.
  4137. case XC_LEX_OP_POWER:
  4138. case XC_LEX_OP_MULTIPLY:
  4139. case XC_LEX_OP_DIVIDE:
  4140. case XC_LEX_OP_MODULUS:
  4141. case XC_LEX_OP_PLUS:
  4142. case XC_LEX_OP_REL_EQ:
  4143. case XC_LEX_OP_REL_LE:
  4144. case XC_LEX_OP_REL_GE:
  4145. case XC_LEX_OP_REL_NE:
  4146. case XC_LEX_OP_REL_LT:
  4147. case XC_LEX_OP_REL_GT:
  4148. case BC_LEX_OP_BOOL_NOT:
  4149. case BC_LEX_OP_BOOL_OR:
  4150. case BC_LEX_OP_BOOL_AND:
  4151. dbg_lex("%s:%d LEX_OP_xyz", __func__, __LINE__);
  4152. if (t == BC_LEX_OP_BOOL_NOT) {
  4153. if (!bin_last && p->lex_last != BC_LEX_OP_BOOL_NOT)
  4154. RETURN_STATUS(bc_error_bad_expression());
  4155. } else if (prev == XC_INST_BOOL_NOT) {
  4156. RETURN_STATUS(bc_error_bad_expression());
  4157. }
  4158. nrelops += (t >= XC_LEX_OP_REL_EQ && t <= XC_LEX_OP_REL_GT);
  4159. prev = BC_TOKEN_2_INST(t);
  4160. bc_parse_operator(t, ops_bgn, &nexprs);
  4161. rprn = incdec = false;
  4162. get_token = true;
  4163. bin_last = (t != BC_LEX_OP_BOOL_NOT);
  4164. break;
  4165. case BC_LEX_LPAREN:
  4166. dbg_lex("%s:%d LEX_LPAREN", __func__, __LINE__);
  4167. if (BC_PARSE_LEAF(prev, bin_last, rprn))
  4168. RETURN_STATUS(bc_error_bad_expression());
  4169. bc_vec_push(&p->ops, &t);
  4170. nparens++;
  4171. get_token = true;
  4172. rprn = incdec = false;
  4173. break;
  4174. case BC_LEX_RPAREN:
  4175. dbg_lex("%s:%d LEX_RPAREN", __func__, __LINE__);
  4176. //why?
  4177. // if (p->lex_last == BC_LEX_LPAREN) {
  4178. // RETURN_STATUS(bc_error_at("empty expression"));
  4179. // }
  4180. if (bin_last || prev == XC_INST_BOOL_NOT)
  4181. RETURN_STATUS(bc_error_bad_expression());
  4182. if (nparens == 0) {
  4183. goto exit_loop;
  4184. }
  4185. s = zbc_parse_rightParen(ops_bgn, &nexprs);
  4186. nparens--;
  4187. get_token = true;
  4188. rprn = true;
  4189. bin_last = incdec = false;
  4190. break;
  4191. case XC_LEX_NAME:
  4192. dbg_lex("%s:%d LEX_NAME", __func__, __LINE__);
  4193. if (BC_PARSE_LEAF(prev, bin_last, rprn))
  4194. RETURN_STATUS(bc_error_bad_expression());
  4195. s = zbc_parse_name(&prev, flags & ~BC_PARSE_NOCALL);
  4196. rprn = (prev == BC_INST_CALL);
  4197. bin_last = false;
  4198. //get_token = false; - already is
  4199. nexprs++;
  4200. break;
  4201. case XC_LEX_NUMBER:
  4202. dbg_lex("%s:%d LEX_NUMBER", __func__, __LINE__);
  4203. if (BC_PARSE_LEAF(prev, bin_last, rprn))
  4204. RETURN_STATUS(bc_error_bad_expression());
  4205. xc_parse_pushNUM();
  4206. prev = XC_INST_NUM;
  4207. get_token = true;
  4208. rprn = bin_last = false;
  4209. nexprs++;
  4210. break;
  4211. case BC_LEX_KEY_IBASE:
  4212. case BC_LEX_KEY_LAST:
  4213. case BC_LEX_KEY_OBASE:
  4214. dbg_lex("%s:%d LEX_IBASE/LAST/OBASE", __func__, __LINE__);
  4215. if (BC_PARSE_LEAF(prev, bin_last, rprn))
  4216. RETURN_STATUS(bc_error_bad_expression());
  4217. prev = (char) (t - BC_LEX_KEY_IBASE + XC_INST_IBASE);
  4218. xc_parse_push((char) prev);
  4219. get_token = true;
  4220. rprn = bin_last = false;
  4221. nexprs++;
  4222. break;
  4223. case BC_LEX_KEY_LENGTH:
  4224. case BC_LEX_KEY_SQRT:
  4225. dbg_lex("%s:%d LEX_LEN/SQRT", __func__, __LINE__);
  4226. if (BC_PARSE_LEAF(prev, bin_last, rprn))
  4227. RETURN_STATUS(bc_error_bad_expression());
  4228. s = zbc_parse_builtin(t, flags, &prev);
  4229. get_token = true;
  4230. rprn = bin_last = incdec = false;
  4231. nexprs++;
  4232. break;
  4233. case BC_LEX_KEY_READ:
  4234. dbg_lex("%s:%d LEX_READ", __func__, __LINE__);
  4235. if (BC_PARSE_LEAF(prev, bin_last, rprn))
  4236. RETURN_STATUS(bc_error_bad_expression());
  4237. s = zbc_parse_read();
  4238. prev = XC_INST_READ;
  4239. get_token = true;
  4240. rprn = bin_last = incdec = false;
  4241. nexprs++;
  4242. break;
  4243. case BC_LEX_KEY_SCALE:
  4244. dbg_lex("%s:%d LEX_SCALE", __func__, __LINE__);
  4245. if (BC_PARSE_LEAF(prev, bin_last, rprn))
  4246. RETURN_STATUS(bc_error_bad_expression());
  4247. s = zbc_parse_scale(&prev, flags);
  4248. //get_token = false; - already is
  4249. rprn = bin_last = false;
  4250. nexprs++;
  4251. break;
  4252. default:
  4253. RETURN_STATUS(bc_error_bad_token());
  4254. }
  4255. if (s || G_interrupt) // error, or ^C: stop parsing
  4256. RETURN_STATUS(BC_STATUS_FAILURE);
  4257. if (get_token) {
  4258. s = zxc_lex_next();
  4259. if (s) RETURN_STATUS(s);
  4260. }
  4261. }
  4262. exit_loop:
  4263. while (p->ops.len > ops_bgn) {
  4264. BcLexType top = BC_PARSE_TOP_OP(p);
  4265. assign = (top >= BC_LEX_OP_ASSIGN_POWER && top <= BC_LEX_OP_ASSIGN);
  4266. if (top == BC_LEX_LPAREN || top == BC_LEX_RPAREN)
  4267. RETURN_STATUS(bc_error_bad_expression());
  4268. xc_parse_push(BC_TOKEN_2_INST(top));
  4269. nexprs -= (top != BC_LEX_OP_BOOL_NOT && top != XC_LEX_NEG);
  4270. bc_vec_pop(&p->ops);
  4271. }
  4272. if (prev == XC_INST_BOOL_NOT || nexprs != 1)
  4273. RETURN_STATUS(bc_error_bad_expression());
  4274. if (!(flags & BC_PARSE_REL) && nrelops) {
  4275. BcStatus s;
  4276. s = zbc_POSIX_does_not_allow("comparison operators outside if or loops");
  4277. if (s) RETURN_STATUS(s);
  4278. } else if ((flags & BC_PARSE_REL) && nrelops > 1) {
  4279. BcStatus s;
  4280. s = zbc_POSIX_requires("exactly one comparison operator per condition");
  4281. if (s) RETURN_STATUS(s);
  4282. }
  4283. if (flags & BC_PARSE_PRINT) {
  4284. if (paren_first || !assign)
  4285. xc_parse_push(XC_INST_PRINT);
  4286. xc_parse_push(XC_INST_POP);
  4287. }
  4288. dbg_lex_done("%s:%d done", __func__, __LINE__);
  4289. RETURN_STATUS(BC_STATUS_SUCCESS);
  4290. }
  4291. #define zbc_parse_expr(...) (zbc_parse_expr(__VA_ARGS__) COMMA_SUCCESS)
  4292. #endif // ENABLE_BC
  4293. #if ENABLE_DC
  4294. static BC_STATUS zdc_parse_register(void)
  4295. {
  4296. BcParse *p = &G.prs;
  4297. BcStatus s;
  4298. s = zxc_lex_next();
  4299. if (s) RETURN_STATUS(s);
  4300. if (p->lex != XC_LEX_NAME) RETURN_STATUS(bc_error_bad_token());
  4301. xc_parse_pushName(p->lex_strnumbuf.v);
  4302. RETURN_STATUS(s);
  4303. }
  4304. #define zdc_parse_register(...) (zdc_parse_register(__VA_ARGS__) COMMA_SUCCESS)
  4305. static void dc_parse_string(void)
  4306. {
  4307. BcParse *p = &G.prs;
  4308. char *str;
  4309. size_t len = G.prog.strs.len;
  4310. dbg_lex_enter("%s:%d entered", __func__, __LINE__);
  4311. str = xstrdup(p->lex_strnumbuf.v);
  4312. xc_parse_pushInst_and_Index(XC_INST_STR, len);
  4313. bc_vec_push(&G.prog.strs, &str);
  4314. // Add an empty function so that if zdc_program_execStr ever needs to
  4315. // parse the string into code (from the 'x' command) there's somewhere
  4316. // to store the bytecode.
  4317. xc_program_add_fn();
  4318. p->func = xc_program_func(p->fidx);
  4319. dbg_lex_done("%s:%d done", __func__, __LINE__);
  4320. }
  4321. static BC_STATUS zdc_parse_mem(uint8_t inst, bool name, bool store)
  4322. {
  4323. BcStatus s;
  4324. xc_parse_push(inst);
  4325. if (name) {
  4326. s = zdc_parse_register();
  4327. if (s) RETURN_STATUS(s);
  4328. }
  4329. if (store) {
  4330. xc_parse_push(DC_INST_SWAP);
  4331. xc_parse_push(XC_INST_ASSIGN);
  4332. xc_parse_push(XC_INST_POP);
  4333. }
  4334. RETURN_STATUS(BC_STATUS_SUCCESS);
  4335. }
  4336. #define zdc_parse_mem(...) (zdc_parse_mem(__VA_ARGS__) COMMA_SUCCESS)
  4337. static BC_STATUS zdc_parse_cond(uint8_t inst)
  4338. {
  4339. BcParse *p = &G.prs;
  4340. BcStatus s;
  4341. xc_parse_push(inst);
  4342. xc_parse_push(DC_INST_EXEC_COND);
  4343. s = zdc_parse_register();
  4344. if (s) RETURN_STATUS(s);
  4345. s = zxc_lex_next();
  4346. if (s) RETURN_STATUS(s);
  4347. // Note that 'else' part can not be on the next line:
  4348. // echo -e '[1p]sa [2p]sb 2 1>a eb' | dc - OK, prints "2"
  4349. // echo -e '[1p]sa [2p]sb 2 1>a\neb' | dc - parse error
  4350. if (p->lex == DC_LEX_ELSE) {
  4351. s = zdc_parse_register();
  4352. if (s) RETURN_STATUS(s);
  4353. s = zxc_lex_next();
  4354. } else {
  4355. xc_parse_push('\0');
  4356. }
  4357. RETURN_STATUS(s);
  4358. }
  4359. #define zdc_parse_cond(...) (zdc_parse_cond(__VA_ARGS__) COMMA_SUCCESS)
  4360. static BC_STATUS zdc_parse_token(BcLexType t)
  4361. {
  4362. BcStatus s;
  4363. uint8_t inst;
  4364. bool assign, get_token;
  4365. dbg_lex_enter("%s:%d entered", __func__, __LINE__);
  4366. s = BC_STATUS_SUCCESS;
  4367. get_token = true;
  4368. switch (t) {
  4369. case XC_LEX_OP_REL_EQ:
  4370. case XC_LEX_OP_REL_LE:
  4371. case XC_LEX_OP_REL_GE:
  4372. case XC_LEX_OP_REL_NE:
  4373. case XC_LEX_OP_REL_LT:
  4374. case XC_LEX_OP_REL_GT:
  4375. dbg_lex("%s:%d LEX_OP_REL_xyz", __func__, __LINE__);
  4376. s = zdc_parse_cond(t - XC_LEX_OP_REL_EQ + XC_INST_REL_EQ);
  4377. get_token = false;
  4378. break;
  4379. case DC_LEX_SCOLON:
  4380. case DC_LEX_COLON:
  4381. dbg_lex("%s:%d LEX_[S]COLON", __func__, __LINE__);
  4382. s = zdc_parse_mem(XC_INST_ARRAY_ELEM, true, t == DC_LEX_COLON);
  4383. break;
  4384. case XC_LEX_STR:
  4385. dbg_lex("%s:%d LEX_STR", __func__, __LINE__);
  4386. dc_parse_string();
  4387. break;
  4388. case XC_LEX_NEG:
  4389. dbg_lex("%s:%d LEX_NEG", __func__, __LINE__);
  4390. s = zxc_lex_next();
  4391. if (s) RETURN_STATUS(s);
  4392. if (G.prs.lex != XC_LEX_NUMBER)
  4393. RETURN_STATUS(bc_error_bad_token());
  4394. xc_parse_pushNUM();
  4395. xc_parse_push(XC_INST_NEG);
  4396. break;
  4397. case XC_LEX_NUMBER:
  4398. dbg_lex("%s:%d LEX_NUMBER", __func__, __LINE__);
  4399. xc_parse_pushNUM();
  4400. break;
  4401. case DC_LEX_READ:
  4402. dbg_lex("%s:%d LEX_KEY_READ", __func__, __LINE__);
  4403. xc_parse_push(XC_INST_READ);
  4404. break;
  4405. case DC_LEX_OP_ASSIGN:
  4406. case DC_LEX_STORE_PUSH:
  4407. dbg_lex("%s:%d LEX_OP_ASSIGN/STORE_PUSH", __func__, __LINE__);
  4408. assign = (t == DC_LEX_OP_ASSIGN);
  4409. inst = assign ? XC_INST_VAR : DC_INST_PUSH_TO_VAR;
  4410. s = zdc_parse_mem(inst, true, assign);
  4411. break;
  4412. case DC_LEX_LOAD:
  4413. case DC_LEX_LOAD_POP:
  4414. dbg_lex("%s:%d LEX_OP_LOAD[_POP]", __func__, __LINE__);
  4415. inst = t == DC_LEX_LOAD_POP ? DC_INST_PUSH_VAR : DC_INST_LOAD;
  4416. s = zdc_parse_mem(inst, true, false);
  4417. break;
  4418. case DC_LEX_STORE_IBASE:
  4419. case DC_LEX_STORE_SCALE:
  4420. case DC_LEX_STORE_OBASE:
  4421. dbg_lex("%s:%d LEX_OP_STORE_I/OBASE/SCALE", __func__, __LINE__);
  4422. inst = t - DC_LEX_STORE_IBASE + XC_INST_IBASE;
  4423. s = zdc_parse_mem(inst, false, true);
  4424. break;
  4425. default:
  4426. dbg_lex_done("%s:%d done (bad token)", __func__, __LINE__);
  4427. RETURN_STATUS(bc_error_bad_token());
  4428. }
  4429. if (!s && get_token) s = zxc_lex_next();
  4430. dbg_lex_done("%s:%d done", __func__, __LINE__);
  4431. RETURN_STATUS(s);
  4432. }
  4433. #define zdc_parse_token(...) (zdc_parse_token(__VA_ARGS__) COMMA_SUCCESS)
  4434. static BC_STATUS zdc_parse_expr(void)
  4435. {
  4436. BcParse *p = &G.prs;
  4437. int i;
  4438. if (p->lex == XC_LEX_NLINE)
  4439. RETURN_STATUS(zxc_lex_next());
  4440. i = (int)p->lex - (int)XC_LEX_OP_POWER;
  4441. if (i >= 0) {
  4442. BcInst inst = dc_LEX_to_INST[i];
  4443. if (inst != DC_INST_INVALID) {
  4444. xc_parse_push(inst);
  4445. RETURN_STATUS(zxc_lex_next());
  4446. }
  4447. }
  4448. RETURN_STATUS(zdc_parse_token(p->lex));
  4449. }
  4450. #define zdc_parse_expr(...) (zdc_parse_expr(__VA_ARGS__) COMMA_SUCCESS)
  4451. static BC_STATUS zdc_parse_exprs_until_eof(void)
  4452. {
  4453. BcParse *p = &G.prs;
  4454. dbg_lex_enter("%s:%d entered, p->lex:%d", __func__, __LINE__, p->lex);
  4455. while (p->lex != XC_LEX_EOF) {
  4456. BcStatus s = zdc_parse_expr();
  4457. if (s) RETURN_STATUS(s);
  4458. }
  4459. dbg_lex_done("%s:%d done", __func__, __LINE__);
  4460. RETURN_STATUS(BC_STATUS_SUCCESS);
  4461. }
  4462. #define zdc_parse_exprs_until_eof(...) (zdc_parse_exprs_until_eof(__VA_ARGS__) COMMA_SUCCESS)
  4463. #endif // ENABLE_DC
  4464. //
  4465. // Execution engine
  4466. //
  4467. #define BC_PROG_STR(n) (!(n)->num && !(n)->cap)
  4468. #define BC_PROG_NUM(r, n) \
  4469. ((r)->t != XC_RESULT_ARRAY && (r)->t != XC_RESULT_STR && !BC_PROG_STR(n))
  4470. #define STACK_HAS_MORE_THAN(s, n) ((s)->len > ((size_t)(n)))
  4471. #define STACK_HAS_EQUAL_OR_MORE_THAN(s, n) ((s)->len >= ((size_t)(n)))
  4472. static size_t xc_program_index(char *code, size_t *bgn)
  4473. {
  4474. unsigned char *bytes = (void*)(code + *bgn);
  4475. unsigned amt;
  4476. unsigned i;
  4477. size_t res;
  4478. amt = *bytes++;
  4479. if (amt < SMALL_INDEX_LIMIT) {
  4480. *bgn += 1;
  4481. return amt;
  4482. }
  4483. amt -= (SMALL_INDEX_LIMIT - 1); // amt is 1 or more here
  4484. *bgn += amt + 1;
  4485. res = 0;
  4486. i = 0;
  4487. do {
  4488. res |= (size_t)(*bytes++) << i;
  4489. i += 8;
  4490. } while (--amt != 0);
  4491. return res;
  4492. }
  4493. static char *xc_program_name(char *code, size_t *bgn)
  4494. {
  4495. code += *bgn;
  4496. *bgn += strlen(code) + 1;
  4497. return xstrdup(code);
  4498. }
  4499. static BcVec* xc_program_dereference(BcVec *vec)
  4500. {
  4501. BcVec *v;
  4502. size_t vidx, nidx, i = 0;
  4503. //assert(vec->size == sizeof(uint8_t));
  4504. vidx = xc_program_index(vec->v, &i);
  4505. nidx = xc_program_index(vec->v, &i);
  4506. v = bc_vec_item(&G.prog.arrs, vidx);
  4507. v = bc_vec_item(v, nidx);
  4508. //assert(v->size != sizeof(uint8_t));
  4509. return v;
  4510. }
  4511. static BcVec* xc_program_search(char *id, BcType type)
  4512. {
  4513. BcId e, *ptr;
  4514. BcVec *v, *map;
  4515. size_t i;
  4516. int new;
  4517. bool var = (type == BC_TYPE_VAR);
  4518. v = var ? &G.prog.vars : &G.prog.arrs;
  4519. map = var ? &G.prog.var_map : &G.prog.arr_map;
  4520. e.name = id;
  4521. e.idx = v->len;
  4522. new = bc_map_insert(map, &e, &i); // 1 if insertion was successful
  4523. if (new) {
  4524. BcVec v2;
  4525. bc_array_init(&v2, var);
  4526. bc_vec_push(v, &v2);
  4527. }
  4528. ptr = bc_vec_item(map, i);
  4529. if (new) ptr->name = xstrdup(e.name);
  4530. return bc_vec_item(v, ptr->idx);
  4531. }
  4532. // 'num' need not be initialized on entry
  4533. static BC_STATUS zxc_program_num(BcResult *r, BcNum **num)
  4534. {
  4535. switch (r->t) {
  4536. case XC_RESULT_STR:
  4537. case XC_RESULT_TEMP:
  4538. IF_BC(case BC_RESULT_VOID:)
  4539. case XC_RESULT_IBASE:
  4540. case XC_RESULT_SCALE:
  4541. case XC_RESULT_OBASE:
  4542. *num = &r->d.n;
  4543. break;
  4544. case XC_RESULT_CONSTANT: {
  4545. BcStatus s;
  4546. char *str;
  4547. size_t len;
  4548. str = *xc_program_const(r->d.id.idx);
  4549. len = strlen(str);
  4550. bc_num_init(&r->d.n, len);
  4551. s = zxc_num_parse(&r->d.n, str, G.prog.ib_t);
  4552. if (s) {
  4553. bc_num_free(&r->d.n);
  4554. RETURN_STATUS(s);
  4555. }
  4556. *num = &r->d.n;
  4557. r->t = XC_RESULT_TEMP;
  4558. break;
  4559. }
  4560. case XC_RESULT_VAR:
  4561. case XC_RESULT_ARRAY:
  4562. case XC_RESULT_ARRAY_ELEM: {
  4563. BcType type = (r->t == XC_RESULT_VAR) ? BC_TYPE_VAR : BC_TYPE_ARRAY;
  4564. BcVec *v = xc_program_search(r->d.id.name, type);
  4565. void *p = bc_vec_top(v);
  4566. if (r->t == XC_RESULT_ARRAY_ELEM) {
  4567. size_t idx = r->d.id.idx;
  4568. v = p;
  4569. if (v->size == sizeof(uint8_t))
  4570. v = xc_program_dereference(v);
  4571. //assert(v->size == sizeof(BcNum));
  4572. if (v->len <= idx)
  4573. bc_array_expand(v, idx + 1);
  4574. *num = bc_vec_item(v, idx);
  4575. } else {
  4576. *num = p;
  4577. }
  4578. break;
  4579. }
  4580. #if ENABLE_BC
  4581. case BC_RESULT_LAST:
  4582. *num = &G.prog.last;
  4583. break;
  4584. case BC_RESULT_ONE:
  4585. *num = &G.prog.one;
  4586. break;
  4587. #endif
  4588. #if SANITY_CHECKS
  4589. default:
  4590. // Testing the theory that dc does not reach LAST/ONE
  4591. bb_error_msg_and_die("BUG:%d", r->t);
  4592. #endif
  4593. }
  4594. RETURN_STATUS(BC_STATUS_SUCCESS);
  4595. }
  4596. #define zxc_program_num(...) (zxc_program_num(__VA_ARGS__) COMMA_SUCCESS)
  4597. static BC_STATUS zxc_program_binOpPrep(BcResult **l, BcNum **ln,
  4598. BcResult **r, BcNum **rn, bool assign)
  4599. {
  4600. BcStatus s;
  4601. BcResultType lt, rt;
  4602. if (!STACK_HAS_MORE_THAN(&G.prog.results, 1))
  4603. RETURN_STATUS(bc_error_stack_has_too_few_elements());
  4604. *r = bc_vec_item_rev(&G.prog.results, 0);
  4605. *l = bc_vec_item_rev(&G.prog.results, 1);
  4606. s = zxc_program_num(*l, ln);
  4607. if (s) RETURN_STATUS(s);
  4608. s = zxc_program_num(*r, rn);
  4609. if (s) RETURN_STATUS(s);
  4610. lt = (*l)->t;
  4611. rt = (*r)->t;
  4612. // We run this again under these conditions in case any vector has been
  4613. // reallocated out from under the BcNums or arrays we had.
  4614. if (lt == rt && (lt == XC_RESULT_VAR || lt == XC_RESULT_ARRAY_ELEM)) {
  4615. s = zxc_program_num(*l, ln);
  4616. if (s) RETURN_STATUS(s);
  4617. }
  4618. if (!BC_PROG_NUM((*l), (*ln)) && (!assign || (*l)->t != XC_RESULT_VAR))
  4619. RETURN_STATUS(bc_error_variable_is_wrong_type());
  4620. if (!assign && !BC_PROG_NUM((*r), (*ln)))
  4621. RETURN_STATUS(bc_error_variable_is_wrong_type());
  4622. RETURN_STATUS(s);
  4623. }
  4624. #define zxc_program_binOpPrep(...) (zxc_program_binOpPrep(__VA_ARGS__) COMMA_SUCCESS)
  4625. static void xc_program_binOpRetire(BcResult *r)
  4626. {
  4627. r->t = XC_RESULT_TEMP;
  4628. bc_vec_pop(&G.prog.results);
  4629. bc_result_pop_and_push(r);
  4630. }
  4631. // Note: *r and *n need not be initialized by caller
  4632. static BC_STATUS zxc_program_prep(BcResult **r, BcNum **n)
  4633. {
  4634. BcStatus s;
  4635. if (!STACK_HAS_MORE_THAN(&G.prog.results, 0))
  4636. RETURN_STATUS(bc_error_stack_has_too_few_elements());
  4637. *r = bc_vec_top(&G.prog.results);
  4638. s = zxc_program_num(*r, n);
  4639. if (s) RETURN_STATUS(s);
  4640. if (!BC_PROG_NUM((*r), (*n)))
  4641. RETURN_STATUS(bc_error_variable_is_wrong_type());
  4642. RETURN_STATUS(s);
  4643. }
  4644. #define zxc_program_prep(...) (zxc_program_prep(__VA_ARGS__) COMMA_SUCCESS)
  4645. static void xc_program_retire(BcResult *r, BcResultType t)
  4646. {
  4647. r->t = t;
  4648. bc_result_pop_and_push(r);
  4649. }
  4650. static BC_STATUS zxc_program_op(char inst)
  4651. {
  4652. BcStatus s;
  4653. BcResult *opd1, *opd2, res;
  4654. BcNum *n1, *n2;
  4655. s = zxc_program_binOpPrep(&opd1, &n1, &opd2, &n2, false);
  4656. if (s) RETURN_STATUS(s);
  4657. bc_num_init_DEF_SIZE(&res.d.n);
  4658. s = BC_STATUS_SUCCESS;
  4659. IF_ERROR_RETURN_POSSIBLE(s =) zxc_program_ops[inst - XC_INST_POWER](n1, n2, &res.d.n, G.prog.scale);
  4660. if (s) goto err;
  4661. xc_program_binOpRetire(&res);
  4662. RETURN_STATUS(s);
  4663. err:
  4664. bc_num_free(&res.d.n);
  4665. RETURN_STATUS(s);
  4666. }
  4667. #define zxc_program_op(...) (zxc_program_op(__VA_ARGS__) COMMA_SUCCESS)
  4668. static BC_STATUS zxc_program_read(void)
  4669. {
  4670. BcStatus s;
  4671. BcParse sv_parse;
  4672. BcVec buf;
  4673. BcInstPtr ip;
  4674. BcFunc *f;
  4675. bc_char_vec_init(&buf);
  4676. xc_read_line(&buf, stdin);
  4677. f = xc_program_func(BC_PROG_READ);
  4678. bc_vec_pop_all(&f->code);
  4679. sv_parse = G.prs; // struct copy
  4680. xc_parse_create(BC_PROG_READ);
  4681. //G.err_line = G.prs.lex_line = 1; - not needed, error line info is not printed for read()
  4682. s = zxc_parse_text_init(buf.v);
  4683. if (s) goto exec_err;
  4684. if (IS_BC) {
  4685. IF_BC(s = zbc_parse_expr(0));
  4686. } else {
  4687. IF_DC(s = zdc_parse_exprs_until_eof());
  4688. }
  4689. if (s) goto exec_err;
  4690. if (G.prs.lex != XC_LEX_NLINE && G.prs.lex != XC_LEX_EOF) {
  4691. s = bc_error_at("bad read() expression");
  4692. goto exec_err;
  4693. }
  4694. xc_parse_push(XC_INST_RET);
  4695. ip.func = BC_PROG_READ;
  4696. ip.inst_idx = 0;
  4697. bc_vec_push(&G.prog.exestack, &ip);
  4698. exec_err:
  4699. xc_parse_free();
  4700. G.prs = sv_parse; // struct copy
  4701. bc_vec_free(&buf);
  4702. RETURN_STATUS(s);
  4703. }
  4704. #define zxc_program_read(...) (zxc_program_read(__VA_ARGS__) COMMA_SUCCESS)
  4705. static void xc_program_printString(const char *str)
  4706. {
  4707. #if ENABLE_DC
  4708. if (!str[0] && IS_DC) {
  4709. // Example: echo '[]ap' | dc
  4710. // should print two bytes: 0x00, 0x0A
  4711. bb_putchar('\0');
  4712. return;
  4713. }
  4714. #endif
  4715. while (*str) {
  4716. char c = *str++;
  4717. if (c == '\\') {
  4718. static const char esc[] ALIGN1 = "nabfrt""e\\";
  4719. char *n;
  4720. c = *str++;
  4721. n = strchr(esc, c); // note: if c is NUL, n = \0 at end of esc
  4722. if (!n || !c) {
  4723. // Just print the backslash and following character
  4724. bb_putchar('\\');
  4725. ++G.prog.nchars;
  4726. // But if we're at the end of the string, stop
  4727. if (!c) break;
  4728. } else {
  4729. if (n - esc == 0) // "\n" ?
  4730. G.prog.nchars = SIZE_MAX;
  4731. c = "\n\a\b\f\r\t""\\\\""\\"[n - esc];
  4732. // n a b f r t e \ \<end of line>
  4733. }
  4734. }
  4735. putchar(c);
  4736. ++G.prog.nchars;
  4737. }
  4738. }
  4739. static void bc_num_printNewline(void)
  4740. {
  4741. if (G.prog.nchars == G.prog.len - 1) {
  4742. bb_putchar('\\');
  4743. bb_putchar('\n');
  4744. G.prog.nchars = 0;
  4745. }
  4746. }
  4747. #if ENABLE_DC
  4748. static FAST_FUNC void dc_num_printChar(size_t num, size_t width, bool radix)
  4749. {
  4750. (void) radix;
  4751. bb_putchar((char) num);
  4752. G.prog.nchars += width;
  4753. }
  4754. #endif
  4755. static FAST_FUNC void bc_num_printDigits(size_t num, size_t width, bool radix)
  4756. {
  4757. size_t exp, pow;
  4758. bc_num_printNewline();
  4759. bb_putchar(radix ? '.' : ' ');
  4760. ++G.prog.nchars;
  4761. bc_num_printNewline();
  4762. for (exp = 0, pow = 1; exp < width - 1; ++exp, pow *= 10)
  4763. continue;
  4764. for (exp = 0; exp < width; pow /= 10, ++G.prog.nchars, ++exp) {
  4765. size_t dig;
  4766. bc_num_printNewline();
  4767. dig = num / pow;
  4768. num -= dig * pow;
  4769. bb_putchar(((char) dig) + '0');
  4770. }
  4771. }
  4772. static FAST_FUNC void bc_num_printHex(size_t num, size_t width, bool radix)
  4773. {
  4774. if (radix) {
  4775. bc_num_printNewline();
  4776. bb_putchar('.');
  4777. G.prog.nchars++;
  4778. }
  4779. bc_num_printNewline();
  4780. bb_putchar(bb_hexdigits_upcase[num]);
  4781. G.prog.nchars += width;
  4782. }
  4783. static void bc_num_printDecimal(BcNum *n)
  4784. {
  4785. size_t i, rdx = n->rdx - 1;
  4786. if (n->neg) {
  4787. bb_putchar('-');
  4788. G.prog.nchars++;
  4789. }
  4790. for (i = n->len - 1; i < n->len; --i)
  4791. bc_num_printHex((size_t) n->num[i], 1, i == rdx);
  4792. }
  4793. typedef void (*BcNumDigitOp)(size_t, size_t, bool) FAST_FUNC;
  4794. static BC_STATUS zxc_num_printNum(BcNum *n, unsigned base_t, size_t width, BcNumDigitOp print)
  4795. {
  4796. BcStatus s;
  4797. BcVec stack;
  4798. BcNum base;
  4799. BcDig base_digs[ULONG_NUM_BUFSIZE];
  4800. BcNum intp, fracp, digit, frac_len;
  4801. unsigned long dig, *ptr;
  4802. size_t i;
  4803. bool radix;
  4804. if (n->len == 0) {
  4805. print(0, width, false);
  4806. RETURN_STATUS(BC_STATUS_SUCCESS);
  4807. }
  4808. bc_vec_init(&stack, sizeof(long), NULL);
  4809. bc_num_init(&intp, n->len);
  4810. bc_num_init(&fracp, n->rdx);
  4811. bc_num_init(&digit, width);
  4812. bc_num_init(&frac_len, BC_NUM_INT(n));
  4813. bc_num_copy(&intp, n);
  4814. bc_num_one(&frac_len);
  4815. base.cap = ARRAY_SIZE(base_digs);
  4816. base.num = base_digs;
  4817. bc_num_ulong2num(&base, base_t);
  4818. bc_num_truncate(&intp, intp.rdx);
  4819. s = zbc_num_sub(n, &intp, &fracp, 0);
  4820. if (s) goto err;
  4821. while (intp.len != 0) {
  4822. s = zbc_num_divmod(&intp, &base, &intp, &digit, 0);
  4823. if (s) goto err;
  4824. s = zbc_num_ulong(&digit, &dig);
  4825. if (s) goto err;
  4826. bc_vec_push(&stack, &dig);
  4827. }
  4828. for (i = 0; i < stack.len; ++i) {
  4829. ptr = bc_vec_item_rev(&stack, i);
  4830. print(*ptr, width, false);
  4831. }
  4832. if (!n->rdx) goto err;
  4833. for (radix = true; frac_len.len <= n->rdx; radix = false) {
  4834. s = zbc_num_mul(&fracp, &base, &fracp, n->rdx);
  4835. if (s) goto err;
  4836. s = zbc_num_ulong(&fracp, &dig);
  4837. if (s) goto err;
  4838. bc_num_ulong2num(&intp, dig);
  4839. s = zbc_num_sub(&fracp, &intp, &fracp, 0);
  4840. if (s) goto err;
  4841. print(dig, width, radix);
  4842. s = zbc_num_mul(&frac_len, &base, &frac_len, 0);
  4843. if (s) goto err;
  4844. }
  4845. err:
  4846. bc_num_free(&frac_len);
  4847. bc_num_free(&digit);
  4848. bc_num_free(&fracp);
  4849. bc_num_free(&intp);
  4850. bc_vec_free(&stack);
  4851. RETURN_STATUS(s);
  4852. }
  4853. #define zxc_num_printNum(...) (zxc_num_printNum(__VA_ARGS__) COMMA_SUCCESS)
  4854. static BC_STATUS zxc_num_printBase(BcNum *n)
  4855. {
  4856. BcStatus s;
  4857. size_t width;
  4858. BcNumDigitOp print;
  4859. bool neg = n->neg;
  4860. if (neg) {
  4861. bb_putchar('-');
  4862. G.prog.nchars++;
  4863. }
  4864. n->neg = false;
  4865. if (G.prog.ob_t <= 16) {
  4866. width = 1;
  4867. print = bc_num_printHex;
  4868. } else {
  4869. unsigned i = G.prog.ob_t - 1;
  4870. width = 0;
  4871. for (;;) {
  4872. width++;
  4873. i /= 10;
  4874. if (i == 0)
  4875. break;
  4876. }
  4877. print = bc_num_printDigits;
  4878. }
  4879. s = zxc_num_printNum(n, G.prog.ob_t, width, print);
  4880. n->neg = neg;
  4881. RETURN_STATUS(s);
  4882. }
  4883. #define zxc_num_printBase(...) (zxc_num_printBase(__VA_ARGS__) COMMA_SUCCESS)
  4884. static BC_STATUS zxc_num_print(BcNum *n, bool newline)
  4885. {
  4886. BcStatus s = BC_STATUS_SUCCESS;
  4887. bc_num_printNewline();
  4888. if (n->len == 0) {
  4889. bb_putchar('0');
  4890. ++G.prog.nchars;
  4891. } else if (G.prog.ob_t == 10)
  4892. bc_num_printDecimal(n);
  4893. else
  4894. s = zxc_num_printBase(n);
  4895. if (newline) {
  4896. bb_putchar('\n');
  4897. G.prog.nchars = 0;
  4898. }
  4899. RETURN_STATUS(s);
  4900. }
  4901. #define zxc_num_print(...) (zxc_num_print(__VA_ARGS__) COMMA_SUCCESS)
  4902. #if !ENABLE_DC
  4903. // for bc, idx is always 0
  4904. #define xc_program_print(inst, idx) \
  4905. xc_program_print(inst)
  4906. #endif
  4907. static BC_STATUS xc_program_print(char inst, size_t idx)
  4908. {
  4909. BcStatus s;
  4910. BcResult *r;
  4911. BcNum *num;
  4912. IF_NOT_DC(size_t idx = 0);
  4913. if (!STACK_HAS_MORE_THAN(&G.prog.results, idx))
  4914. RETURN_STATUS(bc_error_stack_has_too_few_elements());
  4915. r = bc_vec_item_rev(&G.prog.results, idx);
  4916. #if ENABLE_BC
  4917. if (inst == XC_INST_PRINT && r->t == BC_RESULT_VOID)
  4918. // void function's result on stack, ignore
  4919. RETURN_STATUS(BC_STATUS_SUCCESS);
  4920. #endif
  4921. s = zxc_program_num(r, &num);
  4922. if (s) RETURN_STATUS(s);
  4923. if (BC_PROG_NUM(r, num)) {
  4924. s = zxc_num_print(num, /*newline:*/ inst == XC_INST_PRINT);
  4925. #if ENABLE_BC
  4926. if (!s && IS_BC) bc_num_copy(&G.prog.last, num);
  4927. #endif
  4928. } else {
  4929. char *str;
  4930. idx = (r->t == XC_RESULT_STR) ? r->d.id.idx : num->rdx;
  4931. str = *xc_program_str(idx);
  4932. if (inst == XC_INST_PRINT_STR) {
  4933. char *nl;
  4934. G.prog.nchars += printf("%s", str);
  4935. nl = strrchr(str, '\n');
  4936. if (nl)
  4937. G.prog.nchars = strlen(nl + 1);
  4938. } else {
  4939. xc_program_printString(str);
  4940. if (inst == XC_INST_PRINT)
  4941. bb_putchar('\n');
  4942. }
  4943. }
  4944. if (!s && inst != XC_INST_PRINT) bc_vec_pop(&G.prog.results);
  4945. RETURN_STATUS(s);
  4946. }
  4947. #define zxc_program_print(...) (xc_program_print(__VA_ARGS__) COMMA_SUCCESS)
  4948. static BC_STATUS zxc_program_negate(void)
  4949. {
  4950. BcStatus s;
  4951. BcResult res, *ptr;
  4952. BcNum *num;
  4953. s = zxc_program_prep(&ptr, &num);
  4954. if (s) RETURN_STATUS(s);
  4955. bc_num_init(&res.d.n, num->len);
  4956. bc_num_copy(&res.d.n, num);
  4957. if (res.d.n.len) res.d.n.neg = !res.d.n.neg;
  4958. xc_program_retire(&res, XC_RESULT_TEMP);
  4959. RETURN_STATUS(s);
  4960. }
  4961. #define zxc_program_negate(...) (zxc_program_negate(__VA_ARGS__) COMMA_SUCCESS)
  4962. static BC_STATUS zxc_program_logical(char inst)
  4963. {
  4964. BcStatus s;
  4965. BcResult *opd1, *opd2, res;
  4966. BcNum *n1, *n2;
  4967. ssize_t cond;
  4968. s = zxc_program_binOpPrep(&opd1, &n1, &opd2, &n2, false);
  4969. if (s) RETURN_STATUS(s);
  4970. bc_num_init_DEF_SIZE(&res.d.n);
  4971. if (inst == XC_INST_BOOL_AND)
  4972. cond = bc_num_cmp(n1, &G.prog.zero) && bc_num_cmp(n2, &G.prog.zero);
  4973. else if (inst == XC_INST_BOOL_OR)
  4974. cond = bc_num_cmp(n1, &G.prog.zero) || bc_num_cmp(n2, &G.prog.zero);
  4975. else {
  4976. cond = bc_num_cmp(n1, n2);
  4977. switch (inst) {
  4978. case XC_INST_REL_EQ:
  4979. cond = (cond == 0);
  4980. break;
  4981. case XC_INST_REL_LE:
  4982. cond = (cond <= 0);
  4983. break;
  4984. case XC_INST_REL_GE:
  4985. cond = (cond >= 0);
  4986. break;
  4987. case XC_INST_REL_LT:
  4988. cond = (cond < 0);
  4989. break;
  4990. case XC_INST_REL_GT:
  4991. cond = (cond > 0);
  4992. break;
  4993. default: // = case XC_INST_REL_NE:
  4994. //cond = (cond != 0); - not needed
  4995. break;
  4996. }
  4997. }
  4998. if (cond) bc_num_one(&res.d.n);
  4999. //else bc_num_zero(&res.d.n); - already is
  5000. xc_program_binOpRetire(&res);
  5001. RETURN_STATUS(s);
  5002. }
  5003. #define zxc_program_logical(...) (zxc_program_logical(__VA_ARGS__) COMMA_SUCCESS)
  5004. #if ENABLE_DC
  5005. static BC_STATUS zdc_program_assignStr(BcResult *r, BcVec *v, bool push)
  5006. {
  5007. BcNum n2;
  5008. BcResult res;
  5009. memset(&n2, 0, sizeof(BcNum));
  5010. n2.rdx = res.d.id.idx = r->d.id.idx;
  5011. res.t = XC_RESULT_STR;
  5012. if (!push) {
  5013. if (!STACK_HAS_MORE_THAN(&G.prog.results, 1))
  5014. RETURN_STATUS(bc_error_stack_has_too_few_elements());
  5015. bc_vec_pop(v);
  5016. bc_vec_pop(&G.prog.results);
  5017. }
  5018. bc_result_pop_and_push(&res);
  5019. bc_vec_push(v, &n2);
  5020. RETURN_STATUS(BC_STATUS_SUCCESS);
  5021. }
  5022. #define zdc_program_assignStr(...) (zdc_program_assignStr(__VA_ARGS__) COMMA_SUCCESS)
  5023. #endif // ENABLE_DC
  5024. static BC_STATUS zxc_program_popResultAndCopyToVar(char *name, BcType t)
  5025. {
  5026. BcStatus s;
  5027. BcResult *ptr, r;
  5028. BcVec *vec;
  5029. BcNum *n;
  5030. bool var = (t == BC_TYPE_VAR);
  5031. if (!STACK_HAS_MORE_THAN(&G.prog.results, 0))
  5032. RETURN_STATUS(bc_error_stack_has_too_few_elements());
  5033. ptr = bc_vec_top(&G.prog.results);
  5034. if ((ptr->t == XC_RESULT_ARRAY) == var)
  5035. RETURN_STATUS(bc_error_variable_is_wrong_type());
  5036. vec = xc_program_search(name, t);
  5037. #if ENABLE_DC
  5038. if (ptr->t == XC_RESULT_STR) {
  5039. if (!var)
  5040. RETURN_STATUS(bc_error_variable_is_wrong_type());
  5041. RETURN_STATUS(zdc_program_assignStr(ptr, vec, true));
  5042. }
  5043. #endif
  5044. s = zxc_program_num(ptr, &n);
  5045. if (s) RETURN_STATUS(s);
  5046. // Do this once more to make sure that pointers were not invalidated.
  5047. vec = xc_program_search(name, t);
  5048. if (var) {
  5049. bc_num_init_DEF_SIZE(&r.d.n);
  5050. bc_num_copy(&r.d.n, n);
  5051. } else {
  5052. BcVec *v = (BcVec*) n;
  5053. bool ref, ref_size;
  5054. ref = (v->size == sizeof(BcVec) && t != BC_TYPE_ARRAY);
  5055. ref_size = (v->size == sizeof(uint8_t));
  5056. if (ref || (ref_size && t == BC_TYPE_REF)) {
  5057. bc_vec_init(&r.d.v, sizeof(uint8_t), NULL);
  5058. if (ref) {
  5059. size_t vidx, idx;
  5060. BcId id;
  5061. id.name = ptr->d.id.name;
  5062. v = xc_program_search(ptr->d.id.name, BC_TYPE_REF);
  5063. // Make sure the pointer was not invalidated.
  5064. vec = xc_program_search(name, t);
  5065. vidx = bc_map_find_exact(&G.prog.arr_map, &id);
  5066. //assert(vidx != BC_VEC_INVALID_IDX);
  5067. vidx = ((BcId*) bc_vec_item(&G.prog.arr_map, vidx))->idx;
  5068. idx = v->len - 1;
  5069. bc_vec_pushIndex(&r.d.v, vidx);
  5070. bc_vec_pushIndex(&r.d.v, idx);
  5071. }
  5072. // If we get here, we are copying a ref to a ref.
  5073. else bc_vec_npush(&r.d.v, v->len, v->v);
  5074. // We need to return early.
  5075. goto ret;
  5076. }
  5077. if (ref_size && t != BC_TYPE_REF)
  5078. v = xc_program_dereference(v);
  5079. bc_array_init(&r.d.v, true);
  5080. bc_array_copy(&r.d.v, v);
  5081. }
  5082. ret:
  5083. bc_vec_push(vec, &r.d);
  5084. bc_vec_pop(&G.prog.results);
  5085. RETURN_STATUS(s);
  5086. }
  5087. #define zxc_program_popResultAndCopyToVar(...) (zxc_program_popResultAndCopyToVar(__VA_ARGS__) COMMA_SUCCESS)
  5088. static BC_STATUS zxc_program_assign(char inst)
  5089. {
  5090. BcStatus s;
  5091. BcResult *left, *right, res;
  5092. BcNum *l, *r;
  5093. bool assign = (inst == XC_INST_ASSIGN);
  5094. bool ib, sc;
  5095. s = zxc_program_binOpPrep(&left, &l, &right, &r, assign);
  5096. if (s) RETURN_STATUS(s);
  5097. ib = left->t == XC_RESULT_IBASE;
  5098. sc = left->t == XC_RESULT_SCALE;
  5099. #if ENABLE_DC
  5100. if (right->t == XC_RESULT_STR) {
  5101. BcVec *v;
  5102. if (left->t != XC_RESULT_VAR)
  5103. RETURN_STATUS(bc_error_variable_is_wrong_type());
  5104. v = xc_program_search(left->d.id.name, BC_TYPE_VAR);
  5105. RETURN_STATUS(zdc_program_assignStr(right, v, false));
  5106. }
  5107. #endif
  5108. if (left->t == XC_RESULT_CONSTANT
  5109. || left->t == XC_RESULT_TEMP
  5110. IF_BC(|| left->t == BC_RESULT_VOID)
  5111. ) {
  5112. RETURN_STATUS(bc_error_bad_assignment());
  5113. }
  5114. #if ENABLE_BC
  5115. if (assign)
  5116. bc_num_copy(l, r);
  5117. else {
  5118. s = BC_STATUS_SUCCESS;
  5119. IF_ERROR_RETURN_POSSIBLE(s =) zxc_program_ops[inst - BC_INST_ASSIGN_POWER](l, r, l, G.prog.scale);
  5120. }
  5121. if (s) RETURN_STATUS(s);
  5122. #else
  5123. bc_num_copy(l, r);
  5124. #endif
  5125. if (ib || sc || left->t == XC_RESULT_OBASE) {
  5126. static const char *const msg[] = {
  5127. "bad ibase; must be [2,16]", //XC_RESULT_IBASE
  5128. "bad obase; must be [2,"BC_MAX_OBASE_STR"]", //XC_RESULT_OBASE
  5129. "bad scale; must be [0,"BC_MAX_SCALE_STR"]", //XC_RESULT_SCALE
  5130. };
  5131. size_t *ptr;
  5132. size_t max;
  5133. unsigned long val;
  5134. s = zbc_num_ulong(l, &val);
  5135. if (s) RETURN_STATUS(s);
  5136. s = left->t - XC_RESULT_IBASE;
  5137. if (sc) {
  5138. max = BC_MAX_SCALE;
  5139. ptr = &G.prog.scale;
  5140. } else {
  5141. if (val < 2)
  5142. RETURN_STATUS(bc_error(msg[s]));
  5143. max = ib ? BC_NUM_MAX_IBASE : BC_MAX_OBASE;
  5144. ptr = ib ? &G.prog.ib_t : &G.prog.ob_t;
  5145. }
  5146. if (val > max)
  5147. RETURN_STATUS(bc_error(msg[s]));
  5148. *ptr = (size_t) val;
  5149. s = BC_STATUS_SUCCESS;
  5150. }
  5151. bc_num_init(&res.d.n, l->len);
  5152. bc_num_copy(&res.d.n, l);
  5153. xc_program_binOpRetire(&res);
  5154. RETURN_STATUS(s);
  5155. }
  5156. #define zxc_program_assign(...) (zxc_program_assign(__VA_ARGS__) COMMA_SUCCESS)
  5157. #if !ENABLE_DC
  5158. #define xc_program_pushVar(code, bgn, pop, copy) \
  5159. xc_program_pushVar(code, bgn)
  5160. // for bc, 'pop' and 'copy' are always false
  5161. #endif
  5162. static BC_STATUS xc_program_pushVar(char *code, size_t *bgn,
  5163. bool pop, bool copy)
  5164. {
  5165. BcResult r;
  5166. char *name = xc_program_name(code, bgn);
  5167. r.t = XC_RESULT_VAR;
  5168. r.d.id.name = name;
  5169. #if ENABLE_DC
  5170. if (pop || copy) {
  5171. BcVec *v = xc_program_search(name, BC_TYPE_VAR);
  5172. BcNum *num = bc_vec_top(v);
  5173. free(name);
  5174. if (!STACK_HAS_MORE_THAN(v, 1 - copy)) {
  5175. RETURN_STATUS(bc_error_stack_has_too_few_elements());
  5176. }
  5177. if (!BC_PROG_STR(num)) {
  5178. r.t = XC_RESULT_TEMP;
  5179. bc_num_init_DEF_SIZE(&r.d.n);
  5180. bc_num_copy(&r.d.n, num);
  5181. } else {
  5182. r.t = XC_RESULT_STR;
  5183. r.d.id.idx = num->rdx;
  5184. }
  5185. if (!copy) bc_vec_pop(v);
  5186. }
  5187. #endif // ENABLE_DC
  5188. bc_vec_push(&G.prog.results, &r);
  5189. RETURN_STATUS(BC_STATUS_SUCCESS);
  5190. }
  5191. #define zxc_program_pushVar(...) (xc_program_pushVar(__VA_ARGS__) COMMA_SUCCESS)
  5192. static BC_STATUS zbc_program_pushArray(char *code, size_t *bgn, char inst)
  5193. {
  5194. BcStatus s = BC_STATUS_SUCCESS;
  5195. BcResult r;
  5196. BcNum *num;
  5197. r.d.id.name = xc_program_name(code, bgn);
  5198. if (inst == XC_INST_ARRAY) {
  5199. r.t = XC_RESULT_ARRAY;
  5200. bc_vec_push(&G.prog.results, &r);
  5201. } else {
  5202. BcResult *operand;
  5203. unsigned long temp;
  5204. s = zxc_program_prep(&operand, &num);
  5205. if (s) goto err;
  5206. s = zbc_num_ulong(num, &temp);
  5207. if (s) goto err;
  5208. if (temp > BC_MAX_DIM) {
  5209. s = bc_error("array too long; must be [1,"BC_MAX_DIM_STR"]");
  5210. goto err;
  5211. }
  5212. r.d.id.idx = (size_t) temp;
  5213. xc_program_retire(&r, XC_RESULT_ARRAY_ELEM);
  5214. }
  5215. err:
  5216. if (s) free(r.d.id.name);
  5217. RETURN_STATUS(s);
  5218. }
  5219. #define zbc_program_pushArray(...) (zbc_program_pushArray(__VA_ARGS__) COMMA_SUCCESS)
  5220. #if ENABLE_BC
  5221. static BC_STATUS zbc_program_incdec(char inst)
  5222. {
  5223. BcStatus s;
  5224. BcResult *ptr, res, copy;
  5225. BcNum *num;
  5226. char inst2 = inst;
  5227. s = zxc_program_prep(&ptr, &num);
  5228. if (s) RETURN_STATUS(s);
  5229. if (inst == BC_INST_INC_POST || inst == BC_INST_DEC_POST) {
  5230. copy.t = XC_RESULT_TEMP;
  5231. bc_num_init(&copy.d.n, num->len);
  5232. bc_num_copy(&copy.d.n, num);
  5233. }
  5234. res.t = BC_RESULT_ONE;
  5235. inst = (inst == BC_INST_INC_PRE || inst == BC_INST_INC_POST)
  5236. ? BC_INST_ASSIGN_PLUS
  5237. : BC_INST_ASSIGN_MINUS;
  5238. bc_vec_push(&G.prog.results, &res);
  5239. s = zxc_program_assign(inst);
  5240. if (s) RETURN_STATUS(s);
  5241. if (inst2 == BC_INST_INC_POST || inst2 == BC_INST_DEC_POST) {
  5242. bc_result_pop_and_push(&copy);
  5243. }
  5244. RETURN_STATUS(s);
  5245. }
  5246. #define zbc_program_incdec(...) (zbc_program_incdec(__VA_ARGS__) COMMA_SUCCESS)
  5247. static BC_STATUS zbc_program_call(char *code, size_t *idx)
  5248. {
  5249. BcInstPtr ip;
  5250. size_t i, nparams;
  5251. BcId *a;
  5252. BcFunc *func;
  5253. nparams = xc_program_index(code, idx);
  5254. ip.func = xc_program_index(code, idx);
  5255. func = xc_program_func(ip.func);
  5256. if (func->code.len == 0) {
  5257. RETURN_STATUS(bc_error("undefined function"));
  5258. }
  5259. if (nparams != func->nparams) {
  5260. RETURN_STATUS(bc_error_fmt("function has %u parameters, but called with %u", func->nparams, nparams));
  5261. }
  5262. ip.inst_idx = 0;
  5263. for (i = 0; i < nparams; ++i) {
  5264. BcResult *arg;
  5265. BcStatus s;
  5266. bool arr;
  5267. a = bc_vec_item(&func->autos, nparams - 1 - i);
  5268. arg = bc_vec_top(&G.prog.results);
  5269. arr = (a->idx == BC_TYPE_ARRAY || a->idx == BC_TYPE_REF);
  5270. if (arr != (arg->t == XC_RESULT_ARRAY) // array/variable mismatch
  5271. // || arg->t == XC_RESULT_STR - impossible, f("str") is not a legal syntax (strings are not bc expressions)
  5272. ) {
  5273. RETURN_STATUS(bc_error_variable_is_wrong_type());
  5274. }
  5275. s = zxc_program_popResultAndCopyToVar(a->name, (BcType) a->idx);
  5276. if (s) RETURN_STATUS(s);
  5277. }
  5278. a = bc_vec_item(&func->autos, i);
  5279. for (; i < func->autos.len; i++, a++) {
  5280. BcVec *v;
  5281. v = xc_program_search(a->name, (BcType) a->idx);
  5282. if (a->idx == BC_TYPE_VAR) {
  5283. BcNum n2;
  5284. bc_num_init_DEF_SIZE(&n2);
  5285. bc_vec_push(v, &n2);
  5286. } else {
  5287. //assert(a->idx == BC_TYPE_ARRAY);
  5288. BcVec v2;
  5289. bc_array_init(&v2, true);
  5290. bc_vec_push(v, &v2);
  5291. }
  5292. }
  5293. bc_vec_push(&G.prog.exestack, &ip);
  5294. RETURN_STATUS(BC_STATUS_SUCCESS);
  5295. }
  5296. #define zbc_program_call(...) (zbc_program_call(__VA_ARGS__) COMMA_SUCCESS)
  5297. static BC_STATUS zbc_program_return(char inst)
  5298. {
  5299. BcResult res;
  5300. BcFunc *f;
  5301. BcId *a;
  5302. size_t i;
  5303. BcInstPtr *ip = bc_vec_top(&G.prog.exestack);
  5304. f = xc_program_func(ip->func);
  5305. res.t = XC_RESULT_TEMP;
  5306. if (inst == XC_INST_RET) {
  5307. // bc needs this for e.g. RESULT_CONSTANT ("return 5")
  5308. // because bc constants are per-function.
  5309. // TODO: maybe avoid if value is already RESULT_TEMP?
  5310. BcStatus s;
  5311. BcNum *num;
  5312. BcResult *operand = bc_vec_top(&G.prog.results);
  5313. s = zxc_program_num(operand, &num);
  5314. if (s) RETURN_STATUS(s);
  5315. bc_num_init(&res.d.n, num->len);
  5316. bc_num_copy(&res.d.n, num);
  5317. bc_vec_pop(&G.prog.results);
  5318. } else {
  5319. if (f->voidfunc)
  5320. res.t = BC_RESULT_VOID;
  5321. bc_num_init_DEF_SIZE(&res.d.n);
  5322. //bc_num_zero(&res.d.n); - already is
  5323. }
  5324. bc_vec_push(&G.prog.results, &res);
  5325. bc_vec_pop(&G.prog.exestack);
  5326. // We need to pop arguments as well, so this takes that into account.
  5327. a = (void*)f->autos.v;
  5328. for (i = 0; i < f->autos.len; i++, a++) {
  5329. BcVec *v;
  5330. v = xc_program_search(a->name, (BcType) a->idx);
  5331. bc_vec_pop(v);
  5332. }
  5333. RETURN_STATUS(BC_STATUS_SUCCESS);
  5334. }
  5335. #define zbc_program_return(...) (zbc_program_return(__VA_ARGS__) COMMA_SUCCESS)
  5336. #endif // ENABLE_BC
  5337. static unsigned long xc_program_scale(BcNum *n)
  5338. {
  5339. return (unsigned long) n->rdx;
  5340. }
  5341. static unsigned long xc_program_len(BcNum *n)
  5342. {
  5343. size_t len = n->len;
  5344. if (n->rdx != len) return len;
  5345. for (;;) {
  5346. if (len == 0) break;
  5347. len--;
  5348. if (n->num[len] != 0) break;
  5349. }
  5350. return len;
  5351. }
  5352. static BC_STATUS zxc_program_builtin(char inst)
  5353. {
  5354. BcStatus s;
  5355. BcResult *opnd;
  5356. BcNum *num;
  5357. BcResult res;
  5358. bool len = (inst == XC_INST_LENGTH);
  5359. if (!STACK_HAS_MORE_THAN(&G.prog.results, 0))
  5360. RETURN_STATUS(bc_error_stack_has_too_few_elements());
  5361. opnd = bc_vec_top(&G.prog.results);
  5362. s = zxc_program_num(opnd, &num);
  5363. if (s) RETURN_STATUS(s);
  5364. #if ENABLE_DC
  5365. if (!BC_PROG_NUM(opnd, num) && !len)
  5366. RETURN_STATUS(bc_error_variable_is_wrong_type());
  5367. #endif
  5368. bc_num_init_DEF_SIZE(&res.d.n);
  5369. if (inst == XC_INST_SQRT)
  5370. s = zbc_num_sqrt(num, &res.d.n, G.prog.scale);
  5371. #if ENABLE_BC
  5372. else if (len != 0 && opnd->t == XC_RESULT_ARRAY) {
  5373. bc_num_ulong2num(&res.d.n, (unsigned long) ((BcVec *) num)->len);
  5374. }
  5375. #endif
  5376. #if ENABLE_DC
  5377. else if (len != 0 && !BC_PROG_NUM(opnd, num)) {
  5378. char **str;
  5379. size_t idx = opnd->t == XC_RESULT_STR ? opnd->d.id.idx : num->rdx;
  5380. str = xc_program_str(idx);
  5381. bc_num_ulong2num(&res.d.n, strlen(*str));
  5382. }
  5383. #endif
  5384. else {
  5385. bc_num_ulong2num(&res.d.n, len ? xc_program_len(num) : xc_program_scale(num));
  5386. }
  5387. xc_program_retire(&res, XC_RESULT_TEMP);
  5388. RETURN_STATUS(s);
  5389. }
  5390. #define zxc_program_builtin(...) (zxc_program_builtin(__VA_ARGS__) COMMA_SUCCESS)
  5391. #if ENABLE_DC
  5392. static BC_STATUS zdc_program_divmod(void)
  5393. {
  5394. BcStatus s;
  5395. BcResult *opd1, *opd2, res, res2;
  5396. BcNum *n1, *n2;
  5397. s = zxc_program_binOpPrep(&opd1, &n1, &opd2, &n2, false);
  5398. if (s) RETURN_STATUS(s);
  5399. bc_num_init_DEF_SIZE(&res.d.n);
  5400. bc_num_init(&res2.d.n, n2->len);
  5401. s = zbc_num_divmod(n1, n2, &res2.d.n, &res.d.n, G.prog.scale);
  5402. if (s) goto err;
  5403. xc_program_binOpRetire(&res2);
  5404. res.t = XC_RESULT_TEMP;
  5405. bc_vec_push(&G.prog.results, &res);
  5406. RETURN_STATUS(s);
  5407. err:
  5408. bc_num_free(&res2.d.n);
  5409. bc_num_free(&res.d.n);
  5410. RETURN_STATUS(s);
  5411. }
  5412. #define zdc_program_divmod(...) (zdc_program_divmod(__VA_ARGS__) COMMA_SUCCESS)
  5413. static BC_STATUS zdc_program_modexp(void)
  5414. {
  5415. BcStatus s;
  5416. BcResult *r1, *r2, *r3, res;
  5417. BcNum *n1, *n2, *n3;
  5418. if (!STACK_HAS_MORE_THAN(&G.prog.results, 2))
  5419. RETURN_STATUS(bc_error_stack_has_too_few_elements());
  5420. s = zxc_program_binOpPrep(&r2, &n2, &r3, &n3, false);
  5421. if (s) RETURN_STATUS(s);
  5422. r1 = bc_vec_item_rev(&G.prog.results, 2);
  5423. s = zxc_program_num(r1, &n1);
  5424. if (s) RETURN_STATUS(s);
  5425. if (!BC_PROG_NUM(r1, n1))
  5426. RETURN_STATUS(bc_error_variable_is_wrong_type());
  5427. // Make sure that the values have their pointers updated, if necessary.
  5428. if (r1->t == XC_RESULT_VAR || r1->t == XC_RESULT_ARRAY_ELEM) {
  5429. if (r1->t == r2->t) {
  5430. s = zxc_program_num(r2, &n2);
  5431. if (s) RETURN_STATUS(s);
  5432. }
  5433. if (r1->t == r3->t) {
  5434. s = zxc_program_num(r3, &n3);
  5435. if (s) RETURN_STATUS(s);
  5436. }
  5437. }
  5438. bc_num_init(&res.d.n, n3->len);
  5439. s = zdc_num_modexp(n1, n2, n3, &res.d.n);
  5440. if (s) goto err;
  5441. bc_vec_pop(&G.prog.results);
  5442. xc_program_binOpRetire(&res);
  5443. RETURN_STATUS(s);
  5444. err:
  5445. bc_num_free(&res.d.n);
  5446. RETURN_STATUS(s);
  5447. }
  5448. #define zdc_program_modexp(...) (zdc_program_modexp(__VA_ARGS__) COMMA_SUCCESS)
  5449. static void dc_program_stackLen(void)
  5450. {
  5451. BcResult res;
  5452. size_t len = G.prog.results.len;
  5453. res.t = XC_RESULT_TEMP;
  5454. bc_num_init_DEF_SIZE(&res.d.n);
  5455. bc_num_ulong2num(&res.d.n, len);
  5456. bc_vec_push(&G.prog.results, &res);
  5457. }
  5458. static BC_STATUS zdc_program_asciify(void)
  5459. {
  5460. BcStatus s;
  5461. BcResult *r, res;
  5462. BcNum *num, n;
  5463. char **strs;
  5464. char *str;
  5465. char c;
  5466. size_t idx;
  5467. if (!STACK_HAS_MORE_THAN(&G.prog.results, 0))
  5468. RETURN_STATUS(bc_error_stack_has_too_few_elements());
  5469. r = bc_vec_top(&G.prog.results);
  5470. s = zxc_program_num(r, &num);
  5471. if (s) RETURN_STATUS(s);
  5472. if (BC_PROG_NUM(r, num)) {
  5473. unsigned long val;
  5474. BcNum strmb;
  5475. BcDig strmb_digs[ULONG_NUM_BUFSIZE];
  5476. bc_num_init_DEF_SIZE(&n);
  5477. bc_num_copy(&n, num);
  5478. bc_num_truncate(&n, n.rdx);
  5479. strmb.cap = ARRAY_SIZE(strmb_digs);
  5480. strmb.num = strmb_digs;
  5481. bc_num_ulong2num(&strmb, 0x100);
  5482. s = zbc_num_mod(&n, &strmb, &n, 0);
  5483. if (s) goto num_err;
  5484. s = zbc_num_ulong(&n, &val);
  5485. if (s) goto num_err;
  5486. c = (char) val;
  5487. bc_num_free(&n);
  5488. } else {
  5489. char *sp;
  5490. idx = (r->t == XC_RESULT_STR) ? r->d.id.idx : num->rdx;
  5491. sp = *xc_program_str(idx);
  5492. c = sp[0];
  5493. }
  5494. strs = (void*)G.prog.strs.v;
  5495. for (idx = 0; idx < G.prog.strs.len; idx++) {
  5496. if (strs[idx][0] == c && strs[idx][1] == '\0') {
  5497. goto dup;
  5498. }
  5499. }
  5500. str = xzalloc(2);
  5501. str[0] = c;
  5502. //str[1] = '\0'; - already is
  5503. idx = bc_vec_push(&G.prog.strs, &str);
  5504. // Add an empty function so that if zdc_program_execStr ever needs to
  5505. // parse the string into code (from the 'x' command) there's somewhere
  5506. // to store the bytecode.
  5507. xc_program_add_fn();
  5508. dup:
  5509. res.t = XC_RESULT_STR;
  5510. res.d.id.idx = idx;
  5511. bc_result_pop_and_push(&res);
  5512. RETURN_STATUS(BC_STATUS_SUCCESS);
  5513. num_err:
  5514. bc_num_free(&n);
  5515. RETURN_STATUS(s);
  5516. }
  5517. #define zdc_program_asciify(...) (zdc_program_asciify(__VA_ARGS__) COMMA_SUCCESS)
  5518. static BC_STATUS zdc_program_printStream(void)
  5519. {
  5520. BcStatus s;
  5521. BcResult *r;
  5522. BcNum *n;
  5523. size_t idx;
  5524. if (!STACK_HAS_MORE_THAN(&G.prog.results, 0))
  5525. RETURN_STATUS(bc_error_stack_has_too_few_elements());
  5526. r = bc_vec_top(&G.prog.results);
  5527. s = zxc_program_num(r, &n);
  5528. if (s) RETURN_STATUS(s);
  5529. if (BC_PROG_NUM(r, n)) {
  5530. s = zxc_num_printNum(n, 0x100, 1, dc_num_printChar);
  5531. } else {
  5532. char *str;
  5533. idx = (r->t == XC_RESULT_STR) ? r->d.id.idx : n->rdx;
  5534. str = *xc_program_str(idx);
  5535. fputs(str, stdout);
  5536. }
  5537. RETURN_STATUS(s);
  5538. }
  5539. #define zdc_program_printStream(...) (zdc_program_printStream(__VA_ARGS__) COMMA_SUCCESS)
  5540. static BC_STATUS zdc_program_nquit(void)
  5541. {
  5542. BcStatus s;
  5543. BcResult *opnd;
  5544. BcNum *num;
  5545. unsigned long val;
  5546. s = zxc_program_prep(&opnd, &num);
  5547. if (s) RETURN_STATUS(s);
  5548. s = zbc_num_ulong(num, &val);
  5549. if (s) RETURN_STATUS(s);
  5550. bc_vec_pop(&G.prog.results);
  5551. if (G.prog.exestack.len < val)
  5552. RETURN_STATUS(bc_error_stack_has_too_few_elements());
  5553. if (G.prog.exestack.len == val) {
  5554. QUIT_OR_RETURN_TO_MAIN;
  5555. }
  5556. bc_vec_npop(&G.prog.exestack, val);
  5557. RETURN_STATUS(s);
  5558. }
  5559. #define zdc_program_nquit(...) (zdc_program_nquit(__VA_ARGS__) COMMA_SUCCESS)
  5560. static BC_STATUS zdc_program_execStr(char *code, size_t *bgn, bool cond)
  5561. {
  5562. BcStatus s = BC_STATUS_SUCCESS;
  5563. BcResult *r;
  5564. BcFunc *f;
  5565. BcInstPtr ip;
  5566. size_t fidx, sidx;
  5567. if (!STACK_HAS_MORE_THAN(&G.prog.results, 0))
  5568. RETURN_STATUS(bc_error_stack_has_too_few_elements());
  5569. r = bc_vec_top(&G.prog.results);
  5570. if (cond) {
  5571. BcNum *n = n; // for compiler
  5572. bool exec;
  5573. char *name;
  5574. char *then_name = xc_program_name(code, bgn);
  5575. char *else_name = NULL;
  5576. if (code[*bgn] == '\0')
  5577. (*bgn) += 1;
  5578. else
  5579. else_name = xc_program_name(code, bgn);
  5580. exec = r->d.n.len != 0;
  5581. name = then_name;
  5582. if (!exec && else_name != NULL) {
  5583. exec = true;
  5584. name = else_name;
  5585. }
  5586. if (exec) {
  5587. BcVec *v;
  5588. v = xc_program_search(name, BC_TYPE_VAR);
  5589. n = bc_vec_top(v);
  5590. }
  5591. free(then_name);
  5592. free(else_name);
  5593. if (!exec) goto exit;
  5594. if (!BC_PROG_STR(n)) {
  5595. s = bc_error_variable_is_wrong_type();
  5596. goto exit;
  5597. }
  5598. sidx = n->rdx;
  5599. } else {
  5600. if (r->t == XC_RESULT_STR) {
  5601. sidx = r->d.id.idx;
  5602. } else if (r->t == XC_RESULT_VAR) {
  5603. BcNum *n;
  5604. s = zxc_program_num(r, &n);
  5605. if (s || !BC_PROG_STR(n)) goto exit;
  5606. sidx = n->rdx;
  5607. } else
  5608. goto exit_nopop;
  5609. }
  5610. fidx = sidx + BC_PROG_REQ_FUNCS;
  5611. f = xc_program_func(fidx);
  5612. if (f->code.len == 0) {
  5613. BcParse sv_parse;
  5614. char *str;
  5615. sv_parse = G.prs; // struct copy
  5616. xc_parse_create(fidx);
  5617. str = *xc_program_str(sidx);
  5618. s = zxc_parse_text_init(str);
  5619. if (s) goto err;
  5620. s = zdc_parse_exprs_until_eof();
  5621. if (s) goto err;
  5622. xc_parse_push(DC_INST_POP_EXEC);
  5623. if (G.prs.lex != XC_LEX_EOF)
  5624. s = bc_error_bad_expression();
  5625. xc_parse_free();
  5626. G.prs = sv_parse; // struct copy
  5627. if (s) {
  5628. err:
  5629. bc_vec_pop_all(&f->code);
  5630. goto exit;
  5631. }
  5632. }
  5633. ip.inst_idx = 0;
  5634. ip.func = fidx;
  5635. bc_vec_pop(&G.prog.results);
  5636. bc_vec_push(&G.prog.exestack, &ip);
  5637. RETURN_STATUS(BC_STATUS_SUCCESS);
  5638. exit:
  5639. bc_vec_pop(&G.prog.results);
  5640. exit_nopop:
  5641. RETURN_STATUS(s);
  5642. }
  5643. #define zdc_program_execStr(...) (zdc_program_execStr(__VA_ARGS__) COMMA_SUCCESS)
  5644. #endif // ENABLE_DC
  5645. static void xc_program_pushGlobal(char inst)
  5646. {
  5647. BcResult res;
  5648. unsigned long val;
  5649. res.t = inst - XC_INST_IBASE + XC_RESULT_IBASE;
  5650. if (inst == XC_INST_IBASE)
  5651. val = (unsigned long) G.prog.ib_t;
  5652. else if (inst == XC_INST_SCALE)
  5653. val = (unsigned long) G.prog.scale;
  5654. else
  5655. val = (unsigned long) G.prog.ob_t;
  5656. bc_num_init_DEF_SIZE(&res.d.n);
  5657. bc_num_ulong2num(&res.d.n, val);
  5658. bc_vec_push(&G.prog.results, &res);
  5659. }
  5660. static BC_STATUS zxc_program_exec(void)
  5661. {
  5662. BcResult r, *ptr;
  5663. BcInstPtr *ip = bc_vec_top(&G.prog.exestack);
  5664. BcFunc *func = xc_program_func(ip->func);
  5665. char *code = func->code.v;
  5666. dbg_exec("func:%zd bytes:%zd ip:%zd results.len:%d",
  5667. ip->func, func->code.len, ip->inst_idx, G.prog.results.len);
  5668. while (ip->inst_idx < func->code.len) {
  5669. BcStatus s = BC_STATUS_SUCCESS;
  5670. char inst = code[ip->inst_idx++];
  5671. dbg_exec("inst at %zd:%d results.len:%d", ip->inst_idx - 1, inst, G.prog.results.len);
  5672. switch (inst) {
  5673. case XC_INST_RET:
  5674. if (IS_DC) { // end of '?' reached
  5675. bc_vec_pop(&G.prog.exestack);
  5676. goto read_updated_ip;
  5677. }
  5678. // bc: fall through
  5679. #if ENABLE_BC
  5680. case BC_INST_RET0:
  5681. dbg_exec("BC_INST_RET[0]:");
  5682. s = zbc_program_return(inst);
  5683. goto read_updated_ip;
  5684. case BC_INST_JUMP_ZERO: {
  5685. BcNum *num;
  5686. bool zero;
  5687. dbg_exec("BC_INST_JUMP_ZERO:");
  5688. s = zxc_program_prep(&ptr, &num);
  5689. if (s) RETURN_STATUS(s);
  5690. zero = (bc_num_cmp(num, &G.prog.zero) == 0);
  5691. bc_vec_pop(&G.prog.results);
  5692. if (!zero) {
  5693. xc_program_index(code, &ip->inst_idx);
  5694. break;
  5695. }
  5696. // else: fall through
  5697. }
  5698. case BC_INST_JUMP: {
  5699. size_t idx = xc_program_index(code, &ip->inst_idx);
  5700. size_t *addr = bc_vec_item(&func->labels, idx);
  5701. dbg_exec("BC_INST_JUMP: to %ld", (long)*addr);
  5702. ip->inst_idx = *addr;
  5703. break;
  5704. }
  5705. case BC_INST_CALL:
  5706. dbg_exec("BC_INST_CALL:");
  5707. s = zbc_program_call(code, &ip->inst_idx);
  5708. goto read_updated_ip;
  5709. case BC_INST_INC_PRE:
  5710. case BC_INST_DEC_PRE:
  5711. case BC_INST_INC_POST:
  5712. case BC_INST_DEC_POST:
  5713. dbg_exec("BC_INST_INCDEC:");
  5714. s = zbc_program_incdec(inst);
  5715. break;
  5716. case BC_INST_HALT:
  5717. dbg_exec("BC_INST_HALT:");
  5718. QUIT_OR_RETURN_TO_MAIN;
  5719. break;
  5720. case XC_INST_BOOL_OR:
  5721. case XC_INST_BOOL_AND:
  5722. #endif // ENABLE_BC
  5723. case XC_INST_REL_EQ:
  5724. case XC_INST_REL_LE:
  5725. case XC_INST_REL_GE:
  5726. case XC_INST_REL_NE:
  5727. case XC_INST_REL_LT:
  5728. case XC_INST_REL_GT:
  5729. dbg_exec("BC_INST_BOOL:");
  5730. s = zxc_program_logical(inst);
  5731. break;
  5732. case XC_INST_READ:
  5733. dbg_exec("XC_INST_READ:");
  5734. s = zxc_program_read();
  5735. goto read_updated_ip;
  5736. case XC_INST_VAR:
  5737. dbg_exec("XC_INST_VAR:");
  5738. s = zxc_program_pushVar(code, &ip->inst_idx, false, false);
  5739. break;
  5740. case XC_INST_ARRAY_ELEM:
  5741. case XC_INST_ARRAY:
  5742. dbg_exec("XC_INST_ARRAY[_ELEM]:");
  5743. s = zbc_program_pushArray(code, &ip->inst_idx, inst);
  5744. break;
  5745. #if ENABLE_BC
  5746. case BC_INST_LAST:
  5747. dbg_exec("BC_INST_LAST:");
  5748. r.t = BC_RESULT_LAST;
  5749. bc_vec_push(&G.prog.results, &r);
  5750. break;
  5751. #endif
  5752. case XC_INST_IBASE:
  5753. case XC_INST_OBASE:
  5754. case XC_INST_SCALE:
  5755. dbg_exec("XC_INST_internalvar(%d):", inst - XC_INST_IBASE);
  5756. xc_program_pushGlobal(inst);
  5757. break;
  5758. case XC_INST_SCALE_FUNC:
  5759. case XC_INST_LENGTH:
  5760. case XC_INST_SQRT:
  5761. dbg_exec("BC_INST_builtin:");
  5762. s = zxc_program_builtin(inst);
  5763. break;
  5764. case XC_INST_NUM:
  5765. dbg_exec("XC_INST_NUM:");
  5766. r.t = XC_RESULT_CONSTANT;
  5767. r.d.id.idx = xc_program_index(code, &ip->inst_idx);
  5768. bc_vec_push(&G.prog.results, &r);
  5769. break;
  5770. case XC_INST_POP:
  5771. dbg_exec("XC_INST_POP:");
  5772. if (!STACK_HAS_MORE_THAN(&G.prog.results, 0))
  5773. s = bc_error_stack_has_too_few_elements();
  5774. else
  5775. bc_vec_pop(&G.prog.results);
  5776. break;
  5777. case XC_INST_PRINT:
  5778. case XC_INST_PRINT_POP:
  5779. case XC_INST_PRINT_STR:
  5780. dbg_exec("XC_INST_PRINTxyz(%d):", inst - XC_INST_PRINT);
  5781. s = zxc_program_print(inst, 0);
  5782. break;
  5783. case XC_INST_STR:
  5784. dbg_exec("XC_INST_STR:");
  5785. r.t = XC_RESULT_STR;
  5786. r.d.id.idx = xc_program_index(code, &ip->inst_idx);
  5787. bc_vec_push(&G.prog.results, &r);
  5788. break;
  5789. case XC_INST_POWER:
  5790. case XC_INST_MULTIPLY:
  5791. case XC_INST_DIVIDE:
  5792. case XC_INST_MODULUS:
  5793. case XC_INST_PLUS:
  5794. case XC_INST_MINUS:
  5795. dbg_exec("BC_INST_binaryop:");
  5796. s = zxc_program_op(inst);
  5797. break;
  5798. case XC_INST_BOOL_NOT: {
  5799. BcNum *num;
  5800. dbg_exec("XC_INST_BOOL_NOT:");
  5801. s = zxc_program_prep(&ptr, &num);
  5802. if (s) RETURN_STATUS(s);
  5803. bc_num_init_DEF_SIZE(&r.d.n);
  5804. if (bc_num_cmp(num, &G.prog.zero) == 0)
  5805. bc_num_one(&r.d.n);
  5806. //else bc_num_zero(&r.d.n); - already is
  5807. xc_program_retire(&r, XC_RESULT_TEMP);
  5808. break;
  5809. }
  5810. case XC_INST_NEG:
  5811. dbg_exec("XC_INST_NEG:");
  5812. s = zxc_program_negate();
  5813. break;
  5814. #if ENABLE_BC
  5815. case BC_INST_ASSIGN_POWER:
  5816. case BC_INST_ASSIGN_MULTIPLY:
  5817. case BC_INST_ASSIGN_DIVIDE:
  5818. case BC_INST_ASSIGN_MODULUS:
  5819. case BC_INST_ASSIGN_PLUS:
  5820. case BC_INST_ASSIGN_MINUS:
  5821. #endif
  5822. case XC_INST_ASSIGN:
  5823. dbg_exec("BC_INST_ASSIGNxyz:");
  5824. s = zxc_program_assign(inst);
  5825. break;
  5826. #if ENABLE_DC
  5827. case DC_INST_POP_EXEC:
  5828. dbg_exec("DC_INST_POP_EXEC:");
  5829. bc_vec_pop(&G.prog.exestack);
  5830. goto read_updated_ip;
  5831. case DC_INST_MODEXP:
  5832. dbg_exec("DC_INST_MODEXP:");
  5833. s = zdc_program_modexp();
  5834. break;
  5835. case DC_INST_DIVMOD:
  5836. dbg_exec("DC_INST_DIVMOD:");
  5837. s = zdc_program_divmod();
  5838. break;
  5839. case DC_INST_EXECUTE:
  5840. case DC_INST_EXEC_COND:
  5841. dbg_exec("DC_INST_EXEC[_COND]:");
  5842. s = zdc_program_execStr(code, &ip->inst_idx, inst == DC_INST_EXEC_COND);
  5843. goto read_updated_ip;
  5844. case DC_INST_PRINT_STACK: {
  5845. size_t idx;
  5846. dbg_exec("DC_INST_PRINT_STACK:");
  5847. for (idx = 0; idx < G.prog.results.len; ++idx) {
  5848. s = zxc_program_print(XC_INST_PRINT, idx);
  5849. if (s) break;
  5850. }
  5851. break;
  5852. }
  5853. case DC_INST_CLEAR_STACK:
  5854. dbg_exec("DC_INST_CLEAR_STACK:");
  5855. bc_vec_pop_all(&G.prog.results);
  5856. break;
  5857. case DC_INST_STACK_LEN:
  5858. dbg_exec("DC_INST_STACK_LEN:");
  5859. dc_program_stackLen();
  5860. break;
  5861. case DC_INST_DUPLICATE:
  5862. dbg_exec("DC_INST_DUPLICATE:");
  5863. if (!STACK_HAS_MORE_THAN(&G.prog.results, 0))
  5864. RETURN_STATUS(bc_error_stack_has_too_few_elements());
  5865. ptr = bc_vec_top(&G.prog.results);
  5866. dc_result_copy(&r, ptr);
  5867. bc_vec_push(&G.prog.results, &r);
  5868. break;
  5869. case DC_INST_SWAP: {
  5870. BcResult *ptr2;
  5871. dbg_exec("DC_INST_SWAP:");
  5872. if (!STACK_HAS_MORE_THAN(&G.prog.results, 1))
  5873. RETURN_STATUS(bc_error_stack_has_too_few_elements());
  5874. ptr = bc_vec_item_rev(&G.prog.results, 0);
  5875. ptr2 = bc_vec_item_rev(&G.prog.results, 1);
  5876. memcpy(&r, ptr, sizeof(BcResult));
  5877. memcpy(ptr, ptr2, sizeof(BcResult));
  5878. memcpy(ptr2, &r, sizeof(BcResult));
  5879. break;
  5880. }
  5881. case DC_INST_ASCIIFY:
  5882. dbg_exec("DC_INST_ASCIIFY:");
  5883. s = zdc_program_asciify();
  5884. break;
  5885. case DC_INST_PRINT_STREAM:
  5886. dbg_exec("DC_INST_PRINT_STREAM:");
  5887. s = zdc_program_printStream();
  5888. break;
  5889. case DC_INST_LOAD:
  5890. case DC_INST_PUSH_VAR: {
  5891. bool copy = inst == DC_INST_LOAD;
  5892. s = zxc_program_pushVar(code, &ip->inst_idx, true, copy);
  5893. break;
  5894. }
  5895. case DC_INST_PUSH_TO_VAR: {
  5896. char *name = xc_program_name(code, &ip->inst_idx);
  5897. s = zxc_program_popResultAndCopyToVar(name, BC_TYPE_VAR);
  5898. free(name);
  5899. break;
  5900. }
  5901. case DC_INST_QUIT:
  5902. dbg_exec("DC_INST_QUIT:");
  5903. if (G.prog.exestack.len <= 2)
  5904. QUIT_OR_RETURN_TO_MAIN;
  5905. bc_vec_npop(&G.prog.exestack, 2);
  5906. goto read_updated_ip;
  5907. case DC_INST_NQUIT:
  5908. dbg_exec("DC_INST_NQUIT:");
  5909. s = zdc_program_nquit();
  5910. //goto read_updated_ip; - just fall through to it
  5911. #endif // ENABLE_DC
  5912. read_updated_ip:
  5913. // Instruction stack has changed, read new pointers
  5914. ip = bc_vec_top(&G.prog.exestack);
  5915. func = xc_program_func(ip->func);
  5916. code = func->code.v;
  5917. dbg_exec("func:%zd bytes:%zd ip:%zd", ip->func, func->code.len, ip->inst_idx);
  5918. }
  5919. if (s || G_interrupt) {
  5920. xc_program_reset();
  5921. RETURN_STATUS(s);
  5922. }
  5923. fflush_and_check();
  5924. }
  5925. RETURN_STATUS(BC_STATUS_SUCCESS);
  5926. }
  5927. #define zxc_program_exec(...) (zxc_program_exec(__VA_ARGS__) COMMA_SUCCESS)
  5928. static unsigned xc_vm_envLen(const char *var)
  5929. {
  5930. char *lenv;
  5931. unsigned len;
  5932. lenv = getenv(var);
  5933. len = BC_NUM_PRINT_WIDTH;
  5934. if (!lenv) return len;
  5935. len = bb_strtou(lenv, NULL, 10) - 1;
  5936. if (errno || len < 2 || len >= INT_MAX)
  5937. len = BC_NUM_PRINT_WIDTH;
  5938. return len;
  5939. }
  5940. static BC_STATUS zxc_vm_process(const char *text)
  5941. {
  5942. BcStatus s;
  5943. dbg_lex_enter("%s:%d entered", __func__, __LINE__);
  5944. s = zxc_parse_text_init(text); // does the first zxc_lex_next()
  5945. if (s) RETURN_STATUS(s);
  5946. while (G.prs.lex != XC_LEX_EOF) {
  5947. BcInstPtr *ip;
  5948. BcFunc *f;
  5949. dbg_lex("%s:%d G.prs.lex:%d, parsing...", __func__, __LINE__, G.prs.lex);
  5950. if (IS_BC) {
  5951. #if ENABLE_BC
  5952. s = zbc_parse_stmt_or_funcdef();
  5953. if (s) goto err;
  5954. // Check that next token is a correct stmt delimiter -
  5955. // disallows "print 1 print 2" and such.
  5956. if (G.prs.lex != BC_LEX_SCOLON
  5957. && G.prs.lex != XC_LEX_NLINE
  5958. && G.prs.lex != XC_LEX_EOF
  5959. ) {
  5960. bc_error_at("bad statement terminator");
  5961. goto err;
  5962. }
  5963. // The above logic is fragile. Check these examples:
  5964. // - interactive read() still works
  5965. #endif
  5966. } else {
  5967. #if ENABLE_DC
  5968. s = zdc_parse_expr();
  5969. #endif
  5970. }
  5971. if (s || G_interrupt) {
  5972. err:
  5973. xc_parse_reset(); // includes xc_program_reset()
  5974. RETURN_STATUS(BC_STATUS_FAILURE);
  5975. }
  5976. dbg_lex("%s:%d executing...", __func__, __LINE__);
  5977. s = zxc_program_exec();
  5978. if (s) {
  5979. xc_program_reset();
  5980. break;
  5981. }
  5982. ip = (void*)G.prog.exestack.v;
  5983. #if SANITY_CHECKS
  5984. if (G.prog.exestack.len != 1) // should have only main's IP
  5985. bb_simple_error_msg_and_die("BUG:call stack");
  5986. if (ip->func != BC_PROG_MAIN)
  5987. bb_simple_error_msg_and_die("BUG:not MAIN");
  5988. #endif
  5989. f = xc_program_func_BC_PROG_MAIN();
  5990. // bc discards strings, constants and code after each
  5991. // top-level statement in the "main program".
  5992. // This prevents "yes 1 | bc" from growing its memory
  5993. // without bound. This can be done because data stack
  5994. // is empty and thus can't hold any references to
  5995. // strings or constants, there is no generated code
  5996. // which can hold references (after we discard one
  5997. // we just executed). Code of functions can have references,
  5998. // but bc stores function strings/constants in per-function
  5999. // storage.
  6000. if (IS_BC) {
  6001. #if SANITY_CHECKS
  6002. if (G.prog.results.len != 0) // should be empty
  6003. bb_simple_error_msg_and_die("BUG:data stack");
  6004. #endif
  6005. IF_BC(bc_vec_pop_all(&f->strs);)
  6006. IF_BC(bc_vec_pop_all(&f->consts);)
  6007. // We are at SCOLON/NLINE, skip it:
  6008. s = zxc_lex_next();
  6009. if (s) goto err;
  6010. } else {
  6011. if (G.prog.results.len == 0
  6012. && G.prog.vars.len == 0
  6013. ) {
  6014. // If stack is empty and no registers exist (TODO: or they are all empty),
  6015. // we can get rid of accumulated strings and constants.
  6016. // In this example dc process should not grow
  6017. // its memory consumption with time:
  6018. // yes 1pc | dc
  6019. IF_DC(bc_vec_pop_all(&G.prog.strs);)
  6020. IF_DC(bc_vec_pop_all(&G.prog.consts);)
  6021. }
  6022. // The code is discarded always (below), thus this example
  6023. // should also not grow its memory consumption with time,
  6024. // even though its data stack is not empty:
  6025. // { echo 1; yes dk; } | dc
  6026. }
  6027. // We drop generated and executed code for both bc and dc:
  6028. bc_vec_pop_all(&f->code);
  6029. ip->inst_idx = 0;
  6030. }
  6031. dbg_lex_done("%s:%d done", __func__, __LINE__);
  6032. RETURN_STATUS(s);
  6033. }
  6034. #define zxc_vm_process(...) (zxc_vm_process(__VA_ARGS__) COMMA_SUCCESS)
  6035. static BC_STATUS zxc_vm_execute_FILE(FILE *fp, const char *filename)
  6036. {
  6037. // So far bc/dc have no way to include a file from another file,
  6038. // therefore we know G.prs.lex_filename == NULL on entry
  6039. //const char *sv_file;
  6040. BcStatus s;
  6041. G.prs.lex_filename = filename;
  6042. G.prs.lex_input_fp = fp;
  6043. G.err_line = G.prs.lex_line = 1;
  6044. dbg_lex("p->lex_line reset to 1");
  6045. do {
  6046. s = zxc_vm_process("");
  6047. // We do not stop looping on errors here if reading stdin.
  6048. // Example: start interactive bc and enter "return".
  6049. // It should say "'return' not in a function"
  6050. // but should not exit.
  6051. } while (G.prs.lex_input_fp == stdin);
  6052. G.prs.lex_filename = NULL;
  6053. RETURN_STATUS(s);
  6054. }
  6055. #define zxc_vm_execute_FILE(...) (zxc_vm_execute_FILE(__VA_ARGS__) COMMA_SUCCESS)
  6056. static BC_STATUS zxc_vm_file(const char *file)
  6057. {
  6058. BcStatus s;
  6059. FILE *fp;
  6060. fp = xfopen_for_read(file);
  6061. s = zxc_vm_execute_FILE(fp, file);
  6062. fclose(fp);
  6063. RETURN_STATUS(s);
  6064. }
  6065. #define zxc_vm_file(...) (zxc_vm_file(__VA_ARGS__) COMMA_SUCCESS)
  6066. #if ENABLE_BC
  6067. static void bc_vm_info(void)
  6068. {
  6069. printf("%s "BB_VER"\n"
  6070. "Adapted from https://github.com/gavinhoward/bc\n"
  6071. "Original code (c) 2018 Gavin D. Howard and contributors\n"
  6072. , applet_name);
  6073. }
  6074. static void bc_args(char **argv)
  6075. {
  6076. unsigned opts;
  6077. int i;
  6078. GETOPT_RESET();
  6079. #if ENABLE_FEATURE_BC_LONG_OPTIONS
  6080. opts = option_mask32 |= getopt32long(argv, "wvsqli",
  6081. "warn\0" No_argument "w"
  6082. "version\0" No_argument "v"
  6083. "standard\0" No_argument "s"
  6084. "quiet\0" No_argument "q"
  6085. "mathlib\0" No_argument "l"
  6086. "interactive\0" No_argument "i"
  6087. );
  6088. #else
  6089. opts = option_mask32 |= getopt32(argv, "wvsqli");
  6090. #endif
  6091. if (getenv("POSIXLY_CORRECT"))
  6092. option_mask32 |= BC_FLAG_S;
  6093. if (opts & BC_FLAG_V) {
  6094. bc_vm_info();
  6095. exit(0);
  6096. }
  6097. for (i = optind; argv[i]; ++i)
  6098. bc_vec_push(&G.files, argv + i);
  6099. }
  6100. static void bc_vm_envArgs(void)
  6101. {
  6102. BcVec v;
  6103. char *buf;
  6104. char *env_args = getenv("BC_ENV_ARGS");
  6105. if (!env_args) return;
  6106. G.env_args = xstrdup(env_args);
  6107. buf = G.env_args;
  6108. bc_vec_init(&v, sizeof(char *), NULL);
  6109. while (*(buf = skip_whitespace(buf)) != '\0') {
  6110. bc_vec_push(&v, &buf);
  6111. buf = skip_non_whitespace(buf);
  6112. if (!*buf)
  6113. break;
  6114. *buf++ = '\0';
  6115. }
  6116. // NULL terminate, and pass argv[] so that first arg is argv[1]
  6117. if (sizeof(int) == sizeof(char*)) {
  6118. bc_vec_push(&v, &const_int_0);
  6119. } else {
  6120. static char *const nullptr = NULL;
  6121. bc_vec_push(&v, &nullptr);
  6122. }
  6123. bc_args(((char **)v.v) - 1);
  6124. bc_vec_free(&v);
  6125. }
  6126. static const char bc_lib[] ALIGN1 = {
  6127. "scale=20"
  6128. "\n" "define e(x){"
  6129. "\n" "auto b,s,n,r,d,i,p,f,v"
  6130. ////////////////"if(x<0)return(1/e(-x))" // and drop 'n' and x<0 logic below
  6131. //^^^^^^^^^^^^^^^^ this would work, and is even more precise than GNU bc:
  6132. //e(-.998896): GNU:.36828580434569428695
  6133. // above code:.36828580434569428696
  6134. // actual value:.3682858043456942869594...
  6135. // but for now let's be "GNU compatible"
  6136. "\n" "b=ibase"
  6137. "\n" "ibase=A"
  6138. "\n" "if(x<0){"
  6139. "\n" "n=1"
  6140. "\n" "x=-x"
  6141. "\n" "}"
  6142. "\n" "s=scale"
  6143. "\n" "r=6+s+.44*x"
  6144. "\n" "scale=scale(x)+1"
  6145. "\n" "while(x>1){"
  6146. "\n" "d+=1"
  6147. "\n" "x/=2"
  6148. "\n" "scale+=1"
  6149. "\n" "}"
  6150. "\n" "scale=r"
  6151. "\n" "r=x+1"
  6152. "\n" "p=x"
  6153. "\n" "f=v=1"
  6154. "\n" "for(i=2;v;++i){"
  6155. "\n" "p*=x"
  6156. "\n" "f*=i"
  6157. "\n" "v=p/f"
  6158. "\n" "r+=v"
  6159. "\n" "}"
  6160. "\n" "while(d--)r*=r"
  6161. "\n" "scale=s"
  6162. "\n" "ibase=b"
  6163. "\n" "if(n)return(1/r)"
  6164. "\n" "return(r/1)"
  6165. "\n" "}"
  6166. "\n" "define l(x){"
  6167. "\n" "auto b,s,r,p,a,q,i,v"
  6168. "\n" "b=ibase"
  6169. "\n" "ibase=A"
  6170. "\n" "if(x<=0){"
  6171. "\n" "r=(1-10^scale)/1"
  6172. "\n" "ibase=b"
  6173. "\n" "return(r)"
  6174. "\n" "}"
  6175. "\n" "s=scale"
  6176. "\n" "scale+=6"
  6177. "\n" "p=2"
  6178. "\n" "while(x>=2){"
  6179. "\n" "p*=2"
  6180. "\n" "x=sqrt(x)"
  6181. "\n" "}"
  6182. "\n" "while(x<=.5){"
  6183. "\n" "p*=2"
  6184. "\n" "x=sqrt(x)"
  6185. "\n" "}"
  6186. "\n" "r=a=(x-1)/(x+1)"
  6187. "\n" "q=a*a"
  6188. "\n" "v=1"
  6189. "\n" "for(i=3;v;i+=2){"
  6190. "\n" "a*=q"
  6191. "\n" "v=a/i"
  6192. "\n" "r+=v"
  6193. "\n" "}"
  6194. "\n" "r*=p"
  6195. "\n" "scale=s"
  6196. "\n" "ibase=b"
  6197. "\n" "return(r/1)"
  6198. "\n" "}"
  6199. "\n" "define s(x){"
  6200. "\n" "auto b,s,r,a,q,i"
  6201. "\n" "if(x<0)return(-s(-x))"
  6202. "\n" "b=ibase"
  6203. "\n" "ibase=A"
  6204. "\n" "s=scale"
  6205. "\n" "scale=1.1*s+2"
  6206. "\n" "a=a(1)"
  6207. "\n" "scale=0"
  6208. "\n" "q=(x/a+2)/4"
  6209. "\n" "x-=4*q*a"
  6210. "\n" "if(q%2)x=-x"
  6211. "\n" "scale=s+2"
  6212. "\n" "r=a=x"
  6213. "\n" "q=-x*x"
  6214. "\n" "for(i=3;a;i+=2){"
  6215. "\n" "a*=q/(i*(i-1))"
  6216. "\n" "r+=a"
  6217. "\n" "}"
  6218. "\n" "scale=s"
  6219. "\n" "ibase=b"
  6220. "\n" "return(r/1)"
  6221. "\n" "}"
  6222. "\n" "define c(x){"
  6223. "\n" "auto b,s"
  6224. "\n" "b=ibase"
  6225. "\n" "ibase=A"
  6226. "\n" "s=scale"
  6227. "\n" "scale*=1.2"
  6228. "\n" "x=s(2*a(1)+x)"
  6229. "\n" "scale=s"
  6230. "\n" "ibase=b"
  6231. "\n" "return(x/1)"
  6232. "\n" "}"
  6233. "\n" "define a(x){"
  6234. "\n" "auto b,s,r,n,a,m,t,f,i,u"
  6235. "\n" "b=ibase"
  6236. "\n" "ibase=A"
  6237. "\n" "n=1"
  6238. "\n" "if(x<0){"
  6239. "\n" "n=-1"
  6240. "\n" "x=-x"
  6241. "\n" "}"
  6242. "\n" "if(scale<65){"
  6243. "\n" "if(x==1)return(.7853981633974483096156608458198757210492923498437764552437361480/n)"
  6244. "\n" "if(x==.2)return(.1973955598498807583700497651947902934475851037878521015176889402/n)"
  6245. "\n" "}"
  6246. "\n" "s=scale"
  6247. "\n" "if(x>.2){"
  6248. "\n" "scale+=5"
  6249. "\n" "a=a(.2)"
  6250. "\n" "}"
  6251. "\n" "scale=s+3"
  6252. "\n" "while(x>.2){"
  6253. "\n" "m+=1"
  6254. "\n" "x=(x-.2)/(1+.2*x)"
  6255. "\n" "}"
  6256. "\n" "r=u=x"
  6257. "\n" "f=-x*x"
  6258. "\n" "t=1"
  6259. "\n" "for(i=3;t;i+=2){"
  6260. "\n" "u*=f"
  6261. "\n" "t=u/i"
  6262. "\n" "r+=t"
  6263. "\n" "}"
  6264. "\n" "scale=s"
  6265. "\n" "ibase=b"
  6266. "\n" "return((m*a+r)/n)"
  6267. "\n" "}"
  6268. "\n" "define j(n,x){"
  6269. "\n" "auto b,s,o,a,i,v,f"
  6270. "\n" "b=ibase"
  6271. "\n" "ibase=A"
  6272. "\n" "s=scale"
  6273. "\n" "scale=0"
  6274. "\n" "n/=1"
  6275. "\n" "if(n<0){"
  6276. "\n" "n=-n"
  6277. "\n" "o=n%2"
  6278. "\n" "}"
  6279. "\n" "a=1"
  6280. "\n" "for(i=2;i<=n;++i)a*=i"
  6281. "\n" "scale=1.5*s"
  6282. "\n" "a=(x^n)/2^n/a"
  6283. "\n" "r=v=1"
  6284. "\n" "f=-x*x/4"
  6285. "\n" "scale+=length(a)-scale(a)"
  6286. "\n" "for(i=1;v;++i){"
  6287. "\n" "v=v*f/i/(n+i)"
  6288. "\n" "r+=v"
  6289. "\n" "}"
  6290. "\n" "scale=s"
  6291. "\n" "ibase=b"
  6292. "\n" "if(o)a=-a"
  6293. "\n" "return(a*r/1)"
  6294. "\n" "}"
  6295. };
  6296. #endif // ENABLE_BC
  6297. static BC_STATUS zxc_vm_exec(void)
  6298. {
  6299. char **fname;
  6300. BcStatus s;
  6301. size_t i;
  6302. #if ENABLE_BC
  6303. if (option_mask32 & BC_FLAG_L) {
  6304. // We know that internal library is not buggy,
  6305. // thus error checking is normally disabled.
  6306. # define DEBUG_LIB 0
  6307. s = zxc_vm_process(bc_lib);
  6308. if (DEBUG_LIB && s) RETURN_STATUS(s);
  6309. }
  6310. #endif
  6311. s = BC_STATUS_SUCCESS;
  6312. fname = (void*)G.files.v;
  6313. for (i = 0; i < G.files.len; i++) {
  6314. s = zxc_vm_file(*fname++);
  6315. if (ENABLE_FEATURE_CLEAN_UP && !G_ttyin && s) {
  6316. // Debug config, non-interactive mode:
  6317. // return all the way back to main.
  6318. // Non-debug builds do not come here
  6319. // in non-interactive mode, they exit.
  6320. RETURN_STATUS(s);
  6321. }
  6322. }
  6323. if (IS_BC || (option_mask32 & BC_FLAG_I))
  6324. s = zxc_vm_execute_FILE(stdin, /*filename:*/ NULL);
  6325. RETURN_STATUS(s);
  6326. }
  6327. #define zxc_vm_exec(...) (zxc_vm_exec(__VA_ARGS__) COMMA_SUCCESS)
  6328. #if ENABLE_FEATURE_CLEAN_UP
  6329. static void xc_program_free(void)
  6330. {
  6331. bc_vec_free(&G.prog.fns);
  6332. IF_BC(bc_vec_free(&G.prog.fn_map);)
  6333. bc_vec_free(&G.prog.vars);
  6334. bc_vec_free(&G.prog.var_map);
  6335. bc_vec_free(&G.prog.arrs);
  6336. bc_vec_free(&G.prog.arr_map);
  6337. IF_DC(bc_vec_free(&G.prog.strs);)
  6338. IF_DC(bc_vec_free(&G.prog.consts);)
  6339. bc_vec_free(&G.prog.results);
  6340. bc_vec_free(&G.prog.exestack);
  6341. IF_BC(bc_num_free(&G.prog.last);)
  6342. //IF_BC(bc_num_free(&G.prog.zero);)
  6343. IF_BC(bc_num_free(&G.prog.one);)
  6344. bc_vec_free(&G.input_buffer);
  6345. }
  6346. #endif
  6347. static void xc_program_init(void)
  6348. {
  6349. BcInstPtr ip;
  6350. // memset(&G.prog, 0, sizeof(G.prog)); - already is
  6351. memset(&ip, 0, sizeof(BcInstPtr));
  6352. // G.prog.nchars = G.prog.scale = 0; - already is
  6353. G.prog.ib_t = 10;
  6354. G.prog.ob_t = 10;
  6355. IF_BC(bc_num_init_DEF_SIZE(&G.prog.last);)
  6356. //IF_BC(bc_num_zero(&G.prog.last);) - already is
  6357. //bc_num_init_DEF_SIZE(&G.prog.zero); - not needed
  6358. //bc_num_zero(&G.prog.zero); - already is
  6359. IF_BC(bc_num_init_DEF_SIZE(&G.prog.one);)
  6360. IF_BC(bc_num_one(&G.prog.one);)
  6361. bc_vec_init(&G.prog.fns, sizeof(BcFunc), bc_func_free);
  6362. IF_BC(bc_vec_init(&G.prog.fn_map, sizeof(BcId), bc_id_free);)
  6363. if (IS_BC) {
  6364. // Names are chosen simply to be distinct and never match
  6365. // a valid function name (and be short)
  6366. IF_BC(bc_program_addFunc(xstrdup(""))); // func #0: main
  6367. IF_BC(bc_program_addFunc(xstrdup("1"))); // func #1: for read()
  6368. } else {
  6369. // in dc, functions have no names
  6370. xc_program_add_fn();
  6371. xc_program_add_fn();
  6372. }
  6373. bc_vec_init(&G.prog.vars, sizeof(BcVec), bc_vec_free);
  6374. bc_vec_init(&G.prog.var_map, sizeof(BcId), bc_id_free);
  6375. bc_vec_init(&G.prog.arrs, sizeof(BcVec), bc_vec_free);
  6376. bc_vec_init(&G.prog.arr_map, sizeof(BcId), bc_id_free);
  6377. IF_DC(bc_vec_init(&G.prog.strs, sizeof(char *), bc_string_free);)
  6378. IF_DC(bc_vec_init(&G.prog.consts, sizeof(char *), bc_string_free);)
  6379. bc_vec_init(&G.prog.results, sizeof(BcResult), bc_result_free);
  6380. bc_vec_init(&G.prog.exestack, sizeof(BcInstPtr), NULL);
  6381. bc_vec_push(&G.prog.exestack, &ip);
  6382. bc_char_vec_init(&G.input_buffer);
  6383. }
  6384. static int xc_vm_init(const char *env_len)
  6385. {
  6386. G.prog.len = xc_vm_envLen(env_len);
  6387. #if ENABLE_FEATURE_EDITING
  6388. G.line_input_state = new_line_input_t(DO_HISTORY);
  6389. #endif
  6390. bc_vec_init(&G.files, sizeof(char *), NULL);
  6391. xc_program_init();
  6392. IF_BC(if (IS_BC) bc_vm_envArgs();)
  6393. xc_parse_create(BC_PROG_MAIN);
  6394. //TODO: in GNU bc, the check is (isatty(0) && isatty(1)),
  6395. //-i option unconditionally enables this regardless of isatty():
  6396. if (isatty(0)) {
  6397. #if ENABLE_FEATURE_BC_INTERACTIVE
  6398. G_ttyin = 1;
  6399. // With SA_RESTART, most system calls will restart
  6400. // (IOW: they won't fail with EINTR).
  6401. // In particular, this means ^C won't cause
  6402. // stdout to get into "error state" if SIGINT hits
  6403. // within write() syscall.
  6404. //
  6405. // The downside is that ^C while tty input is taken
  6406. // will only be handled after [Enter] since read()
  6407. // from stdin is not interrupted by ^C either,
  6408. // it restarts, thus fgetc() does not return on ^C.
  6409. // (This problem manifests only if line editing is disabled)
  6410. signal_SA_RESTART_empty_mask(SIGINT, record_signo);
  6411. // Without SA_RESTART, this exhibits a bug:
  6412. // "while (1) print 1" and try ^C-ing it.
  6413. // Intermittently, instead of returning to input line,
  6414. // you'll get "output error: Interrupted system call"
  6415. // and exit.
  6416. //signal_no_SA_RESTART_empty_mask(SIGINT, record_signo);
  6417. #endif
  6418. return 1; // "tty"
  6419. }
  6420. return 0; // "not a tty"
  6421. }
  6422. static BcStatus xc_vm_run(void)
  6423. {
  6424. BcStatus st = zxc_vm_exec();
  6425. #if ENABLE_FEATURE_CLEAN_UP
  6426. if (G_exiting) // it was actually "halt" or "quit"
  6427. st = EXIT_SUCCESS;
  6428. bc_vec_free(&G.files);
  6429. xc_program_free();
  6430. xc_parse_free();
  6431. free(G.env_args);
  6432. # if ENABLE_FEATURE_EDITING
  6433. free_line_input_t(G.line_input_state);
  6434. # endif
  6435. FREE_G();
  6436. #endif
  6437. dbg_exec("exiting with exitcode %d", st);
  6438. return st;
  6439. }
  6440. #if ENABLE_BC
  6441. int bc_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  6442. int bc_main(int argc UNUSED_PARAM, char **argv)
  6443. {
  6444. int is_tty;
  6445. INIT_G();
  6446. is_tty = xc_vm_init("BC_LINE_LENGTH");
  6447. bc_args(argv);
  6448. if (is_tty && !(option_mask32 & BC_FLAG_Q))
  6449. bc_vm_info();
  6450. return xc_vm_run();
  6451. }
  6452. #endif
  6453. #if ENABLE_DC
  6454. int dc_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  6455. int dc_main(int argc UNUSED_PARAM, char **argv)
  6456. {
  6457. int noscript;
  6458. INIT_G();
  6459. // TODO: dc (GNU bc 1.07.1) 1.4.1 seems to use width
  6460. // 1 char wider than bc from the same package.
  6461. // Both default width, and xC_LINE_LENGTH=N are wider:
  6462. // "DC_LINE_LENGTH=5 dc -e'123456 p'" prints:
  6463. // |1234\ |
  6464. // |56 |
  6465. // "echo '123456' | BC_LINE_LENGTH=5 bc" prints:
  6466. // |123\ |
  6467. // |456 |
  6468. // Do the same, or it's a bug?
  6469. xc_vm_init("DC_LINE_LENGTH");
  6470. // Run -e'SCRIPT' and -fFILE in order of appearance, then handle FILEs
  6471. noscript = BC_FLAG_I;
  6472. for (;;) {
  6473. int n = getopt(argc, argv, "e:f:x");
  6474. if (n <= 0)
  6475. break;
  6476. switch (n) {
  6477. case 'e':
  6478. noscript = 0;
  6479. n = zxc_vm_process(optarg);
  6480. if (n) return n;
  6481. break;
  6482. case 'f':
  6483. noscript = 0;
  6484. n = zxc_vm_file(optarg);
  6485. if (n) return n;
  6486. break;
  6487. case 'x':
  6488. option_mask32 |= DC_FLAG_X;
  6489. break;
  6490. default:
  6491. bb_show_usage();
  6492. }
  6493. }
  6494. argv += optind;
  6495. while (*argv) {
  6496. noscript = 0;
  6497. bc_vec_push(&G.files, argv++);
  6498. }
  6499. option_mask32 |= noscript; // set BC_FLAG_I if we need to interpret stdin
  6500. return xc_vm_run();
  6501. }
  6502. #endif
  6503. #endif // DC_BIG