bc.c 186 KB

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