bc.c 186 KB

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