bc.c 182 KB

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