bc.c 181 KB

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