bc.c 182 KB

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