bc.c 185 KB

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